OutlineEffect.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /**
  2. * @author takahirox / http://github.com/takahirox/
  3. *
  4. * Reference: https://en.wikipedia.org/wiki/Cel_shading
  5. *
  6. * // How to set default outline parameters
  7. * new THREE.OutlineEffect( renderer, {
  8. * defaultThickNess: 0.01,
  9. * defaultColor: new THREE.Color( 0x888888 ),
  10. * defaultAlpha: 0.8,
  11. * defaultKeepAlive: true // keeps outline material in cache even if material is removed from scene
  12. * } );
  13. *
  14. * // How to set outline parameters for each material
  15. * material.outlineParameters = {
  16. * thickNess: 0.01, // this paremeter won't work for MultiMaterial
  17. * color: new THREE.Color( 0x888888 ), // this paremeter won't work for MultiMaterial
  18. * alpha: 0.8, // this paremeter won't work for MultiMaterial
  19. * visible: true,
  20. * keepAlive: true // this paremeter won't work for Material in materials of MultiMaterial
  21. * };
  22. *
  23. * TODO
  24. * - support shader material without objectNormal in its vertexShader
  25. */
  26. THREE.OutlineEffect = function ( renderer, parameters ) {
  27. parameters = parameters || {};
  28. this.enabled = true;
  29. var defaultThickness = parameters.defaultThickness !== undefined ? parameters.defaultThickness : 0.003;
  30. var defaultColor = parameters.defaultColor !== undefined ? parameters.defaultColor : new THREE.Color( 0x000000 );
  31. var defaultAlpha = parameters.defaultAlpha !== undefined ? parameters.defaultAlpha : 1.0;
  32. var defaultKeepAlive = parameters.defaultKeepAlive !== undefined ? parameters.defaultKeepAlive : false;
  33. // object.material.uuid -> outlineMaterial
  34. // (no mapping from children of MultiMaterial)
  35. // save at the outline material creation and release
  36. // if it's unused removeThresholdCount frames
  37. // unless keepAlive is true.
  38. var cache = {};
  39. var removeThresholdCount = 60;
  40. // outlineMaterial.uuid (or object.uuid for invisibleMaterial) -> originalMaterial
  41. // including children of MultiMaterial.
  42. // save before render and release after render.
  43. var originalMaterials = {};
  44. // object.uuid -> originalOnBeforeRender
  45. // save before render and release after render.
  46. var originalOnBeforeRenders = {};
  47. //this.cache = cache; // for debug
  48. var invisibleMaterial = new THREE.ShaderMaterial( { visible: false } );
  49. // copied from WebGLPrograms and removed some materials
  50. var shaderIDs = {
  51. MeshBasicMaterial: 'basic',
  52. MeshLambertMaterial: 'lambert',
  53. MeshPhongMaterial: 'phong',
  54. MeshToonMaterial: 'phong',
  55. MeshStandardMaterial: 'physical',
  56. MeshPhysicalMaterial: 'physical'
  57. };
  58. var uniformsChunk = {
  59. outlineThickness: { type: "f", value: defaultThickness },
  60. outlineColor: { type: "c", value: defaultColor },
  61. outlineAlpha: { type: "f", value: defaultAlpha }
  62. };
  63. var vertexShaderChunk = [
  64. "#include <fog_pars_vertex>",
  65. "uniform float outlineThickness;",
  66. "vec4 calculateOutline( vec4 pos, vec3 objectNormal, vec4 skinned ) {",
  67. " float thickness = outlineThickness;",
  68. " const float ratio = 1.0;", // TODO: support outline thickness ratio for each vertex
  69. " vec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + objectNormal, 1.0 );",
  70. // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  71. " vec4 norm = normalize( pos - pos2 );",
  72. " return pos + norm * thickness * pos.w * ratio;",
  73. "}"
  74. ].join( "\n" );
  75. var vertexShaderChunk2 = [
  76. "#if ! defined( LAMBERT ) && ! defined( PHONG ) && ! defined( TOON ) && ! defined( PHYSICAL )",
  77. " #ifndef USE_ENVMAP",
  78. " vec3 objectNormal = normalize( normal );",
  79. " #ifdef FLIP_SIDED",
  80. " objectNormal = -objectNormal;",
  81. " #endif",
  82. " #endif",
  83. "#endif",
  84. "#ifdef DECLARE_TRANSFORMED",
  85. " vec3 transformed = vec3( position );",
  86. "#endif",
  87. "#ifdef USE_SKINNING",
  88. " gl_Position = calculateOutline( gl_Position, objectNormal, skinned );",
  89. "#else",
  90. " gl_Position = calculateOutline( gl_Position, objectNormal, vec4( transformed, 1.0 ) );",
  91. "#endif",
  92. "#include <fog_vertex>"
  93. ].join( "\n" );
  94. var fragmentShader = [
  95. "#include <common>",
  96. "#include <fog_pars_fragment>",
  97. "uniform vec3 outlineColor;",
  98. "uniform float outlineAlpha;",
  99. "void main() {",
  100. " gl_FragColor = vec4( outlineColor, outlineAlpha );",
  101. " #include <fog_fragment>",
  102. "}"
  103. ].join( "\n" );
  104. function createMaterial( originalMaterial ) {
  105. var shaderID = shaderIDs[ originalMaterial.type ];
  106. var originalUniforms, originalVertexShader;
  107. var outlineParameters = originalMaterial.outlineParameters;
  108. if ( shaderID !== undefined ) {
  109. var shader = THREE.ShaderLib[ shaderID ];
  110. originalUniforms = shader.uniforms;
  111. originalVertexShader = shader.vertexShader;
  112. } else if ( originalMaterial.isRawShaderMaterial === true ) {
  113. originalUniforms = originalMaterial.uniforms;
  114. originalVertexShader = originalMaterial.vertexShader;
  115. if ( ! /attribute\s+vec3\s+position\s*;/.test( originalVertexShader ) ||
  116. ! /attribute\s+vec3\s+normal\s*;/.test( originalVertexShader ) ) {
  117. console.warn( 'THREE.OutlineEffect requires both vec3 position and normal attributes in vertex shader, ' +
  118. 'does not draw outline for ' + originalMaterial.name + '(uuid:' + originalMaterial.uuid + ') material.' );
  119. return invisibleMaterial;
  120. }
  121. } else if ( originalMaterial.isShaderMaterial === true ) {
  122. originalUniforms = originalMaterial.uniforms;
  123. originalVertexShader = originalMaterial.vertexShader;
  124. } else {
  125. return invisibleMaterial;
  126. }
  127. var uniforms = Object.assign( {}, originalUniforms, uniformsChunk );
  128. var vertexShader = originalVertexShader
  129. // put vertexShaderChunk right before "void main() {...}"
  130. .replace( /void\s+main\s*\(\s*\)/, vertexShaderChunk + '\nvoid main()' )
  131. // put vertexShaderChunk2 the end of "void main() {...}"
  132. // Note: here assums originalVertexShader ends with "}" of "void main() {...}"
  133. .replace( /\}\s*$/, vertexShaderChunk2 + '\n}' )
  134. // remove any light related lines
  135. // Note: here is very sensitive to originalVertexShader
  136. // TODO: consider safer way
  137. .replace( /#include\s+<[\w_]*light[\w_]*>/g, '' );
  138. var defines = {};
  139. if ( ! /vec3\s+transformed\s*=/.test( originalVertexShader ) &&
  140. ! /#include\s+<begin_vertex>/.test( originalVertexShader ) ) defines.DECLARE_TRANSFORMED = true;
  141. var material = new THREE.ShaderMaterial( {
  142. defines: defines,
  143. uniforms: uniforms,
  144. vertexShader: vertexShader,
  145. fragmentShader: fragmentShader,
  146. side: THREE.BackSide,
  147. //wireframe: true,
  148. skinning: false,
  149. morphTargets: false,
  150. morphNormals: false,
  151. fog: false
  152. } );
  153. return material;
  154. }
  155. function createMultiMaterial( originalMaterial ) {
  156. var materials = [];
  157. for ( var i = 0, il = originalMaterial.materials.length; i < il; i ++ ) {
  158. materials.push( createMaterial( originalMaterial.materials[ i ] ) );
  159. }
  160. return new THREE.MultiMaterial( materials );
  161. }
  162. function setOutlineMaterial( object ) {
  163. if ( object.material === undefined ) return;
  164. var data = cache[ object.material.uuid ];
  165. if ( data === undefined ) {
  166. data = {
  167. material: object.material.isMultiMaterial === true ? createMultiMaterial( object.material ) : createMaterial( object.material ),
  168. used: true,
  169. keepAlive: defaultKeepAlive,
  170. count: 0
  171. };
  172. cache[ object.material.uuid ] = data;
  173. }
  174. var outlineMaterial = data.material;
  175. data.used = true;
  176. var uuid = outlineMaterial !== invisibleMaterial ? outlineMaterial.uuid : object.uuid;
  177. originalMaterials[ uuid ] = object.material;
  178. if ( object.material.isMultiMaterial === true ) {
  179. for ( var i = 0, il = object.material.materials.length; i < il; i ++ ) {
  180. // originalMaterial of leaf material of MultiMaterial is used only for
  181. // updating outlineMaterial. so need not to save for invisibleMaterial.
  182. if ( outlineMaterial.materials[ i ] !== invisibleMaterial ) {
  183. originalMaterials[ outlineMaterial.materials[ i ].uuid ] = object.material.materials[ i ];
  184. }
  185. }
  186. updateOutlineMultiMaterial( outlineMaterial, object.material );
  187. } else {
  188. updateOutlineMaterial( outlineMaterial, object.material );
  189. }
  190. object.material = outlineMaterial;
  191. originalOnBeforeRenders[ object.uuid ] = object.onBeforeRender;
  192. object.onBeforeRender = onBeforeRender;
  193. }
  194. function restoreOriginalMaterial( object ) {
  195. if ( object.material === undefined ) return;
  196. var originalMaterial = originalMaterials[ object.material.uuid ];
  197. if ( originalMaterial === undefined ) {
  198. originalMaterial = originalMaterials[ object.uuid ];
  199. if ( originalMaterial === undefined ) return;
  200. }
  201. object.material = originalMaterial;
  202. object.onBeforeRender = originalOnBeforeRenders[ object.uuid ];
  203. }
  204. function onBeforeRender( renderer, scene, camera, geometry, material, group ) {
  205. // check some things before updating just in case
  206. if ( material === invisibleMaterial ) return;
  207. if ( material.isMultiMaterial === true ) return;
  208. var originalMaterial = originalMaterials[ material.uuid ];
  209. if ( originalMaterial === undefined ) return;
  210. updateUniforms( material, originalMaterial );
  211. }
  212. function updateUniforms( material, originalMaterial ) {
  213. var outlineParameters = originalMaterial.outlineParameters;
  214. material.uniforms.outlineAlpha.value = originalMaterial.opacity;
  215. if ( outlineParameters !== undefined ) {
  216. if ( outlineParameters.thickness !== undefined ) material.uniforms.outlineThickness.value = outlineParameters.thickness;
  217. if ( outlineParameters.color !== undefined ) material.uniforms.outlineColor.value.copy( outlineParameters.color );
  218. if ( outlineParameters.alpha !== undefined ) material.uniforms.outlineAlpha.value = outlineParameters.alpha;
  219. }
  220. }
  221. function updateOutlineMaterial( material, originalMaterial ) {
  222. if ( material === invisibleMaterial ) return;
  223. var outlineParameters = originalMaterial.outlineParameters;
  224. material.skinning = originalMaterial.skinning;
  225. material.morphTargets = originalMaterial.morphTargets;
  226. material.morphNormals = originalMaterial.morphNormals;
  227. material.fog = originalMaterial.fog;
  228. if ( outlineParameters !== undefined ) {
  229. if ( originalMaterial.visible === false ) {
  230. material.visible = false;
  231. } else {
  232. material.visible = ( outlineParameters.visible !== undefined ) ? outlineParameters.visible : true;
  233. }
  234. material.transparent = ( outlineParameters.alpha !== undefined && outlineParameters.alpha < 1.0 ) ? true : originalMaterial.transparent;
  235. // cache[ originalMaterial.uuid ] is undefined if originalMaterial is in materials of MultiMaterial
  236. if ( outlineParameters.keepAlive !== undefined && cache[ originalMaterial.uuid ] !== undefined ) cache[ originalMaterial.uuid ].keepAlive = outlineParameters.keepAlive;
  237. } else {
  238. material.transparent = originalMaterial.transparent;
  239. material.visible = originalMaterial.visible;
  240. }
  241. if ( originalMaterial.wireframe === true || originalMaterial.depthTest === false ) material.visible = false;
  242. }
  243. function updateOutlineMultiMaterial( material, originalMaterial ) {
  244. if ( material === invisibleMaterial ) return;
  245. var outlineParameters = originalMaterial.outlineParameters;
  246. if ( outlineParameters !== undefined ) {
  247. if ( originalMaterial.visible === false ) {
  248. material.visible = false;
  249. } else {
  250. material.visible = ( outlineParameters.visible !== undefined ) ? outlineParameters.visible : true;
  251. }
  252. if ( outlineParameters.keepAlive !== undefined ) cache[ originalMaterial.uuid ].keepAlive = outlineParameters.keepAlive;
  253. } else {
  254. material.visible = originalMaterial.visible;
  255. }
  256. for ( var i = 0, il = material.materials.length; i < il; i ++ ) {
  257. updateOutlineMaterial( material.materials[ i ], originalMaterial.materials[ i ] );
  258. }
  259. }
  260. function cleanupCache() {
  261. var keys;
  262. // clear originialMaterials
  263. keys = Object.keys( originalMaterials );
  264. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  265. originalMaterials[ keys[ i ] ] = undefined;
  266. }
  267. // clear originalOnBeforeRenders
  268. keys = Object.keys( originalOnBeforeRenders );
  269. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  270. originalOnBeforeRenders[ keys[ i ] ] = undefined;
  271. }
  272. // remove unused outlineMaterial from cache
  273. keys = Object.keys( cache );
  274. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  275. var key = keys[ i ];
  276. if ( cache[ key ].used === false ) {
  277. cache[ key ].count++;
  278. if ( cache[ key ].keepAlive === false && cache[ key ].count > removeThresholdCount ) {
  279. delete cache[ key ];
  280. }
  281. } else {
  282. cache[ key ].used = false;
  283. cache[ key ].count = 0;
  284. }
  285. }
  286. }
  287. this.render = function ( scene, camera, renderTarget, forceClear ) {
  288. if ( this.enabled === false ) {
  289. renderer.render( scene, camera, renderTarget, forceClear );
  290. return;
  291. }
  292. var currentAutoClear = renderer.autoClear;
  293. renderer.autoClear = this.autoClear;
  294. // 1. render normally
  295. renderer.render( scene, camera, renderTarget, forceClear );
  296. // 2. render outline
  297. var currentSceneAutoUpdate = scene.autoUpdate;
  298. var currentSceneBackground = scene.background;
  299. var currentShadowMapEnabled = renderer.shadowMap.enabled;
  300. scene.autoUpdate = false;
  301. scene.background = null;
  302. renderer.autoClear = false;
  303. renderer.shadowMap.enabled = false;
  304. scene.traverse( setOutlineMaterial );
  305. renderer.render( scene, camera, renderTarget );
  306. scene.traverse( restoreOriginalMaterial );
  307. cleanupCache();
  308. scene.autoUpdate = currentSceneAutoUpdate;
  309. scene.background = currentSceneBackground;
  310. renderer.autoClear = currentAutoClear;
  311. renderer.shadowMap.enabled = currentShadowMapEnabled;
  312. };
  313. /*
  314. * See #9918
  315. *
  316. * The following property copies and wrapper methods enable
  317. * THREE.OutlineEffect to be called from other *Effect, like
  318. *
  319. * effect = new THREE.VREffect( new THREE.OutlineEffect( renderer ) );
  320. *
  321. * function render () {
  322. *
  323. * effect.render( scene, camera );
  324. *
  325. * }
  326. */
  327. this.autoClear = renderer.autoClear;
  328. this.domElement = renderer.domElement;
  329. this.shadowMap = renderer.shadowMap;
  330. this.clear = function ( color, depth, stencil ) {
  331. renderer.clear( color, depth, stencil );
  332. };
  333. this.getPixelRatio = function () {
  334. return renderer.getPixelRatio();
  335. };
  336. this.setPixelRatio = function ( value ) {
  337. renderer.setPixelRatio( value );
  338. };
  339. this.getSize = function () {
  340. return renderer.getSize();
  341. };
  342. this.setSize = function ( width, height, updateStyle ) {
  343. renderer.setSize( width, height, updateStyle );
  344. };
  345. this.setViewport = function ( x, y, width, height ) {
  346. renderer.setViewport( x, y, width, height );
  347. };
  348. this.setScissor = function ( x, y, width, height ) {
  349. renderer.setScissor( x, y, width, height );
  350. };
  351. this.setScissorTest = function ( boolean ) {
  352. renderer.setScissorTest( boolean );
  353. };
  354. this.setRenderTarget = function ( renderTarget ) {
  355. renderer.setRenderTarget( renderTarget );
  356. };
  357. };