webgl_loader_obj2_meshspray.html 15 KB

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