webgl_loader_obj2_meshspray.html 15 KB

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