OutlineEffect.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /**
  2. * @author takahirox / http://github.com/takahirox/
  3. *
  4. * Reference: https://en.wikipedia.org/wiki/Cel_shading
  5. *
  6. * API
  7. *
  8. * 1. Traditional
  9. *
  10. * var effect = new OutlineEffect( renderer );
  11. *
  12. * function render() {
  13. *
  14. * effect.render( scene, camera );
  15. *
  16. * }
  17. *
  18. * 2. VR compatible
  19. *
  20. * var effect = new OutlineEffect( renderer );
  21. * var renderingOutline = false;
  22. *
  23. * scene.onAfterRender = function () {
  24. *
  25. * if ( renderingOutline ) return;
  26. *
  27. * renderingOutline = true;
  28. *
  29. * effect.renderOutline( scene, camera );
  30. *
  31. * renderingOutline = false;
  32. *
  33. * };
  34. *
  35. * function render() {
  36. *
  37. * renderer.render( scene, camera );
  38. *
  39. * }
  40. *
  41. * // How to set default outline parameters
  42. * new OutlineEffect( renderer, {
  43. * defaultThickness: 0.01,
  44. * defaultColor: [ 0, 0, 0 ],
  45. * defaultAlpha: 0.8,
  46. * defaultKeepAlive: true // keeps outline material in cache even if material is removed from scene
  47. * } );
  48. *
  49. * // How to set outline parameters for each material
  50. * material.userData.outlineParameters = {
  51. * thickness: 0.01,
  52. * color: [ 0, 0, 0 ]
  53. * alpha: 0.8,
  54. * visible: true,
  55. * keepAlive: true
  56. * };
  57. */
  58. import {
  59. BackSide,
  60. Color,
  61. ShaderMaterial,
  62. UniformsLib,
  63. UniformsUtils
  64. } from "../../../build/three.module.js";
  65. var OutlineEffect = function ( renderer, parameters ) {
  66. parameters = parameters || {};
  67. this.enabled = true;
  68. var defaultThickness = parameters.defaultThickness !== undefined ? parameters.defaultThickness : 0.003;
  69. var defaultColor = new Color().fromArray( parameters.defaultColor !== undefined ? parameters.defaultColor : [ 0, 0, 0 ] );
  70. var defaultAlpha = parameters.defaultAlpha !== undefined ? parameters.defaultAlpha : 1.0;
  71. var defaultKeepAlive = parameters.defaultKeepAlive !== undefined ? parameters.defaultKeepAlive : false;
  72. // object.material.uuid -> outlineMaterial or
  73. // object.material[ n ].uuid -> outlineMaterial
  74. // save at the outline material creation and release
  75. // if it's unused removeThresholdCount frames
  76. // unless keepAlive is true.
  77. var cache = {};
  78. var removeThresholdCount = 60;
  79. // outlineMaterial.uuid -> object.material or
  80. // outlineMaterial.uuid -> object.material[ n ]
  81. // save before render and release after render.
  82. var originalMaterials = {};
  83. // object.uuid -> originalOnBeforeRender
  84. // save before render and release after render.
  85. var originalOnBeforeRenders = {};
  86. //this.cache = cache; // for debug
  87. var uniformsOutline = {
  88. outlineThickness: { value: defaultThickness },
  89. outlineColor: { value: defaultColor },
  90. outlineAlpha: { value: defaultAlpha }
  91. };
  92. var vertexShader = [
  93. "#include <common>",
  94. "#include <uv_pars_vertex>",
  95. "#include <displacementmap_pars_vertex>",
  96. "#include <fog_pars_vertex>",
  97. "#include <morphtarget_pars_vertex>",
  98. "#include <skinning_pars_vertex>",
  99. "#include <logdepthbuf_pars_vertex>",
  100. "#include <clipping_planes_pars_vertex>",
  101. "uniform float outlineThickness;",
  102. "vec4 calculateOutline( vec4 pos, vec3 normal, vec4 skinned ) {",
  103. " float thickness = outlineThickness;",
  104. " const float ratio = 1.0;", // TODO: support outline thickness ratio for each vertex
  105. " vec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + normal, 1.0 );",
  106. // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  107. " vec4 norm = normalize( pos - pos2 );",
  108. " return pos + norm * thickness * pos.w * ratio;",
  109. "}",
  110. "void main() {",
  111. " #include <uv_vertex>",
  112. " #include <beginnormal_vertex>",
  113. " #include <morphnormal_vertex>",
  114. " #include <skinbase_vertex>",
  115. " #include <skinnormal_vertex>",
  116. " #include <begin_vertex>",
  117. " #include <morphtarget_vertex>",
  118. " #include <skinning_vertex>",
  119. " #include <displacementmap_vertex>",
  120. " #include <project_vertex>",
  121. " vec3 outlineNormal = - objectNormal;", // the outline material is always rendered with BackSide
  122. " gl_Position = calculateOutline( gl_Position, outlineNormal, vec4( transformed, 1.0 ) );",
  123. " #include <logdepthbuf_vertex>",
  124. " #include <clipping_planes_vertex>",
  125. " #include <fog_vertex>",
  126. "}",
  127. ].join( "\n" );
  128. var fragmentShader = [
  129. "#include <common>",
  130. "#include <fog_pars_fragment>",
  131. "#include <logdepthbuf_pars_fragment>",
  132. "#include <clipping_planes_pars_fragment>",
  133. "uniform vec3 outlineColor;",
  134. "uniform float outlineAlpha;",
  135. "void main() {",
  136. " #include <clipping_planes_fragment>",
  137. " #include <logdepthbuf_fragment>",
  138. " gl_FragColor = vec4( outlineColor, outlineAlpha );",
  139. " #include <tonemapping_fragment>",
  140. " #include <encodings_fragment>",
  141. " #include <fog_fragment>",
  142. " #include <premultiplied_alpha_fragment>",
  143. "}"
  144. ].join( "\n" );
  145. function createMaterial() {
  146. return new ShaderMaterial( {
  147. type: 'OutlineEffect',
  148. uniforms: UniformsUtils.merge( [
  149. UniformsLib[ 'fog' ],
  150. UniformsLib[ 'displacementmap' ],
  151. uniformsOutline
  152. ] ),
  153. vertexShader: vertexShader,
  154. fragmentShader: fragmentShader,
  155. side: BackSide
  156. } );
  157. }
  158. function getOutlineMaterialFromCache( originalMaterial ) {
  159. var data = cache[ originalMaterial.uuid ];
  160. if ( data === undefined ) {
  161. data = {
  162. material: createMaterial(),
  163. used: true,
  164. keepAlive: defaultKeepAlive,
  165. count: 0
  166. };
  167. cache[ originalMaterial.uuid ] = data;
  168. }
  169. data.used = true;
  170. return data.material;
  171. }
  172. function getOutlineMaterial( originalMaterial ) {
  173. var outlineMaterial = getOutlineMaterialFromCache( originalMaterial );
  174. originalMaterials[ outlineMaterial.uuid ] = originalMaterial;
  175. updateOutlineMaterial( outlineMaterial, originalMaterial );
  176. return outlineMaterial;
  177. }
  178. function isCompatible( object ) {
  179. var geometry = object.geometry;
  180. var hasNormals = false;
  181. if ( object.geometry !== undefined ) {
  182. if ( geometry.isBufferGeometry ) {
  183. hasNormals = geometry.attributes.normal !== undefined;
  184. } else {
  185. hasNormals = true; // the renderer always produces a normal attribute for Geometry
  186. }
  187. }
  188. return ( object.isMesh === true && object.material !== undefined && hasNormals === true );
  189. }
  190. function setOutlineMaterial( object ) {
  191. if ( isCompatible( object ) === false ) return;
  192. if ( Array.isArray( object.material ) ) {
  193. for ( var i = 0, il = object.material.length; i < il; i ++ ) {
  194. object.material[ i ] = getOutlineMaterial( object.material[ i ] );
  195. }
  196. } else {
  197. object.material = getOutlineMaterial( object.material );
  198. }
  199. originalOnBeforeRenders[ object.uuid ] = object.onBeforeRender;
  200. object.onBeforeRender = onBeforeRender;
  201. }
  202. function restoreOriginalMaterial( object ) {
  203. if ( isCompatible( object ) === false ) return;
  204. if ( Array.isArray( object.material ) ) {
  205. for ( var i = 0, il = object.material.length; i < il; i ++ ) {
  206. object.material[ i ] = originalMaterials[ object.material[ i ].uuid ];
  207. }
  208. } else {
  209. object.material = originalMaterials[ object.material.uuid ];
  210. }
  211. object.onBeforeRender = originalOnBeforeRenders[ object.uuid ];
  212. }
  213. function onBeforeRender( renderer, scene, camera, geometry, material ) {
  214. var originalMaterial = originalMaterials[ material.uuid ];
  215. // just in case
  216. if ( originalMaterial === undefined ) return;
  217. updateUniforms( material, originalMaterial );
  218. }
  219. function updateUniforms( material, originalMaterial ) {
  220. var outlineParameters = originalMaterial.userData.outlineParameters;
  221. material.uniforms.outlineAlpha.value = originalMaterial.opacity;
  222. if ( outlineParameters !== undefined ) {
  223. if ( outlineParameters.thickness !== undefined ) material.uniforms.outlineThickness.value = outlineParameters.thickness;
  224. if ( outlineParameters.color !== undefined ) material.uniforms.outlineColor.value.fromArray( outlineParameters.color );
  225. if ( outlineParameters.alpha !== undefined ) material.uniforms.outlineAlpha.value = outlineParameters.alpha;
  226. }
  227. if ( originalMaterial.displacementMap ) {
  228. material.uniforms.displacementMap.value = originalMaterial.displacementMap;
  229. material.uniforms.displacementScale.value = originalMaterial.displacementScale;
  230. material.uniforms.displacementBias.value = originalMaterial.displacementBias;
  231. }
  232. }
  233. function updateOutlineMaterial( material, originalMaterial ) {
  234. if ( material.name === 'invisible' ) return;
  235. var outlineParameters = originalMaterial.userData.outlineParameters;
  236. material.skinning = originalMaterial.skinning;
  237. material.morphTargets = originalMaterial.morphTargets;
  238. material.morphNormals = originalMaterial.morphNormals;
  239. material.fog = originalMaterial.fog;
  240. material.toneMapped = originalMaterial.toneMapped;
  241. material.premultipliedAlpha = originalMaterial.premultipliedAlpha;
  242. material.displacementMap = originalMaterial.displacementMap;
  243. if ( outlineParameters !== undefined ) {
  244. if ( originalMaterial.visible === false ) {
  245. material.visible = false;
  246. } else {
  247. material.visible = ( outlineParameters.visible !== undefined ) ? outlineParameters.visible : true;
  248. }
  249. material.transparent = ( outlineParameters.alpha !== undefined && outlineParameters.alpha < 1.0 ) ? true : originalMaterial.transparent;
  250. if ( outlineParameters.keepAlive !== undefined ) cache[ originalMaterial.uuid ].keepAlive = outlineParameters.keepAlive;
  251. } else {
  252. material.transparent = originalMaterial.transparent;
  253. material.visible = originalMaterial.visible;
  254. }
  255. if ( originalMaterial.wireframe === true || originalMaterial.depthTest === false ) material.visible = false;
  256. if ( originalMaterial.clippingPlanes ) {
  257. material.clipping = true;
  258. material.clippingPlanes = originalMaterial.clippingPlanes;
  259. material.clipIntersection = originalMaterial.clipIntersection;
  260. material.clipShadows = originalMaterial.clipShadows;
  261. }
  262. material.version = originalMaterial.version; // update outline material if necessary
  263. }
  264. function cleanupCache() {
  265. var keys;
  266. // clear originialMaterials
  267. keys = Object.keys( originalMaterials );
  268. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  269. originalMaterials[ keys[ i ] ] = undefined;
  270. }
  271. // clear originalOnBeforeRenders
  272. keys = Object.keys( originalOnBeforeRenders );
  273. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  274. originalOnBeforeRenders[ keys[ i ] ] = undefined;
  275. }
  276. // remove unused outlineMaterial from cache
  277. keys = Object.keys( cache );
  278. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  279. var key = keys[ i ];
  280. if ( cache[ key ].used === false ) {
  281. cache[ key ].count ++;
  282. if ( cache[ key ].keepAlive === false && cache[ key ].count > removeThresholdCount ) {
  283. delete cache[ key ];
  284. }
  285. } else {
  286. cache[ key ].used = false;
  287. cache[ key ].count = 0;
  288. }
  289. }
  290. }
  291. this.render = function ( scene, camera ) {
  292. var renderTarget;
  293. var forceClear = false;
  294. if ( arguments[ 2 ] !== undefined ) {
  295. console.warn( 'THREE.OutlineEffect.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  296. renderTarget = arguments[ 2 ];
  297. }
  298. if ( arguments[ 3 ] !== undefined ) {
  299. console.warn( 'THREE.OutlineEffect.render(): the forceClear argument has been removed. Use .clear() instead.' );
  300. forceClear = arguments[ 3 ];
  301. }
  302. if ( renderTarget !== undefined ) renderer.setRenderTarget( renderTarget );
  303. if ( forceClear ) renderer.clear();
  304. if ( this.enabled === false ) {
  305. renderer.render( scene, camera );
  306. return;
  307. }
  308. var currentAutoClear = renderer.autoClear;
  309. renderer.autoClear = this.autoClear;
  310. renderer.render( scene, camera );
  311. renderer.autoClear = currentAutoClear;
  312. this.renderOutline( scene, camera );
  313. };
  314. this.renderOutline = function ( scene, camera ) {
  315. var currentAutoClear = renderer.autoClear;
  316. var currentSceneAutoUpdate = scene.autoUpdate;
  317. var currentSceneBackground = scene.background;
  318. var currentShadowMapEnabled = renderer.shadowMap.enabled;
  319. scene.autoUpdate = false;
  320. scene.background = null;
  321. renderer.autoClear = false;
  322. renderer.shadowMap.enabled = false;
  323. scene.traverse( setOutlineMaterial );
  324. renderer.render( scene, camera );
  325. scene.traverse( restoreOriginalMaterial );
  326. cleanupCache();
  327. scene.autoUpdate = currentSceneAutoUpdate;
  328. scene.background = currentSceneBackground;
  329. renderer.autoClear = currentAutoClear;
  330. renderer.shadowMap.enabled = currentShadowMapEnabled;
  331. };
  332. /*
  333. * See #9918
  334. *
  335. * The following property copies and wrapper methods enable
  336. * OutlineEffect to be called from other *Effect, like
  337. *
  338. * effect = new StereoEffect( new OutlineEffect( renderer ) );
  339. *
  340. * function render () {
  341. *
  342. * effect.render( scene, camera );
  343. *
  344. * }
  345. */
  346. this.autoClear = renderer.autoClear;
  347. this.domElement = renderer.domElement;
  348. this.shadowMap = renderer.shadowMap;
  349. this.clear = function ( color, depth, stencil ) {
  350. renderer.clear( color, depth, stencil );
  351. };
  352. this.getPixelRatio = function () {
  353. return renderer.getPixelRatio();
  354. };
  355. this.setPixelRatio = function ( value ) {
  356. renderer.setPixelRatio( value );
  357. };
  358. this.getSize = function ( target ) {
  359. return renderer.getSize( target );
  360. };
  361. this.setSize = function ( width, height, updateStyle ) {
  362. renderer.setSize( width, height, updateStyle );
  363. };
  364. this.setViewport = function ( x, y, width, height ) {
  365. renderer.setViewport( x, y, width, height );
  366. };
  367. this.setScissor = function ( x, y, width, height ) {
  368. renderer.setScissor( x, y, width, height );
  369. };
  370. this.setScissorTest = function ( boolean ) {
  371. renderer.setScissorTest( boolean );
  372. };
  373. this.setRenderTarget = function ( renderTarget ) {
  374. renderer.setRenderTarget( renderTarget );
  375. };
  376. };
  377. export { OutlineEffect };