webgl_clipping_advanced.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - clipping planes - advanced</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <!-- Import maps polyfill -->
  11. <!-- Remove this when import maps will be widely supported -->
  12. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../build/three.module.js",
  17. "three/addons/": "./jsm/"
  18. }
  19. }
  20. </script>
  21. <script type="module">
  22. import * as THREE from 'three';
  23. import Stats from 'three/addons/libs/stats.module.js';
  24. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  25. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  26. THREE.ColorManagement.enabled = true;
  27. function planesFromMesh( vertices, indices ) {
  28. // creates a clipping volume from a convex triangular mesh
  29. // specified by the arrays 'vertices' and 'indices'
  30. const n = indices.length / 3,
  31. result = new Array( n );
  32. for ( let i = 0, j = 0; i < n; ++ i, j += 3 ) {
  33. const a = vertices[ indices[ j ] ],
  34. b = vertices[ indices[ j + 1 ] ],
  35. c = vertices[ indices[ j + 2 ] ];
  36. result[ i ] = new THREE.Plane().
  37. setFromCoplanarPoints( a, b, c );
  38. }
  39. return result;
  40. }
  41. function createPlanes( n ) {
  42. // creates an array of n uninitialized plane objects
  43. const result = new Array( n );
  44. for ( let i = 0; i !== n; ++ i )
  45. result[ i ] = new THREE.Plane();
  46. return result;
  47. }
  48. function assignTransformedPlanes( planesOut, planesIn, matrix ) {
  49. // sets an array of existing planes to transformed 'planesIn'
  50. for ( let i = 0, n = planesIn.length; i !== n; ++ i )
  51. planesOut[ i ].copy( planesIn[ i ] ).applyMatrix4( matrix );
  52. }
  53. function cylindricalPlanes( n, innerRadius ) {
  54. const result = createPlanes( n );
  55. for ( let i = 0; i !== n; ++ i ) {
  56. const plane = result[ i ],
  57. angle = i * Math.PI * 2 / n;
  58. plane.normal.set(
  59. Math.cos( angle ), 0, Math.sin( angle ) );
  60. plane.constant = innerRadius;
  61. }
  62. return result;
  63. }
  64. const planeToMatrix = ( function () {
  65. // creates a matrix that aligns X/Y to a given plane
  66. // temporaries:
  67. const xAxis = new THREE.Vector3(),
  68. yAxis = new THREE.Vector3(),
  69. trans = new THREE.Vector3();
  70. return function planeToMatrix( plane ) {
  71. const zAxis = plane.normal,
  72. matrix = new THREE.Matrix4();
  73. // Hughes & Moeller '99
  74. // "Building an Orthonormal Basis from a Unit Vector."
  75. if ( Math.abs( zAxis.x ) > Math.abs( zAxis.z ) ) {
  76. yAxis.set( - zAxis.y, zAxis.x, 0 );
  77. } else {
  78. yAxis.set( 0, - zAxis.z, zAxis.y );
  79. }
  80. xAxis.crossVectors( yAxis.normalize(), zAxis );
  81. plane.coplanarPoint( trans );
  82. return matrix.set(
  83. xAxis.x, yAxis.x, zAxis.x, trans.x,
  84. xAxis.y, yAxis.y, zAxis.y, trans.y,
  85. xAxis.z, yAxis.z, zAxis.z, trans.z,
  86. 0, 0, 0, 1 );
  87. };
  88. } )();
  89. // A regular tetrahedron for the clipping volume:
  90. const Vertices = [
  91. new THREE.Vector3( + 1, 0, + Math.SQRT1_2 ),
  92. new THREE.Vector3( - 1, 0, + Math.SQRT1_2 ),
  93. new THREE.Vector3( 0, + 1, - Math.SQRT1_2 ),
  94. new THREE.Vector3( 0, - 1, - Math.SQRT1_2 )
  95. ],
  96. Indices = [
  97. 0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2
  98. ],
  99. Planes = planesFromMesh( Vertices, Indices ),
  100. PlaneMatrices = Planes.map( planeToMatrix ),
  101. GlobalClippingPlanes = cylindricalPlanes( 5, 2.5 ),
  102. Empty = Object.freeze( [] );
  103. let camera, scene, renderer, startTime, stats,
  104. object, clipMaterial,
  105. volumeVisualization,
  106. globalClippingPlanes;
  107. function init() {
  108. camera = new THREE.PerspectiveCamera(
  109. 36, window.innerWidth / window.innerHeight, 0.25, 16 );
  110. camera.position.set( 0, 1.5, 3 );
  111. scene = new THREE.Scene();
  112. // Lights
  113. scene.add( new THREE.AmbientLight( 0xffffff, 0.3 ) );
  114. const spotLight = new THREE.SpotLight( 0xffffff, 0.5 );
  115. spotLight.angle = Math.PI / 5;
  116. spotLight.penumbra = 0.2;
  117. spotLight.position.set( 2, 3, 3 );
  118. spotLight.castShadow = true;
  119. spotLight.shadow.camera.near = 3;
  120. spotLight.shadow.camera.far = 10;
  121. spotLight.shadow.mapSize.width = 1024;
  122. spotLight.shadow.mapSize.height = 1024;
  123. scene.add( spotLight );
  124. const dirLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  125. dirLight.position.set( 0, 2, 0 );
  126. dirLight.castShadow = true;
  127. dirLight.shadow.camera.near = 1;
  128. dirLight.shadow.camera.far = 10;
  129. dirLight.shadow.camera.right = 1;
  130. dirLight.shadow.camera.left = - 1;
  131. dirLight.shadow.camera.top = 1;
  132. dirLight.shadow.camera.bottom = - 1;
  133. dirLight.shadow.mapSize.width = 1024;
  134. dirLight.shadow.mapSize.height = 1024;
  135. scene.add( dirLight );
  136. // Geometry
  137. clipMaterial = new THREE.MeshPhongMaterial( {
  138. color: 0xee0a10,
  139. shininess: 100,
  140. side: THREE.DoubleSide,
  141. // Clipping setup:
  142. clippingPlanes: createPlanes( Planes.length ),
  143. clipShadows: true
  144. } );
  145. object = new THREE.Group();
  146. const geometry = new THREE.BoxGeometry( 0.18, 0.18, 0.18 );
  147. for ( let z = - 2; z <= 2; ++ z )
  148. for ( let y = - 2; y <= 2; ++ y )
  149. for ( let x = - 2; x <= 2; ++ x ) {
  150. const mesh = new THREE.Mesh( geometry, clipMaterial );
  151. mesh.position.set( x / 5, y / 5, z / 5 );
  152. mesh.castShadow = true;
  153. object.add( mesh );
  154. }
  155. scene.add( object );
  156. const planeGeometry = new THREE.PlaneGeometry( 3, 3, 1, 1 ),
  157. color = new THREE.Color();
  158. volumeVisualization = new THREE.Group();
  159. volumeVisualization.visible = false;
  160. for ( let i = 0, n = Planes.length; i !== n; ++ i ) {
  161. const material = new THREE.MeshBasicMaterial( {
  162. color: color.setHSL( i / n, 0.5, 0.5 ).getHex(),
  163. side: THREE.DoubleSide,
  164. opacity: 0.2,
  165. transparent: true,
  166. // clip to the others to show the volume (wildly
  167. // intersecting transparent planes look bad)
  168. clippingPlanes: clipMaterial.clippingPlanes.
  169. filter( function ( _, j ) {
  170. return j !== i;
  171. } )
  172. // no need to enable shadow clipping - the plane
  173. // visualization does not cast shadows
  174. } );
  175. const mesh = new THREE.Mesh( planeGeometry, material );
  176. mesh.matrixAutoUpdate = false;
  177. volumeVisualization.add( mesh );
  178. }
  179. scene.add( volumeVisualization );
  180. const ground = new THREE.Mesh( planeGeometry,
  181. new THREE.MeshPhongMaterial( {
  182. color: 0xa0adaf, shininess: 10 } ) );
  183. ground.rotation.x = - Math.PI / 2;
  184. ground.scale.multiplyScalar( 3 );
  185. ground.receiveShadow = true;
  186. scene.add( ground );
  187. // Renderer
  188. const container = document.body;
  189. renderer = new THREE.WebGLRenderer();
  190. renderer.shadowMap.enabled = true;
  191. renderer.setPixelRatio( window.devicePixelRatio );
  192. renderer.setSize( window.innerWidth, window.innerHeight );
  193. window.addEventListener( 'resize', onWindowResize );
  194. container.appendChild( renderer.domElement );
  195. // Clipping setup:
  196. globalClippingPlanes = createPlanes( GlobalClippingPlanes.length );
  197. renderer.clippingPlanes = Empty;
  198. renderer.localClippingEnabled = true;
  199. // Stats
  200. stats = new Stats();
  201. container.appendChild( stats.dom );
  202. // Controls
  203. const controls = new OrbitControls( camera, renderer.domElement );
  204. controls.minDistance = 1;
  205. controls.maxDistance = 8;
  206. controls.target.set( 0, 1, 0 );
  207. controls.update();
  208. // GUI
  209. const gui = new GUI(),
  210. folder = gui.addFolder( 'Local Clipping' ),
  211. props = {
  212. get 'Enabled'() {
  213. return renderer.localClippingEnabled;
  214. },
  215. set 'Enabled'( v ) {
  216. renderer.localClippingEnabled = v;
  217. if ( ! v ) volumeVisualization.visible = false;
  218. },
  219. get 'Shadows'() {
  220. return clipMaterial.clipShadows;
  221. },
  222. set 'Shadows'( v ) {
  223. clipMaterial.clipShadows = v;
  224. },
  225. get 'Visualize'() {
  226. return volumeVisualization.visible;
  227. },
  228. set 'Visualize'( v ) {
  229. if ( renderer.localClippingEnabled )
  230. volumeVisualization.visible = v;
  231. }
  232. };
  233. folder.add( props, 'Enabled' );
  234. folder.add( props, 'Shadows' );
  235. folder.add( props, 'Visualize' ).listen();
  236. gui.addFolder( 'Global Clipping' ).
  237. add( {
  238. get 'Enabled'() {
  239. return renderer.clippingPlanes !== Empty;
  240. },
  241. set 'Enabled'( v ) {
  242. renderer.clippingPlanes = v ?
  243. globalClippingPlanes : Empty;
  244. }
  245. }, 'Enabled' );
  246. // Start
  247. startTime = Date.now();
  248. }
  249. function onWindowResize() {
  250. camera.aspect = window.innerWidth / window.innerHeight;
  251. camera.updateProjectionMatrix();
  252. renderer.setSize( window.innerWidth, window.innerHeight );
  253. }
  254. function setObjectWorldMatrix( object, matrix ) {
  255. // set the orientation of an object based on a world matrix
  256. const parent = object.parent;
  257. scene.updateMatrixWorld();
  258. object.matrix.copy( parent.matrixWorld ).invert();
  259. object.applyMatrix4( matrix );
  260. }
  261. const transform = new THREE.Matrix4(),
  262. tmpMatrix = new THREE.Matrix4();
  263. function animate() {
  264. const currentTime = Date.now(),
  265. time = ( currentTime - startTime ) / 1000;
  266. requestAnimationFrame( animate );
  267. object.position.y = 1;
  268. object.rotation.x = time * 0.5;
  269. object.rotation.y = time * 0.2;
  270. object.updateMatrix();
  271. transform.copy( object.matrix );
  272. const bouncy = Math.cos( time * .5 ) * 0.5 + 0.7;
  273. transform.multiply(
  274. tmpMatrix.makeScale( bouncy, bouncy, bouncy ) );
  275. assignTransformedPlanes(
  276. clipMaterial.clippingPlanes, Planes, transform );
  277. const planeMeshes = volumeVisualization.children;
  278. for ( let i = 0, n = planeMeshes.length; i !== n; ++ i ) {
  279. tmpMatrix.multiplyMatrices( transform, PlaneMatrices[ i ] );
  280. setObjectWorldMatrix( planeMeshes[ i ], tmpMatrix );
  281. }
  282. transform.makeRotationY( time * 0.1 );
  283. assignTransformedPlanes( globalClippingPlanes, GlobalClippingPlanes, transform );
  284. stats.begin();
  285. renderer.render( scene, camera );
  286. stats.end();
  287. }
  288. init();
  289. animate();
  290. </script>
  291. </body>
  292. </html>