webgl_loader_obj2_meshspray.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - Mesh Spray</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. <style>
  8. body {
  9. font-family: Monospace;
  10. background-color: #000;
  11. color: #fff;
  12. margin: 0 0 0 0;
  13. padding: 0 0 0 0;
  14. border: none;
  15. cursor: default;
  16. }
  17. #info {
  18. color: #fff;
  19. position: absolute;
  20. top: 10px;
  21. width: 100%;
  22. text-align: center;
  23. z-index: 100;
  24. display:block;
  25. }
  26. #info a {
  27. color: #f00;
  28. font-weight: bold;
  29. text-decoration: underline;
  30. cursor: pointer
  31. }
  32. #glFullscreen {
  33. width: 100%;
  34. height: 100vh;
  35. min-width: 640px;
  36. min-height: 360px;
  37. position: relative;
  38. overflow: hidden;
  39. z-index: 0;
  40. }
  41. #example {
  42. width: 100%;
  43. height: 100%;
  44. top: 0;
  45. left: 0;
  46. background-color: #000000;
  47. }
  48. #feedback {
  49. color: darkorange;
  50. }
  51. #dat {
  52. user-select: none;
  53. position: absolute;
  54. left: 0;
  55. top: 0;
  56. z-Index: 200;
  57. }
  58. </style>
  59. </head>
  60. <body>
  61. <div id="glFullscreen">
  62. <canvas id="example"></canvas>
  63. </div>
  64. <div id="dat">
  65. </div>
  66. <div id="info">
  67. <a href="http://threejs.org" target="_blank">three.js</a> - Mesh Spray
  68. <div id="feedback"></div>
  69. </div>
  70. <script src="js/Detector.js"></script>
  71. <script src="../build/three.js"></script>
  72. <script src="js/controls/TrackballControls.js"></script>
  73. <script src="js/libs/dat.gui.min.js"></script>
  74. <script src="js/loaders/LoaderSupport.js"></script>
  75. <script>
  76. 'use strict';
  77. var MeshSpray = (function () {
  78. var Validator = THREE.LoaderSupport.Validator;
  79. function MeshSpray( manager ) {
  80. this.manager = Validator.verifyInput( manager, THREE.DefaultLoadingManager );
  81. this.logging = {
  82. enabled: true,
  83. debug: false
  84. };
  85. this.instanceNo = 0;
  86. this.loaderRootNode = new THREE.Group();
  87. this.meshBuilder = new THREE.LoaderSupport.MeshBuilder();
  88. this.callbacks = new THREE.LoaderSupport.Callbacks();
  89. this.workerSupport = null;
  90. }
  91. MeshSpray.prototype.setLogging = function ( enabled, debug ) {
  92. this.logging.enabled = enabled === true;
  93. this.logging.debug = debug === true;
  94. this.meshBuilder.setLogging( this.logging.enabled, this.logging.debug );
  95. };
  96. MeshSpray.prototype.setStreamMeshesTo = function ( streamMeshesTo ) {
  97. this.loaderRootNode = Validator.verifyInput( streamMeshesTo, this.loaderRootNode );
  98. };
  99. MeshSpray.prototype.setForceWorkerDataCopy = function ( forceWorkerDataCopy ) {
  100. // nothing to do here
  101. };
  102. MeshSpray.prototype.run = function ( prepData, workerSupportExternal ) {
  103. if ( THREE.LoaderSupport.Validator.isValid( workerSupportExternal ) ) {
  104. this.workerSupport = workerSupportExternal;
  105. this.logging.enabled = this.workerSupport.logging.enabled;
  106. this.logging.debug = this.workerSupport.logging.debug;
  107. } else {
  108. this.workerSupport = THREE.LoaderSupport.Validator.verifyInput( this.workerSupport, new THREE.LoaderSupport.WorkerSupport() );
  109. }
  110. if ( this.logging.enabled ) console.time( 'MeshSpray' + this.instanceNo );
  111. this._applyPrepData( prepData );
  112. this.meshBuilder.init();
  113. var scope = this;
  114. var scopeBuilderFunc = function ( payload ) {
  115. var meshes = scope.meshBuilder.processPayload( payload );
  116. var mesh;
  117. for ( var i in meshes ) {
  118. mesh = meshes[ i ];
  119. scope.loaderRootNode.add( mesh );
  120. }
  121. };
  122. var scopeFuncComplete = function ( message ) {
  123. var callback = scope.callbacks.onLoad;
  124. if ( THREE.LoaderSupport.Validator.isValid( callback ) ) callback(
  125. {
  126. detail: {
  127. loaderRootNode: scope.loaderRootNode,
  128. modelName: scope.modelName,
  129. instanceNo: scope.instanceNo
  130. }
  131. }
  132. );
  133. if ( scope.logging.enabled ) console.timeEnd( 'MeshSpray' + scope.instanceNo );
  134. };
  135. var buildCode = function ( funcBuildObject, funcBuildSingleton ) {
  136. var workerCode = '';
  137. workerCode += '/**\n';
  138. workerCode += ' * This code was constructed by MeshSpray buildCode.\n';
  139. workerCode += ' */\n\n';
  140. workerCode += 'THREE.LoaderSupport = {};\n\n';
  141. workerCode += funcBuildObject( 'THREE.LoaderSupport.Validator', THREE.LoaderSupport.Validator );
  142. workerCode += funcBuildSingleton( 'Parser', Parser );
  143. return workerCode;
  144. };
  145. var libs2Load = [ 'build/three.min.js' ];
  146. this.workerSupport.validate( buildCode, 'Parser', libs2Load, '../' );
  147. this.workerSupport.setCallbacks( scopeBuilderFunc, scopeFuncComplete );
  148. this.workerSupport.run(
  149. {
  150. params: {
  151. dimension: prepData.dimension,
  152. quantity: prepData.quantity,
  153. globalObjectCount: prepData.globalObjectCount
  154. },
  155. materials: {
  156. serializedMaterials: this.meshBuilder.getMaterialsJSON()
  157. },
  158. logging: {
  159. enabled: this.logging.enabled,
  160. debug: this.logging.debug
  161. },
  162. data: {
  163. input: null,
  164. options: null
  165. }
  166. }
  167. );
  168. };
  169. MeshSpray.prototype._applyPrepData = function ( prepData ) {
  170. if ( Validator.isValid( prepData ) ) {
  171. this.setLogging( prepData.logging.enabled, prepData.logging.debug );
  172. this.setStreamMeshesTo( prepData.streamMeshesTo );
  173. this.meshBuilder.setMaterials( prepData.materials );
  174. this._setCallbacks( prepData.getCallbacks() );
  175. }
  176. };
  177. MeshSpray.prototype._setCallbacks = function ( callbacks ) {
  178. if ( Validator.isValid( callbacks.onProgress ) ) this.callbacks.setCallbackOnProgress( callbacks.onProgress );
  179. if ( Validator.isValid( callbacks.onMeshAlter ) ) this.callbacks.setCallbackOnMeshAlter( callbacks.onMeshAlter );
  180. if ( Validator.isValid( callbacks.onLoad ) ) this.callbacks.setCallbackOnLoad( callbacks.onLoad );
  181. if ( Validator.isValid( callbacks.onLoadMaterials ) ) this.callbacks.setCallbackOnLoadMaterials( callbacks.onLoadMaterials );
  182. this.meshBuilder._setCallbacks( this.callbacks );
  183. };
  184. var Parser = ( function () {
  185. function Parser() {
  186. this.sizeFactor = 0.5;
  187. this.localOffsetFactor = 1.0;
  188. this.globalObjectCount = 0;
  189. this.debug = false;
  190. this.dimension = 200;
  191. this.quantity = 1;
  192. this.callbackMeshBuilder = null;
  193. this.callbackProgress = null;
  194. this.serializedMaterials = null;
  195. this.logging = {
  196. enabled: true,
  197. debug: false
  198. };
  199. };
  200. Parser.prototype.setLogging = function ( enabled, debug ) {
  201. this.logging.enabled = enabled === true;
  202. this.logging.debug = debug === true;
  203. };
  204. Parser.prototype.parse = function () {
  205. var baseTriangle = [ 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 0.0, -1.0, 1.0 ];
  206. var vertices = [];
  207. var colors = [];
  208. var normals = [];
  209. var uvs = [];
  210. var dimensionHalf = this.dimension / 2;
  211. var fixedOffsetX;
  212. var fixedOffsetY;
  213. var fixedOffsetZ;
  214. var s, t;
  215. // complete triangle
  216. // local coords offset
  217. var localOffsetFactor = this.localOffsetFactor;
  218. for ( var i = 0; i < this.quantity; i++ ) {
  219. var sizeVaring = this.sizeFactor * Math.random();
  220. s = 2 * Math.PI * Math.random();
  221. t = Math.PI * Math.random();
  222. fixedOffsetX = dimensionHalf * Math.random() * Math.cos( s ) * Math.sin( t );
  223. fixedOffsetY = dimensionHalf * Math.random() * Math.sin( s ) * Math.sin( t );
  224. fixedOffsetZ = dimensionHalf * Math.random() * Math.cos( t );
  225. for ( var j = 0; j < baseTriangle.length; j += 3 ) {
  226. vertices.push( baseTriangle[ j ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetX );
  227. vertices.push( baseTriangle[ j + 1 ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetY );
  228. vertices.push( baseTriangle[ j + 2 ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetZ );
  229. colors.push( Math.random() );
  230. colors.push( Math.random() );
  231. colors.push( Math.random() );
  232. }
  233. }
  234. var absoluteVertexCount = vertices.length;
  235. var absoluteColorCount = colors.length;
  236. var absoluteNormalCount = 0;
  237. var absoluteUvCount = 0;
  238. var vertexFA = new Float32Array( absoluteVertexCount );
  239. var colorFA = ( absoluteColorCount > 0 ) ? new Float32Array( absoluteColorCount ) : null;
  240. var normalFA = ( absoluteNormalCount > 0 ) ? new Float32Array( absoluteNormalCount ) : null;
  241. var uvFA = ( absoluteUvCount > 0 ) ? new Float32Array( absoluteUvCount ) : null;
  242. vertexFA.set( vertices, 0 );
  243. if ( colorFA ) {
  244. colorFA.set( colors, 0 );
  245. }
  246. if ( normalFA ) {
  247. normalFA.set( normals, 0 );
  248. }
  249. if ( uvFA ) {
  250. uvFA.set( uvs, 0 );
  251. }
  252. /*
  253. * This demonstrates the usage of embedded three.js in the worker blob and
  254. * the serialization of materials back to the Builder outside the worker.
  255. *
  256. * This is not the most effective way, but outlining possibilities
  257. */
  258. var materialName = 'defaultVertexColorMaterial_double';
  259. var defaultVertexColorMaterialJson = this.serializedMaterials[ 'defaultVertexColorMaterial' ];
  260. var loader = new THREE.MaterialLoader();
  261. var defaultVertexColorMaterialDouble = loader.parse( defaultVertexColorMaterialJson );
  262. defaultVertexColorMaterialDouble.name = materialName;
  263. defaultVertexColorMaterialDouble.side = THREE.DoubleSide;
  264. var newSerializedMaterials = {};
  265. newSerializedMaterials[ materialName ] = defaultVertexColorMaterialDouble.toJSON();
  266. var payload = {
  267. cmd: 'materialData',
  268. materials: {
  269. serializedMaterials: newSerializedMaterials
  270. }
  271. };
  272. this.callbackMeshBuilder( payload );
  273. this.globalObjectCount++;
  274. this.callbackMeshBuilder(
  275. {
  276. cmd: 'meshData',
  277. progress: {
  278. numericalValue: 1.0
  279. },
  280. params: {
  281. meshName: 'Gen' + this.globalObjectCount
  282. },
  283. materials: {
  284. multiMaterial: false,
  285. materialNames: [ materialName ],
  286. materialGroups: []
  287. },
  288. buffers: {
  289. vertices: vertexFA,
  290. colors: colorFA,
  291. normals: normalFA,
  292. uvs: uvFA
  293. }
  294. },
  295. [ vertexFA.buffer ],
  296. colorFA !== null ? [ colorFA.buffer ] : null,
  297. normalFA !== null ? [ normalFA.buffer ] : null,
  298. uvFA !== null ? [ uvFA.buffer ] : null
  299. );
  300. if ( this.logging.enabled ) console.info( 'Global output object count: ' + this.globalObjectCount );
  301. };
  302. return Parser;
  303. })();
  304. Parser.prototype.setSerializedMaterials = function ( serializedMaterials ) {
  305. if ( THREE.LoaderSupport.Validator.isValid( serializedMaterials ) ) {
  306. this.serializedMaterials = serializedMaterials;
  307. }
  308. };
  309. return MeshSpray;
  310. })();
  311. var MeshSprayApp = (function () {
  312. function MeshSprayApp( elementToBindTo ) {
  313. this.renderer = null;
  314. this.canvas = elementToBindTo;
  315. this.aspectRatio = 1;
  316. this.recalcAspectRatio();
  317. this.scene = null;
  318. this.cameraDefaults = {
  319. posCamera: new THREE.Vector3( 500.0, 500.0, 1000.0 ),
  320. posCameraTarget: new THREE.Vector3( 0, 0, 0 ),
  321. near: 0.1,
  322. far: 10000,
  323. fov: 45
  324. };
  325. this.camera = null;
  326. this.cameraTarget = this.cameraDefaults.posCameraTarget;
  327. this.controls = null;
  328. this.cube = null;
  329. this.pivot = null;
  330. }
  331. MeshSprayApp.prototype.initGL = function () {
  332. this.renderer = new THREE.WebGLRenderer( {
  333. canvas: this.canvas,
  334. antialias: true,
  335. autoClear: true
  336. } );
  337. this.renderer.setClearColor( 0x050505 );
  338. this.scene = new THREE.Scene();
  339. this.camera = new THREE.PerspectiveCamera( this.cameraDefaults.fov, this.aspectRatio, this.cameraDefaults.near, this.cameraDefaults.far );
  340. this.resetCamera();
  341. this.controls = new THREE.TrackballControls( this.camera, this.renderer.domElement );
  342. var ambientLight = new THREE.AmbientLight( 0x404040 );
  343. var directionalLight1 = new THREE.DirectionalLight( 0xC0C090 );
  344. var directionalLight2 = new THREE.DirectionalLight( 0xC0C090 );
  345. directionalLight1.position.set( -100, -50, 100 );
  346. directionalLight2.position.set( 100, 50, -100 );
  347. this.scene.add( directionalLight1 );
  348. this.scene.add( directionalLight2 );
  349. this.scene.add( ambientLight );
  350. var helper = new THREE.GridHelper( 1200, 60, 0xFF4444, 0x404040 );
  351. this.scene.add( helper );
  352. var geometry = new THREE.BoxBufferGeometry( 10, 10, 10 );
  353. var material = new THREE.MeshNormalMaterial();
  354. this.cube = new THREE.Mesh( geometry, material );
  355. this.cube.position.set( 0, 0, 0 );
  356. this.scene.add( this.cube );
  357. this.pivot = new THREE.Object3D();
  358. this.pivot.name = 'Pivot';
  359. this.scene.add( this.pivot );
  360. };
  361. MeshSprayApp.prototype.initContent = function () {
  362. var maxQueueSize = 1024;
  363. var maxWebWorkers = 4;
  364. var radius = 640;
  365. var workerDirector = new THREE.LoaderSupport.WorkerDirector( MeshSpray );
  366. workerDirector.setLogging( false, false );
  367. workerDirector.setCrossOrigin( 'anonymous' );
  368. var callbackOnLoad = function ( event ) {
  369. console.info( 'Worker #' + event.detail.instanceNo + ': Completed loading. (#' + workerDirector.objectsCompleted + ')' );
  370. };
  371. var reportProgress = function( event ) {
  372. document.getElementById( 'feedback' ).innerHTML = event.detail.text;
  373. console.info( event.detail.text );
  374. };
  375. var callbackMeshAlter = function ( event ) {
  376. var override = new THREE.LoaderSupport.LoadedMeshUserOverride( false, true );
  377. event.detail.side = THREE.DoubleSide;
  378. var mesh = new THREE.Mesh( event.detail.bufferGeometry, event.detail.material );
  379. mesh.name = event.detail.meshName;
  380. override.addMesh( mesh );
  381. return override;
  382. };
  383. var callbacks = new THREE.LoaderSupport.Callbacks();
  384. callbacks.setCallbackOnMeshAlter( callbackMeshAlter );
  385. callbacks.setCallbackOnLoad( callbackOnLoad );
  386. callbacks.setCallbackOnProgress( reportProgress );
  387. workerDirector.prepareWorkers( callbacks, maxQueueSize, maxWebWorkers );
  388. var prepData;
  389. var pivot;
  390. var s, t, r, x, y, z;
  391. var globalObjectCount = 0;
  392. for ( var i = 0; i < maxQueueSize; i++ ) {
  393. prepData = new THREE.LoaderSupport.PrepData( 'Triangles_' + i );
  394. pivot = new THREE.Object3D();
  395. s = 2 * Math.PI * Math.random();
  396. t = Math.PI * Math.random();
  397. r = radius * Math.random();
  398. x = r * Math.cos( s ) * Math.sin( t );
  399. y = r * Math.sin( s ) * Math.sin( t );
  400. z = r * Math.cos( t );
  401. pivot.position.set( x, y, z );
  402. this.scene.add( pivot );
  403. prepData.streamMeshesTo = pivot;
  404. prepData.setLogging( false, false );
  405. prepData.quantity = 8192;
  406. prepData.dimension = Math.max( Math.random() * 500, 100 );
  407. prepData.globalObjectCount = globalObjectCount++;
  408. workerDirector.enqueueForRun( prepData );
  409. }
  410. workerDirector.processQueue();
  411. };
  412. MeshSprayApp.prototype.resizeDisplayGL = function () {
  413. this.controls.handleResize();
  414. this.recalcAspectRatio();
  415. this.renderer.setSize( this.canvas.offsetWidth, this.canvas.offsetHeight, false );
  416. this.updateCamera();
  417. };
  418. MeshSprayApp.prototype.recalcAspectRatio = function () {
  419. this.aspectRatio = ( this.canvas.offsetHeight === 0 ) ? 1 : this.canvas.offsetWidth / this.canvas.offsetHeight;
  420. };
  421. MeshSprayApp.prototype.resetCamera = function () {
  422. this.camera.position.copy( this.cameraDefaults.posCamera );
  423. this.cameraTarget.copy( this.cameraDefaults.posCameraTarget );
  424. this.updateCamera();
  425. };
  426. MeshSprayApp.prototype.updateCamera = function () {
  427. this.camera.aspect = this.aspectRatio;
  428. this.camera.lookAt( this.cameraTarget );
  429. this.camera.updateProjectionMatrix();
  430. };
  431. MeshSprayApp.prototype.render = function () {
  432. if ( ! this.renderer.autoClear ) this.renderer.clear();
  433. this.controls.update();
  434. this.cube.rotation.x += 0.05;
  435. this.cube.rotation.y += 0.05;
  436. this.renderer.render( this.scene, this.camera );
  437. };
  438. return MeshSprayApp;
  439. })();
  440. var app = new MeshSprayApp( document.getElementById( 'example' ) );
  441. // init three.js example application
  442. var resizeWindow = function () {
  443. app.resizeDisplayGL();
  444. };
  445. var render = function () {
  446. requestAnimationFrame( render );
  447. app.render();
  448. };
  449. window.addEventListener( 'resize', resizeWindow, false );
  450. console.log( 'Starting initialisation phase...' );
  451. app.initGL();
  452. app.resizeDisplayGL();
  453. app.initContent();
  454. render();
  455. </script>
  456. </body>
  457. </html>