webgl_loader_obj2_meshspray.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. MeshSpray.prototype = Object.create( THREE.LoaderSupport.LoaderBase.prototype );
  79. MeshSpray.prototype.constructor = MeshSpray;
  80. function MeshSpray( manager, logger ) {
  81. THREE.LoaderSupport.LoaderBase.call( this, manager, logger );
  82. this.workerSupport = null;
  83. this.logger = new THREE.LoaderSupport.ConsoleLogger();
  84. };
  85. MeshSpray.prototype.run = function ( prepData, workerSupportExternal ) {
  86. if ( THREE.LoaderSupport.Validator.isValid( workerSupportExternal ) ) {
  87. this.workerSupport = workerSupportExternal;
  88. this.logger = workerSupportExternal.logger;
  89. } else {
  90. this.workerSupport = THREE.LoaderSupport.Validator.verifyInput( this.workerSupport, new THREE.LoaderSupport.WorkerSupport() );
  91. }
  92. this.logger.logTimeStart( 'MeshSpray' );
  93. this._applyPrepData( prepData );
  94. var scope = this;
  95. var scopeBuilderFunc = function ( payload ) {
  96. var meshes = scope.builder.processPayload( payload );
  97. var mesh;
  98. for ( var i in meshes ) {
  99. mesh = meshes[ i ];
  100. scope.loaderRootNode.add( mesh );
  101. }
  102. };
  103. var scopeFuncComplete = function ( message ) {
  104. var callback = scope.callbacks.onLoad;
  105. if ( THREE.LoaderSupport.Validator.isValid( callback ) ) callback(
  106. {
  107. detail: {
  108. loaderRootNode: scope.loaderRootNode,
  109. modelName: scope.modelName,
  110. instanceNo: scope.instanceNo
  111. }
  112. }
  113. );
  114. scope.logger.logTimeEnd( 'MeshSpray' );
  115. };
  116. var buildCode = function ( funcBuildObject, funcBuildSingleton ) {
  117. var workerCode = '';
  118. workerCode += '/**\n';
  119. workerCode += ' * This code was constructed by MeshSpray buildCode.\n';
  120. workerCode += ' */\n\n';
  121. workerCode += 'THREE.LoaderSupport = {};\n\n';
  122. workerCode += funcBuildObject( 'THREE.LoaderSupport.Validator', THREE.LoaderSupport.Validator );
  123. workerCode += funcBuildSingleton( 'THREE.LoaderSupport.ConsoleLogger', THREE.LoaderSupport.ConsoleLogger );
  124. workerCode += funcBuildSingleton( 'Parser', Parser );
  125. return workerCode;
  126. };
  127. var libs2Load = [ 'build/three.min.js' ];
  128. this.workerSupport.validate( buildCode, 'Parser', libs2Load, '../' );
  129. this.workerSupport.setCallbacks( scopeBuilderFunc, scopeFuncComplete );
  130. this.workerSupport.run(
  131. {
  132. params: {
  133. dimension: prepData.dimension,
  134. quantity: prepData.quantity,
  135. globalObjectCount: prepData.globalObjectCount
  136. },
  137. materials: {
  138. serializedMaterials: this.builder.getMaterialsJSON()
  139. },
  140. logger: {
  141. debug: this.logger.debug,
  142. enabled: this.logger.enabled
  143. },
  144. data: {
  145. input: null,
  146. options: null
  147. }
  148. }
  149. );
  150. };
  151. var Parser = ( function () {
  152. function Parser() {
  153. this.sizeFactor = 0.5;
  154. this.localOffsetFactor = 1.0;
  155. this.globalObjectCount = 0;
  156. this.debug = false;
  157. this.dimension = 200;
  158. this.quantity = 1;
  159. this.callbackBuilder = null;
  160. this.callbackProgress = null;
  161. this.logger = new THREE.LoaderSupport.ConsoleLogger();
  162. this.serializedMaterials = null;
  163. };
  164. Parser.prototype.setLogConfig = function ( enabled, debug ) {
  165. this.logger.setEnabled( enabled );
  166. this.logger.setDebug( debug );
  167. };
  168. Parser.prototype.parse = function () {
  169. var baseTriangle = [ 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 0.0, -1.0, 1.0 ];
  170. var vertices = [];
  171. var colors = [];
  172. var normals = [];
  173. var uvs = [];
  174. var dimensionHalf = this.dimension / 2;
  175. var fixedOffsetX;
  176. var fixedOffsetY;
  177. var fixedOffsetZ;
  178. var s, t;
  179. // complete triagle
  180. var sizeVaring = this.sizeFactor * Math.random();
  181. // local coords offset
  182. var localOffsetFactor = this.localOffsetFactor;
  183. for ( var i = 0; i < this.quantity; i++ ) {
  184. sizeVaring = this.sizeFactor * Math.random();
  185. s = 2 * Math.PI * Math.random();
  186. t = Math.PI * Math.random();
  187. fixedOffsetX = dimensionHalf * Math.random() * Math.cos( s ) * Math.sin( t );
  188. fixedOffsetY = dimensionHalf * Math.random() * Math.sin( s ) * Math.sin( t );
  189. fixedOffsetZ = dimensionHalf * Math.random() * Math.cos( t );
  190. for ( var j = 0; j < baseTriangle.length; j += 3 ) {
  191. vertices.push( baseTriangle[ j ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetX );
  192. vertices.push( baseTriangle[ j + 1 ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetY );
  193. vertices.push( baseTriangle[ j + 2 ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetZ );
  194. colors.push( Math.random() );
  195. colors.push( Math.random() );
  196. colors.push( Math.random() );
  197. }
  198. }
  199. var absoluteVertexCount = vertices.length;
  200. var absoluteColorCount = colors.length;
  201. var absoluteNormalCount = 0;
  202. var absoluteUvCount = 0;
  203. var vertexFA = new Float32Array( absoluteVertexCount );
  204. var colorFA = ( absoluteColorCount > 0 ) ? new Float32Array( absoluteColorCount ) : null;
  205. var normalFA = ( absoluteNormalCount > 0 ) ? new Float32Array( absoluteNormalCount ) : null;
  206. var uvFA = ( absoluteUvCount > 0 ) ? new Float32Array( absoluteUvCount ) : null;
  207. vertexFA.set( vertices, 0 );
  208. if ( colorFA ) {
  209. colorFA.set( colors, 0 );
  210. }
  211. if ( normalFA ) {
  212. normalFA.set( normals, 0 );
  213. }
  214. if ( uvFA ) {
  215. uvFA.set( uvs, 0 );
  216. }
  217. /*
  218. * This demonstrates the usage of embedded three.js in the worker blob and
  219. * the serialization of materials back to the Builder outside the worker.
  220. *
  221. * This is not the most effective way, but outlining possibilities
  222. */
  223. var materialName = 'defaultVertexColorMaterial_double';
  224. var defaultVertexColorMaterialJson = this.serializedMaterials[ 'defaultVertexColorMaterial' ];
  225. var loader = new THREE.MaterialLoader();
  226. var defaultVertexColorMaterialDouble = loader.parse( defaultVertexColorMaterialJson );
  227. defaultVertexColorMaterialDouble.name = materialName;
  228. defaultVertexColorMaterialDouble.side = THREE.DoubleSide;
  229. var newSerializedMaterials = {};
  230. newSerializedMaterials[ materialName ] = defaultVertexColorMaterialDouble.toJSON();
  231. var payload = {
  232. cmd: 'materialData',
  233. materials: {
  234. serializedMaterials: newSerializedMaterials
  235. }
  236. };
  237. this.callbackBuilder( payload );
  238. this.globalObjectCount++;
  239. this.callbackBuilder(
  240. {
  241. cmd: 'meshData',
  242. progress: {
  243. numericalValue: 1.0
  244. },
  245. params: {
  246. meshName: 'Gen' + this.globalObjectCount
  247. },
  248. materials: {
  249. multiMaterial: false,
  250. materialNames: [ materialName ],
  251. materialGroups: []
  252. },
  253. buffers: {
  254. vertices: vertexFA,
  255. colors: colorFA,
  256. normals: normalFA,
  257. uvs: uvFA
  258. }
  259. },
  260. [ vertexFA.buffer ],
  261. colorFA !== null ? [ colorFA.buffer ] : null,
  262. normalFA !== null ? [ normalFA.buffer ] : null,
  263. uvFA !== null ? [ uvFA.buffer ] : null
  264. );
  265. this.logger.logInfo( 'Global output object count: ' + this.globalObjectCount );
  266. };
  267. return Parser;
  268. })();
  269. Parser.prototype.setSerializedMaterials = function ( serializedMaterials ) {
  270. if ( THREE.LoaderSupport.Validator.isValid( serializedMaterials ) ) {
  271. this.serializedMaterials = serializedMaterials;
  272. }
  273. };
  274. return MeshSpray;
  275. })();
  276. var MeshSprayApp = (function () {
  277. function MeshSprayApp( elementToBindTo ) {
  278. this.renderer = null;
  279. this.canvas = elementToBindTo;
  280. this.aspectRatio = 1;
  281. this.recalcAspectRatio();
  282. this.scene = null;
  283. this.cameraDefaults = {
  284. posCamera: new THREE.Vector3( 500.0, 500.0, 1000.0 ),
  285. posCameraTarget: new THREE.Vector3( 0, 0, 0 ),
  286. near: 0.1,
  287. far: 10000,
  288. fov: 45
  289. };
  290. this.camera = null;
  291. this.cameraTarget = this.cameraDefaults.posCameraTarget;
  292. this.controls = null;
  293. this.cube = null;
  294. this.pivot = null;
  295. }
  296. MeshSprayApp.prototype.initGL = function () {
  297. this.renderer = new THREE.WebGLRenderer( {
  298. canvas: this.canvas,
  299. antialias: true,
  300. autoClear: true
  301. } );
  302. this.renderer.setClearColor( 0x050505 );
  303. this.scene = new THREE.Scene();
  304. this.camera = new THREE.PerspectiveCamera( this.cameraDefaults.fov, this.aspectRatio, this.cameraDefaults.near, this.cameraDefaults.far );
  305. this.resetCamera();
  306. this.controls = new THREE.TrackballControls( this.camera, this.renderer.domElement );
  307. var ambientLight = new THREE.AmbientLight( 0x404040 );
  308. var directionalLight1 = new THREE.DirectionalLight( 0xC0C090 );
  309. var directionalLight2 = new THREE.DirectionalLight( 0xC0C090 );
  310. directionalLight1.position.set( -100, -50, 100 );
  311. directionalLight2.position.set( 100, 50, -100 );
  312. this.scene.add( directionalLight1 );
  313. this.scene.add( directionalLight2 );
  314. this.scene.add( ambientLight );
  315. var helper = new THREE.GridHelper( 1200, 60, 0xFF4444, 0x404040 );
  316. this.scene.add( helper );
  317. var geometry = new THREE.BoxGeometry( 10, 10, 10 );
  318. var material = new THREE.MeshNormalMaterial();
  319. this.cube = new THREE.Mesh( geometry, material );
  320. this.cube.position.set( 0, 0, 0 );
  321. this.scene.add( this.cube );
  322. this.pivot = new THREE.Object3D();
  323. this.pivot.name = 'Pivot';
  324. this.scene.add( this.pivot );
  325. };
  326. MeshSprayApp.prototype.initContent = function () {
  327. var maxQueueSize = 1024;
  328. var maxWebWorkers = 4;
  329. var radius = 640;
  330. var logger = new THREE.LoaderSupport.ConsoleLogger( false );
  331. var workerDirector = new THREE.LoaderSupport.WorkerDirector( MeshSpray, logger );
  332. workerDirector.setCrossOrigin( 'anonymous' );
  333. var callbackOnLoad = function ( event ) {
  334. logger.logInfo( 'Worker #' + event.detail.instanceNo + ': Completed loading. (#' + workerDirector.objectsCompleted + ')' );
  335. };
  336. var reportProgress = function( event ) {
  337. document.getElementById( 'feedback' ).innerHTML = event.detail.text;
  338. logger.logInfo( event.detail.text );
  339. };
  340. var callbackMeshAlter = function ( event ) {
  341. var override = new THREE.LoaderSupport.LoadedMeshUserOverride( false, true );
  342. event.detail.side = THREE.DoubleSide;
  343. var mesh = new THREE.Mesh( event.detail.bufferGeometry, event.detail.material );
  344. mesh.name = event.detail.meshName;
  345. override.addMesh( mesh );
  346. return override;
  347. };
  348. var callbacks = new THREE.LoaderSupport.Callbacks();
  349. callbacks.setCallbackOnMeshAlter( callbackMeshAlter );
  350. callbacks.setCallbackOnLoad( callbackOnLoad );
  351. callbacks.setCallbackOnProgress( reportProgress );
  352. workerDirector.prepareWorkers( callbacks, maxQueueSize, maxWebWorkers );
  353. var prepData;
  354. var pivot;
  355. var s, t, r, x, y, z;
  356. var globalObjectCount = 0;
  357. for ( var i = 0; i < maxQueueSize; i++ ) {
  358. prepData = new THREE.LoaderSupport.PrepData( 'Triangles_' + i );
  359. pivot = new THREE.Object3D();
  360. s = 2 * Math.PI * Math.random();
  361. t = Math.PI * Math.random();
  362. r = radius * Math.random();
  363. x = r * Math.cos( s ) * Math.sin( t );
  364. y = r * Math.sin( s ) * Math.sin( t );
  365. z = r * Math.cos( t );
  366. pivot.position.set( x, y, z );
  367. this.scene.add( pivot );
  368. prepData.setStreamMeshesTo( pivot );
  369. prepData.quantity = 8192;
  370. prepData.dimension = Math.max( Math.random() * 500, 100 );
  371. prepData.globalObjectCount = globalObjectCount++;
  372. workerDirector.enqueueForRun( prepData );
  373. }
  374. workerDirector.processQueue();
  375. };
  376. MeshSprayApp.prototype.resizeDisplayGL = function () {
  377. this.controls.handleResize();
  378. this.recalcAspectRatio();
  379. this.renderer.setSize( this.canvas.offsetWidth, this.canvas.offsetHeight, false );
  380. this.updateCamera();
  381. };
  382. MeshSprayApp.prototype.recalcAspectRatio = function () {
  383. this.aspectRatio = ( this.canvas.offsetHeight === 0 ) ? 1 : this.canvas.offsetWidth / this.canvas.offsetHeight;
  384. };
  385. MeshSprayApp.prototype.resetCamera = function () {
  386. this.camera.position.copy( this.cameraDefaults.posCamera );
  387. this.cameraTarget.copy( this.cameraDefaults.posCameraTarget );
  388. this.updateCamera();
  389. };
  390. MeshSprayApp.prototype.updateCamera = function () {
  391. this.camera.aspect = this.aspectRatio;
  392. this.camera.lookAt( this.cameraTarget );
  393. this.camera.updateProjectionMatrix();
  394. };
  395. MeshSprayApp.prototype.render = function () {
  396. if ( ! this.renderer.autoClear ) this.renderer.clear();
  397. this.controls.update();
  398. this.cube.rotation.x += 0.05;
  399. this.cube.rotation.y += 0.05;
  400. this.renderer.render( this.scene, this.camera );
  401. };
  402. return MeshSprayApp;
  403. })();
  404. var app = new MeshSprayApp( document.getElementById( 'example' ) );
  405. // init three.js example application
  406. var resizeWindow = function () {
  407. app.resizeDisplayGL();
  408. };
  409. var render = function () {
  410. requestAnimationFrame( render );
  411. app.render();
  412. };
  413. window.addEventListener( 'resize', resizeWindow, false );
  414. console.log( 'Starting initialisation phase...' );
  415. app.initGL();
  416. app.resizeDisplayGL();
  417. app.initContent();
  418. render();
  419. </script>
  420. </body>
  421. </html>