webgl_interactive_instances_gpu.html 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - interactive instances (gpu)</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. <style>
  9. #info {
  10. background-color: rgba(0,0,0,0.75);
  11. }
  12. #notSupported {
  13. width: 50%;
  14. margin: auto;
  15. border: 2px red solid;
  16. margin-top: 20px;
  17. padding: 10px;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <div id="info">
  23. <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - gpu picking of geometry instances
  24. <div id="notSupported" style="display:none">Sorry your graphics card + browser does not support hardware instancing</div>
  25. <br/><br/>
  26. <div>
  27. <div>
  28. number of instances:
  29. <select id="instanceCount">
  30. <option>100</option>
  31. <option>500</option>
  32. <option selected>1000</option>
  33. <option>2000</option>
  34. <option>3000</option>
  35. <option>5000</option>
  36. <option>10000</option>
  37. <option>20000</option>
  38. <option>30000</option>
  39. <option>50000</option>
  40. <option>100000</option>
  41. </select>
  42. </div>
  43. <div>
  44. method:
  45. <select id="method">
  46. <option>instanced</option>
  47. <option>merged</option>
  48. <option selected>singleMaterial</option>
  49. <option>multiMaterial</option>
  50. </select>
  51. </div>
  52. <div>
  53. render continuously:
  54. <input id="animate" type="checkbox" />
  55. </div>
  56. <div>
  57. override material (only affects singleMaterial):
  58. <input id="override" type="checkbox" checked/>
  59. </div>
  60. <div>
  61. construct anew(to get additional timings):
  62. <button id="construct" type="button">do it</button>
  63. </div>
  64. </div>
  65. <br/>
  66. <div>
  67. <span>Materials: #<span id="materialCount"></span></span>
  68. &nbsp;&nbsp;&nbsp;
  69. <span>Objects: #<span id="objectCount"></span></span>
  70. &nbsp;&nbsp;&nbsp;
  71. <span>Drawcalls: #<span id="drawcalls"></span></span>
  72. &nbsp;&nbsp;&nbsp;
  73. <span>Construction time: <span id="initTime"></span>&nbsp;ms</span>
  74. &nbsp;&nbsp;&nbsp;
  75. </div>
  76. </div>
  77. <div id="container"></div>
  78. <script id="vertMerged" type="x-shader/x-vertex">
  79. #define SHADER_NAME vertMerged
  80. precision highp float;
  81. uniform mat4 modelViewMatrix;
  82. uniform mat4 projectionMatrix;
  83. attribute vec3 position;
  84. #ifdef PICKING
  85. attribute vec3 pickingColor;
  86. #else
  87. attribute vec3 color;
  88. varying vec3 vPosition;
  89. #endif
  90. varying vec3 vColor;
  91. void main() {
  92. vec3 positionEye = ( modelViewMatrix * vec4( position, 1.0 ) ).xyz;
  93. #ifdef PICKING
  94. vColor = pickingColor;
  95. #else
  96. vColor = color;
  97. vPosition = positionEye;
  98. #endif
  99. gl_Position = projectionMatrix * vec4( positionEye, 1.0 );
  100. }
  101. </script>
  102. <script id="fragMerged" type="x-shader/x-fragment">
  103. #define SHADER_NAME fragMerged
  104. #extension GL_OES_standard_derivatives : enable
  105. precision highp float;
  106. varying vec3 vColor;
  107. #ifndef PICKING
  108. varying vec3 vPosition;
  109. #endif
  110. void main() {
  111. #ifdef PICKING
  112. gl_FragColor = vec4( vColor, 1.0 );
  113. #else
  114. vec3 fdx = dFdx( vPosition );
  115. vec3 fdy = dFdy( vPosition );
  116. vec3 normal = normalize( cross( fdx, fdy ) );
  117. float diffuse = dot( normal, vec3( 0.0, 0.0, 1.0 ) );
  118. gl_FragColor = vec4( diffuse * vColor, 1.0 );
  119. #endif
  120. }
  121. </script>
  122. <script id="vertInstanced" type="x-shader/x-vertex">
  123. #define SHADER_NAME vertInstanced
  124. precision highp float;
  125. uniform mat4 modelViewMatrix;
  126. uniform mat4 projectionMatrix;
  127. attribute vec3 position;
  128. attribute vec3 mcol0;
  129. attribute vec3 mcol1;
  130. attribute vec3 mcol2;
  131. attribute vec3 mcol3;
  132. #ifdef PICKING
  133. attribute vec3 pickingColor;
  134. #else
  135. attribute vec3 color;
  136. varying vec3 vPosition;
  137. #endif
  138. varying vec3 vColor;
  139. void main() {
  140. mat4 matrix = mat4(
  141. vec4( mcol0, 0 ),
  142. vec4( mcol1, 0 ),
  143. vec4( mcol2, 0 ),
  144. vec4( mcol3, 1 )
  145. );
  146. vec3 positionEye = ( modelViewMatrix * matrix * vec4( position, 1.0 ) ).xyz;
  147. #ifdef PICKING
  148. vColor = pickingColor;
  149. #else
  150. vColor = color;
  151. vPosition = positionEye;
  152. #endif
  153. gl_Position = projectionMatrix * vec4( positionEye, 1.0 );
  154. }
  155. </script>
  156. <script id="fragInstanced" type="x-shader/x-fragment">
  157. #define SHADER_NAME fragInstanced
  158. #extension GL_OES_standard_derivatives : enable
  159. precision highp float;
  160. varying vec3 vColor;
  161. #ifndef PICKING
  162. varying vec3 vPosition;
  163. #endif
  164. void main() {
  165. #ifdef PICKING
  166. gl_FragColor = vec4( vColor, 1.0 );
  167. #else
  168. vec3 fdx = dFdx( vPosition );
  169. vec3 fdy = dFdy( vPosition );
  170. vec3 normal = normalize( cross( fdx, fdy ) );
  171. float diffuse = dot( normal, vec3( 0.0, 0.0, 1.0 ) );
  172. gl_FragColor = vec4( diffuse * vColor, 1.0 );
  173. #endif
  174. }
  175. </script>
  176. <script id="vertMaterial" type="x-shader/x-vertex">
  177. #define SHADER_NAME vertMaterial
  178. precision highp float;
  179. uniform mat4 modelViewMatrix;
  180. uniform mat4 projectionMatrix;
  181. attribute vec3 position;
  182. #ifndef PICKING
  183. varying vec3 vPosition;
  184. #endif
  185. void main() {
  186. vec3 positionEye = ( modelViewMatrix * vec4( position, 1.0 ) ).xyz;
  187. #ifndef PICKING
  188. vPosition = positionEye;
  189. #endif
  190. gl_Position = projectionMatrix * vec4( positionEye, 1.0 );
  191. }
  192. </script>
  193. <script id="fragMaterial" type="x-shader/x-fragment">
  194. #define SHADER_NAME fragMaterial
  195. #extension GL_OES_standard_derivatives : enable
  196. precision highp float;
  197. #ifdef PICKING
  198. uniform vec3 pickingColor;
  199. #else
  200. uniform vec3 color;
  201. varying vec3 vPosition;
  202. #endif
  203. void main() {
  204. #ifdef PICKING
  205. gl_FragColor = vec4( pickingColor, 1.0 );
  206. #else
  207. vec3 fdx = dFdx( vPosition );
  208. vec3 fdy = dFdy( vPosition );
  209. vec3 normal = normalize( cross( fdx, fdy ) );
  210. float diffuse = dot( normal, vec3( 0.0, 0.0, 1.0 ) );
  211. gl_FragColor = vec4( diffuse * color, 1.0 );
  212. #endif
  213. }
  214. </script>
  215. <script type="module">
  216. import {
  217. BoxBufferGeometry,
  218. BufferAttribute,
  219. BufferGeometry,
  220. BufferGeometryLoader,
  221. Cache as _Cache,
  222. Color,
  223. Euler,
  224. InstancedBufferAttribute,
  225. InstancedBufferGeometry,
  226. Matrix4,
  227. Mesh,
  228. MeshLambertMaterial,
  229. NearestFilter,
  230. Object3D,
  231. PerspectiveCamera,
  232. RawShaderMaterial,
  233. Quaternion,
  234. Scene,
  235. Vector2,
  236. Vector3,
  237. WebGLRenderer,
  238. WebGLRenderTarget
  239. } from "../build/three.module.js";
  240. import Stats from './jsm/libs/stats.module.js';
  241. import { TrackballControls } from './jsm/controls/TrackballControls.js';
  242. var container, stats;
  243. var camera, controls, scene, renderer;
  244. var pickingData, pickingRenderTarget, pickingScene;
  245. var useOverrideMaterial = true;
  246. var singleMaterial, singlePickingMaterial;
  247. var highlightBox;
  248. var materialList = [];
  249. var geometryList = [];
  250. var objectCount = 0;
  251. var geometrySize = new Vector3();
  252. var mouse = new Vector2();
  253. var scale = 1.03;
  254. var loader = new BufferGeometryLoader();
  255. //create buffer for reading a single pixel
  256. var pixelBuffer = new Uint8Array( 4 );
  257. // gui
  258. var instanceCount, method, doAnimate;
  259. //
  260. gui();
  261. init();
  262. initMesh();
  263. if ( doAnimate ) animate();
  264. //
  265. function gui() {
  266. var instanceCountElm = document.getElementById( 'instanceCount' );
  267. instanceCount = parseInt( instanceCountElm.value );
  268. instanceCountElm.addEventListener( "change", function () {
  269. instanceCount = parseInt( instanceCountElm.value );
  270. initMesh();
  271. } );
  272. //
  273. var methodElm = document.getElementById( 'method' );
  274. method = methodElm.value;
  275. methodElm.addEventListener( "change", function () {
  276. method = methodElm.value;
  277. initMesh();
  278. } );
  279. //
  280. var animateElm = document.getElementById( 'animate' );
  281. doAnimate = animateElm.checked;
  282. animateElm.addEventListener( "click", function () {
  283. doAnimate = animateElm.checked;
  284. animate();
  285. } );
  286. //
  287. var overrideElm = document.getElementById( 'override' );
  288. useOverrideMaterial = overrideElm.checked;
  289. overrideElm.addEventListener( "click", function () {
  290. useOverrideMaterial = overrideElm.checked;
  291. initMesh();
  292. } );
  293. //
  294. var constructElm = document.getElementById( 'construct' );
  295. constructElm.addEventListener( "click", function () {
  296. initMesh();
  297. } );
  298. }
  299. function clean() {
  300. _Cache.clear();
  301. materialList.forEach( function ( m ) {
  302. m.dispose();
  303. } );
  304. geometryList.forEach( function ( g ) {
  305. g.dispose();
  306. } );
  307. scene = new Scene();
  308. scene.background = new Color( 0xffffff );
  309. scene.add( camera );
  310. scene.add( highlightBox );
  311. pickingScene = new Scene();
  312. pickingData = {};
  313. materialList = [];
  314. geometryList = [];
  315. objectCount = 0;
  316. singleMaterial = undefined;
  317. singlePickingMaterial = undefined;
  318. }
  319. var randomizeMatrix = function () {
  320. var position = new Vector3();
  321. var rotation = new Euler();
  322. var quaternion = new Quaternion();
  323. var scale = new Vector3();
  324. return function ( matrix ) {
  325. position.x = Math.random() * 40 - 20;
  326. position.y = Math.random() * 40 - 20;
  327. position.z = Math.random() * 40 - 20;
  328. rotation.x = Math.random() * 2 * Math.PI;
  329. rotation.y = Math.random() * 2 * Math.PI;
  330. rotation.z = Math.random() * 2 * Math.PI;
  331. quaternion.setFromEuler( rotation );
  332. scale.x = scale.y = scale.z = Math.random() * 1;
  333. matrix.compose( position, quaternion, scale );
  334. };
  335. }();
  336. function initMesh() {
  337. clean();
  338. // make instances
  339. loader.load( 'models/json/suzanne_buffergeometry.json', function ( geo ) {
  340. geo = geo.toNonIndexed();
  341. geo.computeBoundingBox();
  342. geo.boundingBox.getSize( geometrySize );
  343. geometryList.push( geo );
  344. var start = window.performance.now();
  345. switch ( method ) {
  346. case "merged":
  347. makeMerged( geo );
  348. break;
  349. case "instanced":
  350. makeInstanced( geo );
  351. break;
  352. case "singleMaterial":
  353. makeSingleMaterial( geo );
  354. break;
  355. case "multiMaterial":
  356. makeMultiMaterial( geo );
  357. break;
  358. }
  359. render();
  360. var end = window.performance.now();
  361. document.getElementById( 'materialCount' ).innerText = materialList.length;
  362. document.getElementById( 'objectCount' ).innerText = objectCount;
  363. document.getElementById( 'drawcalls' ).innerText = renderer.info.render.calls;
  364. document.getElementById( 'initTime' ).innerText = ( end - start ).toFixed( 2 );
  365. } );
  366. }
  367. function makeMultiMaterial( geo ) {
  368. // material
  369. var vert = document.getElementById( 'vertMaterial' ).textContent;
  370. var frag = document.getElementById( 'fragMaterial' ).textContent;
  371. var material = new RawShaderMaterial( {
  372. vertexShader: vert,
  373. fragmentShader: frag,
  374. uniforms: {
  375. color: {
  376. value: new Color()
  377. }
  378. }
  379. } );
  380. var pickingMaterial = new RawShaderMaterial( {
  381. vertexShader: "#define PICKING\n" + vert,
  382. fragmentShader: "#define PICKING\n" + frag,
  383. uniforms: {
  384. pickingColor: {
  385. value: new Color()
  386. }
  387. }
  388. } );
  389. // geometry / mesh
  390. var matrix = new Matrix4();
  391. for ( var i = 0; i < instanceCount; i ++ ) {
  392. var object = new Mesh( geo, material );
  393. objectCount ++;
  394. randomizeMatrix( matrix );
  395. object.applyMatrix( matrix );
  396. var pickingObject = object.clone();
  397. objectCount ++;
  398. object.material = material.clone();
  399. object.material.uniforms[ "color" ].value.setHex( Math.random() * 0xffffff );
  400. materialList.push( object.material );
  401. pickingObject.material = pickingMaterial.clone();
  402. pickingObject.material.uniforms[ "pickingColor" ].value.setHex( i + 1 );
  403. materialList.push( pickingObject.material );
  404. pickingData[ i + 1 ] = object;
  405. scene.add( object );
  406. pickingScene.add( pickingObject );
  407. }
  408. material.dispose();
  409. pickingMaterial.dispose();
  410. }
  411. function makeSingleMaterial( geo ) {
  412. // material
  413. var vert = document.getElementById( 'vertMaterial' ).textContent;
  414. var frag = document.getElementById( 'fragMaterial' ).textContent;
  415. var material = new RawShaderMaterial( {
  416. vertexShader: vert,
  417. fragmentShader: frag,
  418. uniforms: {
  419. "color": {
  420. value: new Color()
  421. }
  422. }
  423. } );
  424. materialList.push( material );
  425. var pickingMaterial = new RawShaderMaterial( {
  426. vertexShader: "#define PICKING\n" + vert,
  427. fragmentShader: "#define PICKING\n" + frag,
  428. uniforms: {
  429. "pickingColor": {
  430. value: new Color()
  431. }
  432. }
  433. } );
  434. materialList.push( pickingMaterial );
  435. if ( useOverrideMaterial ) {
  436. // make globally available
  437. singleMaterial = material;
  438. singlePickingMaterial = pickingMaterial;
  439. }
  440. // geometry / mesh
  441. var matrix = new Matrix4();
  442. function onBeforeRender( renderer, scene, camera, geometry, material ) {
  443. var updateList = [];
  444. var u = material.uniforms;
  445. var d = this.userData;
  446. if ( u.pickingColor ) {
  447. u.pickingColor.value.setHex( d.pickingColor );
  448. updateList.push( "pickingColor" );
  449. }
  450. if ( u.color ) {
  451. u.color.value.setHex( d.color );
  452. updateList.push( "color" );
  453. }
  454. if ( updateList.length ) {
  455. var materialProperties = renderer.properties.get( material );
  456. if ( materialProperties.program ) {
  457. var gl = renderer.getContext();
  458. var p = materialProperties.program;
  459. gl.useProgram( p.program );
  460. var pu = p.getUniforms();
  461. updateList.forEach( function ( name ) {
  462. pu.setValue( gl, name, u[ name ].value );
  463. } );
  464. }
  465. }
  466. }
  467. for ( var i = 0; i < instanceCount; i ++ ) {
  468. var object = new Mesh( geo, material );
  469. objectCount ++;
  470. randomizeMatrix( matrix );
  471. object.applyMatrix( matrix );
  472. var pickingObject;
  473. if ( ! useOverrideMaterial ) {
  474. pickingObject = object.clone();
  475. objectCount ++;
  476. }
  477. object.material = material;
  478. object.userData[ "color" ] = Math.random() * 0xffffff;
  479. if ( useOverrideMaterial ) {
  480. object.userData[ "pickingColor" ] = i + 1;
  481. object.onBeforeRender = onBeforeRender;
  482. } else {
  483. pickingObject.material = pickingMaterial;
  484. pickingObject.userData[ "pickingColor" ] = i + 1;
  485. pickingObject.onBeforeRender = onBeforeRender;
  486. }
  487. pickingData[ i + 1 ] = object;
  488. scene.add( object );
  489. if ( ! useOverrideMaterial ) pickingScene.add( pickingObject );
  490. }
  491. }
  492. function makeMerged( geo ) {
  493. // material
  494. var vert = document.getElementById( 'vertMerged' ).textContent;
  495. var frag = document.getElementById( 'fragMerged' ).textContent;
  496. var material = new RawShaderMaterial( {
  497. vertexShader: vert,
  498. fragmentShader: frag
  499. } );
  500. materialList.push( material );
  501. var pickingMaterial = new RawShaderMaterial( {
  502. vertexShader: "#define PICKING\n" + vert,
  503. fragmentShader: "#define PICKING\n" + frag
  504. } );
  505. materialList.push( pickingMaterial );
  506. // geometry
  507. var mgeo = new BufferGeometry();
  508. geometryList.push( mgeo );
  509. var pos = geo.attributes.position;
  510. var posLen = geo.attributes.position.count * 3;
  511. var vertices = new BufferAttribute(
  512. new Float32Array( instanceCount * posLen ), 3
  513. );
  514. var vertex = new Vector3();
  515. var matrix = new Matrix4();
  516. for ( var i = 0, ul = instanceCount; i < ul; i ++ ) {
  517. var offset = i * posLen;
  518. randomizeMatrix( matrix );
  519. var object = new Object3D();
  520. objectCount ++;
  521. object.applyMatrix( matrix );
  522. pickingData[ i + 1 ] = object;
  523. vertices.set( pos.array, offset );
  524. for ( var k = 0, l = offset; k < posLen; k += 3, l += 3 ) {
  525. vertex.fromArray( vertices.array, l );
  526. vertex.applyMatrix4( matrix );
  527. vertex.toArray( vertices.array, l );
  528. }
  529. }
  530. mgeo.addAttribute( 'position', vertices );
  531. var colCount = posLen / 3;
  532. var colors = new BufferAttribute(
  533. new Float32Array( instanceCount * colCount * 3 ), 3
  534. );
  535. var randCol = function () {
  536. return Math.random();
  537. };
  538. for ( var i = 0, ul = instanceCount; i < ul; i ++ ) {
  539. var r = randCol(), g = randCol(), b = randCol();
  540. for ( var j = i * colCount, jl = ( i + 1 ) * colCount; j < jl; j ++ ) {
  541. colors.setXYZ( j, r, g, b );
  542. }
  543. }
  544. mgeo.addAttribute( 'color', colors );
  545. var col = new Color();
  546. var pickingColors = new BufferAttribute(
  547. new Float32Array( instanceCount * colCount * 3 ), 3
  548. );
  549. for ( var i = 0, ul = instanceCount; i < ul; i ++ ) {
  550. col.setHex( i + 1 );
  551. for ( var j = i * colCount, jl = ( i + 1 ) * colCount; j < jl; j ++ ) {
  552. pickingColors.setXYZ( j, col.r, col.g, col.b );
  553. }
  554. }
  555. mgeo.addAttribute( 'pickingColor', pickingColors );
  556. // mesh
  557. var mesh = new Mesh( mgeo, material );
  558. scene.add( mesh );
  559. var pickingMesh = new Mesh( mgeo, pickingMaterial );
  560. pickingScene.add( pickingMesh );
  561. }
  562. function makeInstanced( geo ) {
  563. // material
  564. var vert = document.getElementById( 'vertInstanced' ).textContent;
  565. var frag = document.getElementById( 'fragInstanced' ).textContent;
  566. var material = new RawShaderMaterial( {
  567. vertexShader: vert,
  568. fragmentShader: frag,
  569. } );
  570. materialList.push( material );
  571. var pickingMaterial = new RawShaderMaterial( {
  572. vertexShader: "#define PICKING\n" + vert,
  573. fragmentShader: "#define PICKING\n" + frag
  574. } );
  575. materialList.push( pickingMaterial );
  576. // geometry
  577. var igeo = new InstancedBufferGeometry();
  578. geometryList.push( igeo );
  579. var vertices = geo.attributes.position.clone();
  580. igeo.addAttribute( 'position', vertices );
  581. // var matrices = new InstancedBufferAttribute(
  582. // new Float32Array( instanceCount * 16 ), 16
  583. // );
  584. var mcol0 = new InstancedBufferAttribute(
  585. new Float32Array( instanceCount * 3 ), 3
  586. );
  587. var mcol1 = new InstancedBufferAttribute(
  588. new Float32Array( instanceCount * 3 ), 3
  589. );
  590. var mcol2 = new InstancedBufferAttribute(
  591. new Float32Array( instanceCount * 3 ), 3
  592. );
  593. var mcol3 = new InstancedBufferAttribute(
  594. new Float32Array( instanceCount * 3 ), 3
  595. );
  596. var matrix = new Matrix4();
  597. var me = matrix.elements;
  598. for ( var i = 0, ul = mcol0.count; i < ul; i ++ ) {
  599. randomizeMatrix( matrix );
  600. var object = new Object3D();
  601. objectCount ++;
  602. object.applyMatrix( matrix );
  603. pickingData[ i + 1 ] = object;
  604. // matrices.set( matrix.elements, i * 16 );
  605. mcol0.setXYZ( i, me[ 0 ], me[ 1 ], me[ 2 ] );
  606. mcol1.setXYZ( i, me[ 4 ], me[ 5 ], me[ 6 ] );
  607. mcol2.setXYZ( i, me[ 8 ], me[ 9 ], me[ 10 ] );
  608. mcol3.setXYZ( i, me[ 12 ], me[ 13 ], me[ 14 ] );
  609. }
  610. // igeo.addAttribute( 'matrix', matrices );
  611. igeo.addAttribute( 'mcol0', mcol0 );
  612. igeo.addAttribute( 'mcol1', mcol1 );
  613. igeo.addAttribute( 'mcol2', mcol2 );
  614. igeo.addAttribute( 'mcol3', mcol3 );
  615. var randCol = function () {
  616. return Math.random();
  617. };
  618. var colors = new InstancedBufferAttribute(
  619. new Float32Array( instanceCount * 3 ), 3
  620. );
  621. for ( var i = 0, ul = colors.count; i < ul; i ++ ) {
  622. colors.setXYZ( i, randCol(), randCol(), randCol() );
  623. }
  624. igeo.addAttribute( 'color', colors );
  625. var col = new Color();
  626. var pickingColors = new InstancedBufferAttribute(
  627. new Float32Array( instanceCount * 3 ), 3
  628. );
  629. for ( var i = 0, ul = pickingColors.count; i < ul; i ++ ) {
  630. col.setHex( i + 1 );
  631. pickingColors.setXYZ( i, col.r, col.g, col.b );
  632. }
  633. igeo.addAttribute( 'pickingColor', pickingColors );
  634. // mesh
  635. var mesh = new Mesh( igeo, material );
  636. scene.add( mesh );
  637. var pickingMesh = new Mesh( igeo, pickingMaterial );
  638. pickingScene.add( pickingMesh );
  639. }
  640. function init() {
  641. // camera
  642. camera = new PerspectiveCamera(
  643. 70, window.innerWidth / window.innerHeight, 1, 100
  644. );
  645. camera.position.z = 40;
  646. // picking render target
  647. pickingRenderTarget = new WebGLRenderTarget(
  648. window.innerWidth, window.innerHeight
  649. );
  650. pickingRenderTarget.texture.generateMipmaps = false;
  651. pickingRenderTarget.texture.minFilter = NearestFilter;
  652. // highlight box
  653. highlightBox = new Mesh(
  654. new BoxBufferGeometry( 1, 1, 1 ),
  655. new MeshLambertMaterial( {
  656. emissive: 0xffff00,
  657. transparent: true,
  658. opacity: 0.5
  659. } )
  660. );
  661. // renderer
  662. container = document.getElementById( "container" );
  663. renderer = new WebGLRenderer( {
  664. antialias: true,
  665. alpha: true
  666. } );
  667. if ( renderer.extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  668. document.getElementById( "notSupported" ).style.display = "";
  669. return;
  670. }
  671. renderer.setPixelRatio( window.devicePixelRatio );
  672. renderer.setSize( window.innerWidth, window.innerHeight );
  673. //renderer.sortObjects = false;
  674. container.appendChild( renderer.domElement );
  675. if ( renderer.extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  676. throw 'ANGLE_instanced_arrays not supported';
  677. }
  678. // controls
  679. controls = new TrackballControls(
  680. camera, renderer.domElement
  681. );
  682. controls.staticMoving = true;
  683. // stats
  684. stats = new Stats();
  685. container.appendChild( stats.dom );
  686. // listeners
  687. renderer.domElement.addEventListener( 'mousemove', onMouseMove );
  688. window.addEventListener( 'resize', onWindowResize, false );
  689. }
  690. //
  691. function onMouseMove( e ) {
  692. mouse.x = e.clientX;
  693. mouse.y = e.clientY;
  694. controls.update();
  695. requestAnimationFrame( render );
  696. }
  697. function onWindowResize() {
  698. camera.aspect = window.innerWidth / window.innerHeight;
  699. camera.updateProjectionMatrix();
  700. renderer.setSize( window.innerWidth, window.innerHeight );
  701. pickingRenderTarget.setSize( window.innerWidth, window.innerHeight );
  702. }
  703. function animate() {
  704. if ( doAnimate ) {
  705. requestAnimationFrame( animate );
  706. }
  707. controls.update();
  708. stats.update();
  709. render();
  710. }
  711. function pick() {
  712. // render the picking scene off-screen
  713. highlightBox.visible = false;
  714. renderer.setRenderTarget( pickingRenderTarget );
  715. if ( singlePickingMaterial ) {
  716. scene.overrideMaterial = singlePickingMaterial;
  717. renderer.render( scene, camera );
  718. scene.overrideMaterial = null;
  719. } else {
  720. renderer.render( pickingScene, camera );
  721. }
  722. // read the pixel under the mouse from the texture
  723. renderer.readRenderTargetPixels(
  724. pickingRenderTarget,
  725. mouse.x,
  726. pickingRenderTarget.height - mouse.y,
  727. 1,
  728. 1,
  729. pixelBuffer
  730. );
  731. // interpret the pixel as an ID
  732. var id =
  733. ( pixelBuffer[ 0 ] << 16 ) |
  734. ( pixelBuffer[ 1 ] << 8 ) |
  735. ( pixelBuffer[ 2 ] );
  736. var object = pickingData[ id ];
  737. if ( object ) {
  738. // move the highlightBox so that it surrounds the picked object
  739. if ( object.position && object.rotation && object.scale ) {
  740. highlightBox.position.copy( object.position );
  741. highlightBox.rotation.copy( object.rotation );
  742. highlightBox.scale.copy( object.scale )
  743. .multiply( geometrySize )
  744. .multiplyScalar( scale );
  745. highlightBox.visible = true;
  746. }
  747. } else {
  748. highlightBox.visible = false;
  749. }
  750. }
  751. function render() {
  752. pick();
  753. renderer.setRenderTarget( null );
  754. renderer.render( scene, camera );
  755. }
  756. </script>
  757. </body>
  758. </html>