webgl_clipping_advanced.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. function planesFromMesh( vertices, indices ) {
  27. // creates a clipping volume from a convex triangular mesh
  28. // specified by the arrays 'vertices' and 'indices'
  29. const n = indices.length / 3,
  30. result = new Array( n );
  31. for ( let i = 0, j = 0; i < n; ++ i, j += 3 ) {
  32. const a = vertices[ indices[ j ] ],
  33. b = vertices[ indices[ j + 1 ] ],
  34. c = vertices[ indices[ j + 2 ] ];
  35. result[ i ] = new THREE.Plane().
  36. setFromCoplanarPoints( a, b, c );
  37. }
  38. return result;
  39. }
  40. function createPlanes( n ) {
  41. // creates an array of n uninitialized plane objects
  42. const result = new Array( n );
  43. for ( let i = 0; i !== n; ++ i )
  44. result[ i ] = new THREE.Plane();
  45. return result;
  46. }
  47. function assignTransformedPlanes( planesOut, planesIn, matrix ) {
  48. // sets an array of existing planes to transformed 'planesIn'
  49. for ( let i = 0, n = planesIn.length; i !== n; ++ i )
  50. planesOut[ i ].copy( planesIn[ i ] ).applyMatrix4( matrix );
  51. }
  52. function cylindricalPlanes( n, innerRadius ) {
  53. const result = createPlanes( n );
  54. for ( let i = 0; i !== n; ++ i ) {
  55. const plane = result[ i ],
  56. angle = i * Math.PI * 2 / n;
  57. plane.normal.set(
  58. Math.cos( angle ), 0, Math.sin( angle ) );
  59. plane.constant = innerRadius;
  60. }
  61. return result;
  62. }
  63. const planeToMatrix = ( function () {
  64. // creates a matrix that aligns X/Y to a given plane
  65. // temporaries:
  66. const xAxis = new THREE.Vector3(),
  67. yAxis = new THREE.Vector3(),
  68. trans = new THREE.Vector3();
  69. return function planeToMatrix( plane ) {
  70. const zAxis = plane.normal,
  71. matrix = new THREE.Matrix4();
  72. // Hughes & Moeller '99
  73. // "Building an Orthonormal Basis from a Unit Vector."
  74. if ( Math.abs( zAxis.x ) > Math.abs( zAxis.z ) ) {
  75. yAxis.set( - zAxis.y, zAxis.x, 0 );
  76. } else {
  77. yAxis.set( 0, - zAxis.z, zAxis.y );
  78. }
  79. xAxis.crossVectors( yAxis.normalize(), zAxis );
  80. plane.coplanarPoint( trans );
  81. return matrix.set(
  82. xAxis.x, yAxis.x, zAxis.x, trans.x,
  83. xAxis.y, yAxis.y, zAxis.y, trans.y,
  84. xAxis.z, yAxis.z, zAxis.z, trans.z,
  85. 0, 0, 0, 1 );
  86. };
  87. } )();
  88. // A regular tetrahedron for the clipping volume:
  89. const Vertices = [
  90. new THREE.Vector3( + 1, 0, + Math.SQRT1_2 ),
  91. new THREE.Vector3( - 1, 0, + Math.SQRT1_2 ),
  92. new THREE.Vector3( 0, + 1, - Math.SQRT1_2 ),
  93. new THREE.Vector3( 0, - 1, - Math.SQRT1_2 )
  94. ],
  95. Indices = [
  96. 0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2
  97. ],
  98. Planes = planesFromMesh( Vertices, Indices ),
  99. PlaneMatrices = Planes.map( planeToMatrix ),
  100. GlobalClippingPlanes = cylindricalPlanes( 5, 2.5 ),
  101. Empty = Object.freeze( [] );
  102. let camera, scene, renderer, startTime, stats,
  103. object, clipMaterial,
  104. volumeVisualization,
  105. globalClippingPlanes;
  106. function init() {
  107. camera = new THREE.PerspectiveCamera(
  108. 36, window.innerWidth / window.innerHeight, 0.25, 16 );
  109. camera.position.set( 0, 1.5, 3 );
  110. scene = new THREE.Scene();
  111. // Lights
  112. scene.add( new THREE.AmbientLight( 0xffffff ) );
  113. const spotLight = new THREE.SpotLight( 0xffffff, 60 );
  114. spotLight.angle = Math.PI / 5;
  115. spotLight.penumbra = 0.2;
  116. spotLight.position.set( 2, 3, 3 );
  117. spotLight.castShadow = true;
  118. spotLight.shadow.camera.near = 3;
  119. spotLight.shadow.camera.far = 10;
  120. spotLight.shadow.mapSize.width = 1024;
  121. spotLight.shadow.mapSize.height = 1024;
  122. scene.add( spotLight );
  123. const dirLight = new THREE.DirectionalLight( 0xffffff, 1.5 );
  124. dirLight.position.set( 0, 2, 0 );
  125. dirLight.castShadow = true;
  126. dirLight.shadow.camera.near = 1;
  127. dirLight.shadow.camera.far = 10;
  128. dirLight.shadow.camera.right = 1;
  129. dirLight.shadow.camera.left = - 1;
  130. dirLight.shadow.camera.top = 1;
  131. dirLight.shadow.camera.bottom = - 1;
  132. dirLight.shadow.mapSize.width = 1024;
  133. dirLight.shadow.mapSize.height = 1024;
  134. scene.add( dirLight );
  135. // Geometry
  136. clipMaterial = new THREE.MeshPhongMaterial( {
  137. color: 0xee0a10,
  138. shininess: 100,
  139. side: THREE.DoubleSide,
  140. // Clipping setup:
  141. clippingPlanes: createPlanes( Planes.length ),
  142. clipShadows: true
  143. } );
  144. object = new THREE.Group();
  145. const geometry = new THREE.BoxGeometry( 0.18, 0.18, 0.18 );
  146. for ( let z = - 2; z <= 2; ++ z )
  147. for ( let y = - 2; y <= 2; ++ y )
  148. for ( let x = - 2; x <= 2; ++ x ) {
  149. const mesh = new THREE.Mesh( geometry, clipMaterial );
  150. mesh.position.set( x / 5, y / 5, z / 5 );
  151. mesh.castShadow = true;
  152. object.add( mesh );
  153. }
  154. scene.add( object );
  155. const planeGeometry = new THREE.PlaneGeometry( 3, 3, 1, 1 ),
  156. color = new THREE.Color();
  157. volumeVisualization = new THREE.Group();
  158. volumeVisualization.visible = false;
  159. for ( let i = 0, n = Planes.length; i !== n; ++ i ) {
  160. const material = new THREE.MeshBasicMaterial( {
  161. color: color.setHSL( i / n, 0.5, 0.5 ).getHex(),
  162. side: THREE.DoubleSide,
  163. opacity: 0.2,
  164. transparent: true,
  165. // clip to the others to show the volume (wildly
  166. // intersecting transparent planes look bad)
  167. clippingPlanes: clipMaterial.clippingPlanes.
  168. filter( function ( _, j ) {
  169. return j !== i;
  170. } )
  171. // no need to enable shadow clipping - the plane
  172. // visualization does not cast shadows
  173. } );
  174. const mesh = new THREE.Mesh( planeGeometry, material );
  175. mesh.matrixAutoUpdate = false;
  176. volumeVisualization.add( mesh );
  177. }
  178. scene.add( volumeVisualization );
  179. const ground = new THREE.Mesh( planeGeometry,
  180. new THREE.MeshPhongMaterial( {
  181. color: 0xa0adaf, shininess: 10 } ) );
  182. ground.rotation.x = - Math.PI / 2;
  183. ground.scale.multiplyScalar( 3 );
  184. ground.receiveShadow = true;
  185. scene.add( ground );
  186. // Renderer
  187. const container = document.body;
  188. renderer = new THREE.WebGLRenderer();
  189. renderer.shadowMap.enabled = true;
  190. renderer.setPixelRatio( window.devicePixelRatio );
  191. renderer.setSize( window.innerWidth, window.innerHeight );
  192. renderer.useLegacyLights = false;
  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>