webgl_clipping_advanced.html 10.0 KB

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