3DMLoader.js 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  1. import {
  2. BufferGeometryLoader,
  3. FileLoader,
  4. Loader,
  5. Object3D,
  6. MeshStandardMaterial,
  7. Mesh,
  8. Color,
  9. Points,
  10. PointsMaterial,
  11. Line,
  12. LineBasicMaterial,
  13. Matrix4,
  14. DirectionalLight,
  15. PointLight,
  16. SpotLight,
  17. RectAreaLight,
  18. Vector3,
  19. Sprite,
  20. SpriteMaterial,
  21. CanvasTexture,
  22. LinearFilter,
  23. ClampToEdgeWrapping,
  24. TextureLoader
  25. } from '../../../build/three.module.js';
  26. var Rhino3dmLoader = function ( manager ) {
  27. Loader.call( this, manager );
  28. this.libraryPath = '';
  29. this.libraryPending = null;
  30. this.libraryBinary = null;
  31. this.libraryConfig = {};
  32. this.workerLimit = 4;
  33. this.workerPool = [];
  34. this.workerNextTaskID = 1;
  35. this.workerSourceURL = '';
  36. this.workerConfig = {};
  37. this.materials = [];
  38. };
  39. Rhino3dmLoader.taskCache = new WeakMap();
  40. Rhino3dmLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  41. constructor: Rhino3dmLoader,
  42. setLibraryPath: function ( path ) {
  43. this.libraryPath = path;
  44. return this;
  45. },
  46. setWorkerLimit: function ( workerLimit ) {
  47. this.workerLimit = workerLimit;
  48. return this;
  49. },
  50. load: function ( url, onLoad, onProgress, onError ) {
  51. var loader = new FileLoader( this.manager );
  52. loader.setPath( this.path );
  53. loader.setResponseType( 'arraybuffer' );
  54. loader.setRequestHeader( this.requestHeader );
  55. loader.load( url, ( buffer ) => {
  56. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  57. // again from this thread.
  58. if ( Rhino3dmLoader.taskCache.has( buffer ) ) {
  59. var cachedTask = Rhino3dmLoader.taskCache.get( buffer );
  60. return cachedTask.promise.then( onLoad ).catch( onError );
  61. }
  62. this.decodeObjects( buffer, url )
  63. .then( onLoad )
  64. .catch( onError );
  65. }, onProgress, onError );
  66. },
  67. debug: function () {
  68. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  69. },
  70. decodeObjects: function ( buffer, url ) {
  71. var worker;
  72. var taskID;
  73. var taskCost = buffer.byteLength;
  74. var objectPending = this._getWorker( taskCost )
  75. .then( ( _worker ) => {
  76. worker = _worker;
  77. taskID = this.workerNextTaskID ++; //hmmm
  78. return new Promise( ( resolve, reject ) => {
  79. worker._callbacks[ taskID ] = { resolve, reject };
  80. worker.postMessage( { type: 'decode', id: taskID, buffer }, [ buffer ] );
  81. //this.debug();
  82. } );
  83. } )
  84. .then( ( message ) => this._createGeometry( message.data ) );
  85. // Remove task from the task list.
  86. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  87. objectPending
  88. .catch( () => true )
  89. .then( () => {
  90. if ( worker && taskID ) {
  91. this._releaseTask( worker, taskID );
  92. //this.debug();
  93. }
  94. } );
  95. // Cache the task result.
  96. Rhino3dmLoader.taskCache.set( buffer, {
  97. url: url,
  98. promise: objectPending
  99. } );
  100. return objectPending;
  101. },
  102. parse: function ( data, onLoad, onError ) {
  103. // issue: https://github.com/mcneel/rhino3dm/issues/338
  104. // issue: https://github.com/emscripten-core/emscripten/issues/13065
  105. if ( data instanceof Uint8Array ) {
  106. data = new Uint8Array( data ).buffer;
  107. }
  108. this.decodeObjects( data, '' )
  109. .then( onLoad )
  110. .catch( onError );
  111. },
  112. _compareMaterials: function ( material ) {
  113. var mat = {};
  114. mat.name = material.name;
  115. mat.color = {};
  116. mat.color.r = material.color.r;
  117. mat.color.g = material.color.g;
  118. mat.color.b = material.color.b;
  119. mat.type = material.type;
  120. for ( var i = 0; i < this.materials.length; i ++ ) {
  121. var m = this.materials[ i ];
  122. var _mat = {};
  123. _mat.name = m.name;
  124. _mat.color = {};
  125. _mat.color.r = m.color.r;
  126. _mat.color.g = m.color.g;
  127. _mat.color.b = m.color.b;
  128. _mat.type = m.type;
  129. if ( JSON.stringify( mat ) === JSON.stringify( _mat ) ) {
  130. return m;
  131. }
  132. }
  133. this.materials.push( material );
  134. return material;
  135. },
  136. _createMaterial: function ( material ) {
  137. if ( material === undefined ) {
  138. return new MeshStandardMaterial( {
  139. color: new Color( 1, 1, 1 ),
  140. metalness: 0.8,
  141. name: 'default',
  142. side: 2
  143. } );
  144. }
  145. var _diffuseColor = material.diffuseColor;
  146. var diffusecolor = new Color( _diffuseColor.r / 255.0, _diffuseColor.g / 255.0, _diffuseColor.b / 255.0 );
  147. if ( _diffuseColor.r === 0 && _diffuseColor.g === 0 && _diffuseColor.b === 0 ) {
  148. diffusecolor.r = 1;
  149. diffusecolor.g = 1;
  150. diffusecolor.b = 1;
  151. }
  152. // console.log( material );
  153. var mat = new MeshStandardMaterial( {
  154. color: diffusecolor,
  155. name: material.name,
  156. side: 2,
  157. transparent: material.transparency > 0 ? true : false,
  158. opacity: 1.0 - material.transparency
  159. } );
  160. var textureLoader = new TextureLoader();
  161. for ( var i = 0; i < material.textures.length; i ++ ) {
  162. var texture = material.textures[ i ];
  163. if ( texture.image !== null ) {
  164. var map = textureLoader.load( texture.image );
  165. switch ( texture.type ) {
  166. case 'Diffuse':
  167. mat.map = map;
  168. break;
  169. case 'Bump':
  170. mat.bumpMap = map;
  171. break;
  172. case 'Transparency':
  173. mat.alphaMap = map;
  174. mat.transparent = true;
  175. break;
  176. case 'Emap':
  177. mat.envMap = map;
  178. break;
  179. }
  180. }
  181. }
  182. return mat;
  183. },
  184. _createGeometry: function ( data ) {
  185. // console.log(data);
  186. var object = new Object3D();
  187. var instanceDefinitionObjects = [];
  188. var instanceDefinitions = [];
  189. var instanceReferences = [];
  190. object.userData[ 'layers' ] = data.layers;
  191. object.userData[ 'groups' ] = data.groups;
  192. object.userData[ 'settings' ] = data.settings;
  193. var objects = data.objects;
  194. var materials = data.materials;
  195. for ( var i = 0; i < objects.length; i ++ ) {
  196. var obj = objects[ i ];
  197. var attributes = obj.attributes;
  198. switch ( obj.objectType ) {
  199. case 'InstanceDefinition':
  200. instanceDefinitions.push( obj );
  201. break;
  202. case 'InstanceReference':
  203. instanceReferences.push( obj );
  204. break;
  205. default:
  206. if ( attributes.hasOwnProperty( 'materialUUID' ) ) {
  207. var rMaterial = materials.find( m => m.id === attributes.materialUUID );
  208. var material = this._createMaterial( rMaterial );
  209. material = this._compareMaterials( material );
  210. var _object = this._createObject( obj, material );
  211. } else {
  212. var material = this._createMaterial( );
  213. var _object = this._createObject( obj, material );
  214. }
  215. if ( _object === undefined ) {
  216. continue;
  217. }
  218. var layer = data.layers[ attributes.layerIndex ];
  219. _object.visible = layer ? data.layers[ attributes.layerIndex ].visible : true;
  220. if ( attributes.isInstanceDefinitionObject ) {
  221. instanceDefinitionObjects.push( _object );
  222. } else {
  223. object.add( _object );
  224. }
  225. break;
  226. }
  227. }
  228. for ( var i = 0; i < instanceDefinitions.length; i ++ ) {
  229. var iDef = instanceDefinitions[ i ];
  230. var objects = [];
  231. for ( var j = 0; j < iDef.attributes.objectIds.length; j ++ ) {
  232. var objId = iDef.attributes.objectIds[ j ];
  233. for ( var p = 0; p < instanceDefinitionObjects.length; p ++ ) {
  234. var idoId = instanceDefinitionObjects[ p ].userData.attributes.id;
  235. if ( objId === idoId ) {
  236. objects.push( instanceDefinitionObjects[ p ] );
  237. }
  238. }
  239. }
  240. // Currently clones geometry and does not take advantage of instancing
  241. for ( var j = 0; j < instanceReferences.length; j ++ ) {
  242. var iRef = instanceReferences[ j ];
  243. if ( iRef.geometry.parentIdefId === iDef.attributes.id ) {
  244. var iRefObject = new Object3D();
  245. var xf = iRef.geometry.xform.array;
  246. var matrix = new Matrix4();
  247. matrix.set( xf[ 0 ], xf[ 1 ], xf[ 2 ], xf[ 3 ], xf[ 4 ], xf[ 5 ], xf[ 6 ], xf[ 7 ], xf[ 8 ], xf[ 9 ], xf[ 10 ], xf[ 11 ], xf[ 12 ], xf[ 13 ], xf[ 14 ], xf[ 15 ] );
  248. iRefObject.applyMatrix4( matrix );
  249. for ( var p = 0; p < objects.length; p ++ ) {
  250. iRefObject.add( objects[ p ].clone( true ) );
  251. }
  252. object.add( iRefObject );
  253. }
  254. }
  255. }
  256. this.materials = [];
  257. return object;
  258. },
  259. _createObject: function ( obj, mat ) {
  260. var loader = new BufferGeometryLoader();
  261. var attributes = obj.attributes;
  262. switch ( obj.objectType ) {
  263. case 'Point':
  264. case 'PointSet':
  265. var geometry = loader.parse( obj.geometry );
  266. var _color = attributes.drawColor;
  267. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  268. var material = new PointsMaterial( { color: color, sizeAttenuation: false, size: 2 } );
  269. if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
  270. material.vertexColors = true;
  271. }
  272. material = this._compareMaterials( material );
  273. var points = new Points( geometry, material );
  274. points.userData[ 'attributes' ] = attributes;
  275. points.userData[ 'objectType' ] = obj.objectType;
  276. if ( attributes.name ) {
  277. points.name = attributes.name;
  278. }
  279. return points;
  280. case 'Mesh':
  281. case 'Extrusion':
  282. case 'SubD':
  283. var geometry = loader.parse( obj.geometry );
  284. if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
  285. mat.vertexColors = true;
  286. }
  287. if ( mat === null ) {
  288. mat = this._createMaterial();
  289. mat = this._compareMaterials( mat );
  290. }
  291. var mesh = new Mesh( geometry, mat );
  292. mesh.castShadow = attributes.castsShadows;
  293. mesh.receiveShadow = attributes.receivesShadows;
  294. mesh.userData[ 'attributes' ] = attributes;
  295. mesh.userData[ 'objectType' ] = obj.objectType;
  296. if ( attributes.name ) {
  297. mesh.name = attributes.name;
  298. }
  299. return mesh;
  300. case 'Brep':
  301. var brepObject = new Object3D();
  302. for ( var j = 0; j < obj.geometry.length; j ++ ) {
  303. geometry = loader.parse( obj.geometry[ j ] );
  304. var mesh = new Mesh( geometry, mat );
  305. mesh.castShadow = attributes.castsShadows;
  306. mesh.receiveShadow = attributes.receivesShadows;
  307. brepObject.add( mesh );
  308. }
  309. brepObject.userData[ 'attributes' ] = attributes;
  310. brepObject.userData[ 'objectType' ] = obj.objectType;
  311. if ( attributes.name ) {
  312. brepObject.name = attributes.name;
  313. }
  314. return brepObject;
  315. case 'Curve':
  316. geometry = loader.parse( obj.geometry );
  317. var _color = attributes.drawColor;
  318. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  319. var material = new LineBasicMaterial( { color: color } );
  320. material = this._compareMaterials( material );
  321. var lines = new Line( geometry, material );
  322. lines.userData[ 'attributes' ] = attributes;
  323. lines.userData[ 'objectType' ] = obj.objectType;
  324. if ( attributes.name ) {
  325. lines.name = attributes.name;
  326. }
  327. return lines;
  328. case 'TextDot':
  329. geometry = obj.geometry;
  330. var ctx = document.createElement( 'canvas' ).getContext( '2d' );
  331. var font = `${geometry.fontHeight}px ${geometry.fontFace}`;
  332. ctx.font = font;
  333. var width = ctx.measureText( geometry.text ).width + 10;
  334. var height = geometry.fontHeight + 10;
  335. var r = window.devicePixelRatio;
  336. ctx.canvas.width = width * r;
  337. ctx.canvas.height = height * r;
  338. ctx.canvas.style.width = width + 'px';
  339. ctx.canvas.style.height = height + 'px';
  340. ctx.setTransform( r, 0, 0, r, 0, 0 );
  341. ctx.font = font;
  342. ctx.textBaseline = 'middle';
  343. ctx.textAlign = 'center';
  344. var color = attributes.drawColor;
  345. ctx.fillStyle = `rgba(${color.r},${color.g},${color.b},${color.a})`;
  346. ctx.fillRect( 0, 0, width, height );
  347. ctx.fillStyle = 'white';
  348. ctx.fillText( geometry.text, width / 2, height / 2 );
  349. var texture = new CanvasTexture( ctx.canvas );
  350. texture.minFilter = LinearFilter;
  351. texture.wrapS = ClampToEdgeWrapping;
  352. texture.wrapT = ClampToEdgeWrapping;
  353. var material = new SpriteMaterial( { map: texture, depthTest: false } );
  354. var sprite = new Sprite( material );
  355. sprite.position.set( geometry.point[ 0 ], geometry.point[ 1 ], geometry.point[ 2 ] );
  356. sprite.scale.set( width / 10, height / 10, 1.0 );
  357. sprite.userData[ 'attributes' ] = attributes;
  358. sprite.userData[ 'objectType' ] = obj.objectType;
  359. if ( attributes.name ) {
  360. sprite.name = attributes.name;
  361. }
  362. return sprite;
  363. case 'Light':
  364. geometry = obj.geometry;
  365. var light;
  366. if ( geometry.isDirectionalLight ) {
  367. light = new DirectionalLight();
  368. light.castShadow = attributes.castsShadows;
  369. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  370. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  371. light.shadow.normalBias = 0.1;
  372. } else if ( geometry.isPointLight ) {
  373. light = new PointLight();
  374. light.castShadow = attributes.castsShadows;
  375. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  376. light.shadow.normalBias = 0.1;
  377. } else if ( geometry.isRectangularLight ) {
  378. light = new RectAreaLight();
  379. var width = Math.abs( geometry.width[ 2 ] );
  380. var height = Math.abs( geometry.length[ 0 ] );
  381. light.position.set( geometry.location[ 0 ] - ( height / 2 ), geometry.location[ 1 ], geometry.location[ 2 ] - ( width / 2 ) );
  382. light.height = height;
  383. light.width = width;
  384. light.lookAt( new Vector3( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] ) );
  385. } else if ( geometry.isSpotLight ) {
  386. light = new SpotLight();
  387. light.castShadow = attributes.castsShadows;
  388. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  389. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  390. light.angle = geometry.spotAngleRadians;
  391. light.shadow.normalBias = 0.1;
  392. } else if ( geometry.isLinearLight ) {
  393. console.warn( 'THREE.3DMLoader: No conversion exists for linear lights.' );
  394. return;
  395. }
  396. if ( light ) {
  397. light.intensity = geometry.intensity;
  398. var _color = geometry.diffuse;
  399. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  400. light.color = color;
  401. light.userData[ 'attributes' ] = attributes;
  402. light.userData[ 'objectType' ] = obj.objectType;
  403. }
  404. return light;
  405. }
  406. },
  407. _initLibrary: function () {
  408. if ( ! this.libraryPending ) {
  409. // Load rhino3dm wrapper.
  410. var jsLoader = new FileLoader( this.manager );
  411. jsLoader.setPath( this.libraryPath );
  412. var jsContent = new Promise( ( resolve, reject ) => {
  413. jsLoader.load( 'rhino3dm.js', resolve, undefined, reject );
  414. } );
  415. // Load rhino3dm WASM binary.
  416. var binaryLoader = new FileLoader( this.manager );
  417. binaryLoader.setPath( this.libraryPath );
  418. binaryLoader.setResponseType( 'arraybuffer' );
  419. var binaryContent = new Promise( ( resolve, reject ) => {
  420. binaryLoader.load( 'rhino3dm.wasm', resolve, undefined, reject );
  421. } );
  422. this.libraryPending = Promise.all( [ jsContent, binaryContent ] )
  423. .then( ( [ jsContent, binaryContent ] ) => {
  424. //this.libraryBinary = binaryContent;
  425. this.libraryConfig.wasmBinary = binaryContent;
  426. var fn = Rhino3dmLoader.Rhino3dmWorker.toString();
  427. var body = [
  428. '/* rhino3dm.js */',
  429. jsContent,
  430. '/* worker */',
  431. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  432. ].join( '\n' );
  433. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  434. } );
  435. }
  436. return this.libraryPending;
  437. },
  438. _getWorker: function ( taskCost ) {
  439. return this._initLibrary().then( () => {
  440. if ( this.workerPool.length < this.workerLimit ) {
  441. var worker = new Worker( this.workerSourceURL );
  442. worker._callbacks = {};
  443. worker._taskCosts = {};
  444. worker._taskLoad = 0;
  445. worker.postMessage( {
  446. type: 'init',
  447. libraryConfig: this.libraryConfig
  448. } );
  449. worker.onmessage = function ( e ) {
  450. var message = e.data;
  451. switch ( message.type ) {
  452. case 'decode':
  453. worker._callbacks[ message.id ].resolve( message );
  454. break;
  455. case 'error':
  456. worker._callbacks[ message.id ].reject( message );
  457. break;
  458. default:
  459. console.error( 'THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"' );
  460. }
  461. };
  462. this.workerPool.push( worker );
  463. } else {
  464. this.workerPool.sort( function ( a, b ) {
  465. return a._taskLoad > b._taskLoad ? - 1 : 1;
  466. } );
  467. }
  468. var worker = this.workerPool[ this.workerPool.length - 1 ];
  469. worker._taskLoad += taskCost;
  470. return worker;
  471. } );
  472. },
  473. _releaseTask: function ( worker, taskID ) {
  474. worker._taskLoad -= worker._taskCosts[ taskID ];
  475. delete worker._callbacks[ taskID ];
  476. delete worker._taskCosts[ taskID ];
  477. },
  478. dispose: function () {
  479. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  480. this.workerPool[ i ].terminate();
  481. }
  482. this.workerPool.length = 0;
  483. return this;
  484. }
  485. } );
  486. /* WEB WORKER */
  487. Rhino3dmLoader.Rhino3dmWorker = function () {
  488. var libraryPending;
  489. var libraryConfig;
  490. var rhino;
  491. onmessage = function ( e ) {
  492. var message = e.data;
  493. switch ( message.type ) {
  494. case 'init':
  495. libraryConfig = message.libraryConfig;
  496. var wasmBinary = libraryConfig.wasmBinary;
  497. var RhinoModule;
  498. libraryPending = new Promise( function ( resolve ) {
  499. /* Like Basis Loader */
  500. RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };
  501. rhino3dm( RhinoModule ); // eslint-disable-line no-undef
  502. } ).then( () => {
  503. rhino = RhinoModule;
  504. } );
  505. break;
  506. case 'decode':
  507. var buffer = message.buffer;
  508. libraryPending.then( () => {
  509. var data = decodeObjects( rhino, buffer );
  510. self.postMessage( { type: 'decode', id: message.id, data } );
  511. } );
  512. break;
  513. }
  514. };
  515. function decodeObjects( rhino, buffer ) {
  516. var arr = new Uint8Array( buffer );
  517. var doc = rhino.File3dm.fromByteArray( arr );
  518. var objects = [];
  519. var materials = [];
  520. var layers = [];
  521. var views = [];
  522. var namedViews = [];
  523. var groups = [];
  524. //Handle objects
  525. var objs = doc.objects();
  526. var cnt = objs.count;
  527. for ( var i = 0; i < cnt; i ++ ) {
  528. var _object = objs.get( i );
  529. var object = extractObjectData( _object, doc );
  530. _object.delete();
  531. if ( object !== undefined ) {
  532. if ( object.attributes.materialIndex >= 0 ) {
  533. var mId = doc.materials().findIndex( object.attributes.materialIndex ).id;
  534. object.attributes.materialUUID = mId;
  535. }
  536. objects.push( object );
  537. }
  538. }
  539. // Handle instance definitions
  540. // console.log( `Instance Definitions Count: ${doc.instanceDefinitions().count()}` );
  541. for ( var i = 0; i < doc.instanceDefinitions().count(); i ++ ) {
  542. var idef = doc.instanceDefinitions().get( i );
  543. var idefAttributes = extractProperties( idef );
  544. idefAttributes.objectIds = idef.getObjectIds();
  545. objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );
  546. }
  547. // Handle materials
  548. var textureTypes = [
  549. // rhino.TextureType.Bitmap,
  550. rhino.TextureType.Diffuse,
  551. rhino.TextureType.Bump,
  552. rhino.TextureType.Transparency,
  553. rhino.TextureType.Opacity,
  554. rhino.TextureType.Emap
  555. ];
  556. var pbrTextureTypes = [
  557. rhino.TextureType.PBR_BaseColor,
  558. rhino.TextureType.PBR_Subsurface,
  559. rhino.TextureType.PBR_SubsurfaceScattering,
  560. rhino.TextureType.PBR_SubsurfaceScatteringRadius,
  561. rhino.TextureType.PBR_Metallic,
  562. rhino.TextureType.PBR_Specular,
  563. rhino.TextureType.PBR_SpecularTint,
  564. rhino.TextureType.PBR_Roughness,
  565. rhino.TextureType.PBR_Anisotropic,
  566. rhino.TextureType.PBR_Anisotropic_Rotation,
  567. rhino.TextureType.PBR_Sheen,
  568. rhino.TextureType.PBR_SheenTint,
  569. rhino.TextureType.PBR_Clearcoat,
  570. rhino.TextureType.PBR_ClearcoatBump,
  571. rhino.TextureType.PBR_ClearcoatRoughness,
  572. rhino.TextureType.PBR_OpacityIor,
  573. rhino.TextureType.PBR_OpacityRoughness,
  574. rhino.TextureType.PBR_Emission,
  575. rhino.TextureType.PBR_AmbientOcclusion,
  576. rhino.TextureType.PBR_Displacement
  577. ];
  578. for ( var i = 0; i < doc.materials().count(); i ++ ) {
  579. var _material = doc.materials().get( i );
  580. var _pbrMaterial = _material.physicallyBased();
  581. var material = extractProperties( _material );
  582. var textures = [];
  583. for ( var j = 0; j < textureTypes.length; j ++ ) {
  584. var _texture = _material.getTexture( textureTypes[ j ] );
  585. if ( _texture ) {
  586. var textureType = textureTypes[ j ].constructor.name;
  587. textureType = textureType.substring( 12, textureType.length );
  588. var texture = { type: textureType };
  589. var image = doc.getEmbeddedFileAsBase64( _texture.fileName );
  590. if ( image ) {
  591. texture.image = 'data:image/png;base64,' + image;
  592. } else {
  593. console.warn( `THREE.3DMLoader: Image for ${textureType} texture not embedded in file.` );
  594. texture.image = null;
  595. }
  596. textures.push( texture );
  597. _texture.delete();
  598. }
  599. }
  600. material.textures = textures;
  601. if ( _pbrMaterial.supported ) {
  602. console.log( 'pbr true' );
  603. for ( var j = 0; j < pbrTextureTypes.length; j ++ ) {
  604. var _texture = _material.getTexture( textureTypes[ j ] );
  605. if ( _texture ) {
  606. var image = doc.getEmbeddedFileAsBase64( _texture.fileName );
  607. var textureType = textureTypes[ j ].constructor.name;
  608. textureType = textureType.substring( 12, textureType.length );
  609. var texture = { type: textureType, image: 'data:image/png;base64,' + image };
  610. textures.push( texture );
  611. _texture.delete();
  612. }
  613. }
  614. var pbMaterialProperties = extractProperties( _material.physicallyBased() );
  615. material = Object.assign( pbMaterialProperties, material );
  616. }
  617. materials.push( material );
  618. _material.delete();
  619. _pbrMaterial.delete();
  620. }
  621. // Handle layers
  622. for ( var i = 0; i < doc.layers().count(); i ++ ) {
  623. var _layer = doc.layers().get( i );
  624. var layer = extractProperties( _layer );
  625. layers.push( layer );
  626. _layer.delete();
  627. }
  628. // Handle views
  629. for ( var i = 0; i < doc.views().count(); i ++ ) {
  630. var _view = doc.views().get( i );
  631. var view = extractProperties( _view );
  632. views.push( view );
  633. _view.delete();
  634. }
  635. // Handle named views
  636. for ( var i = 0; i < doc.namedViews().count(); i ++ ) {
  637. var _namedView = doc.namedViews().get( i );
  638. var namedView = extractProperties( _namedView );
  639. namedViews.push( namedView );
  640. _namedView.delete();
  641. }
  642. // Handle groups
  643. for ( var i = 0; i < doc.groups().count(); i ++ ) {
  644. var _group = doc.groups().get( i );
  645. var group = extractProperties( _group );
  646. groups.push( group );
  647. _group.delete();
  648. }
  649. // Handle settings
  650. var settings = extractProperties( doc.settings() );
  651. //TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.
  652. // Handle dimstyles
  653. // console.log( `Dimstyle Count: ${doc.dimstyles().count()}` );
  654. // Handle bitmaps
  655. // console.log( `Bitmap Count: ${doc.bitmaps().count()}` );
  656. // Handle strings -- this seems to be broken at the moment in rhino3dm
  657. // console.log( `Document Strings Count: ${doc.strings().count()}` );
  658. /*
  659. for( var i = 0; i < doc.strings().count(); i++ ){
  660. var _string= doc.strings().get( i );
  661. console.log(_string);
  662. var string = extractProperties( _group );
  663. strings.push( string );
  664. _string.delete();
  665. }
  666. */
  667. doc.delete();
  668. return { objects, materials, layers, views, namedViews, groups, settings };
  669. }
  670. function extractObjectData( object, doc ) {
  671. var _geometry = object.geometry();
  672. var _attributes = object.attributes();
  673. var objectType = _geometry.objectType;
  674. var geometry = null;
  675. var attributes = null;
  676. // skip instance definition objects
  677. //if( _attributes.isInstanceDefinitionObject ) { continue; }
  678. // TODO: handle other geometry types
  679. switch ( objectType ) {
  680. case rhino.ObjectType.Curve:
  681. var pts = curveToPoints( _geometry, 100 );
  682. var position = {};
  683. var attributes = {};
  684. var data = {};
  685. position.itemSize = 3;
  686. position.type = 'Float32Array';
  687. position.array = [];
  688. for ( var j = 0; j < pts.length; j ++ ) {
  689. position.array.push( pts[ j ][ 0 ] );
  690. position.array.push( pts[ j ][ 1 ] );
  691. position.array.push( pts[ j ][ 2 ] );
  692. }
  693. attributes.position = position;
  694. data.attributes = attributes;
  695. geometry = { data };
  696. break;
  697. case rhino.ObjectType.Point:
  698. var pt = _geometry.location;
  699. var position = {};
  700. var color = {};
  701. var attributes = {};
  702. var data = {};
  703. position.itemSize = 3;
  704. position.type = 'Float32Array';
  705. position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];
  706. var _color = _attributes.drawColor( doc );
  707. color.itemSize = 3;
  708. color.type = 'Float32Array';
  709. color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];
  710. attributes.position = position;
  711. attributes.color = color;
  712. data.attributes = attributes;
  713. geometry = { data };
  714. break;
  715. case rhino.ObjectType.PointSet:
  716. case rhino.ObjectType.Mesh:
  717. geometry = _geometry.toThreejsJSON();
  718. break;
  719. case rhino.ObjectType.Brep:
  720. var faces = _geometry.faces();
  721. geometry = [];
  722. for ( var faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {
  723. var face = faces.get( faceIndex );
  724. var mesh = face.getMesh( rhino.MeshType.Any );
  725. if ( mesh ) {
  726. geometry.push( mesh.toThreejsJSON() );
  727. mesh.delete();
  728. }
  729. face.delete();
  730. }
  731. faces.delete();
  732. break;
  733. case rhino.ObjectType.Extrusion:
  734. var mesh = _geometry.getMesh( rhino.MeshType.Any );
  735. if ( mesh ) {
  736. geometry = mesh.toThreejsJSON();
  737. mesh.delete();
  738. }
  739. break;
  740. case rhino.ObjectType.TextDot:
  741. geometry = extractProperties( _geometry );
  742. break;
  743. case rhino.ObjectType.Light:
  744. geometry = extractProperties( _geometry );
  745. break;
  746. case rhino.ObjectType.InstanceReference:
  747. geometry = extractProperties( _geometry );
  748. geometry.xform = extractProperties( _geometry.xform );
  749. geometry.xform.array = _geometry.xform.toFloatArray( true );
  750. break;
  751. case rhino.ObjectType.SubD:
  752. // TODO: precalculate resulting vertices and faces and warn on excessive results
  753. _geometry.subdivide( 3 );
  754. var mesh = rhino.Mesh.createFromSubDControlNet( _geometry );
  755. if ( mesh ) {
  756. geometry = mesh.toThreejsJSON();
  757. mesh.delete();
  758. }
  759. break;
  760. /*
  761. case rhino.ObjectType.Annotation:
  762. case rhino.ObjectType.Hatch:
  763. case rhino.ObjectType.ClipPlane:
  764. */
  765. default:
  766. console.warn( `THREE.3DMLoader: TODO: Implement ${objectType.constructor.name}` );
  767. break;
  768. }
  769. if ( Array.isArray( geometry ) === false || geometry.length > 0 ) {
  770. var attributes = extractProperties( _attributes );
  771. attributes.geometry = extractProperties( _geometry );
  772. if ( _attributes.groupCount > 0 ) {
  773. attributes.groupIds = _attributes.getGroupList();
  774. }
  775. if ( _attributes.userStringCount > 0 ) {
  776. attributes.userStrings = _attributes.getUserStrings();
  777. }
  778. attributes.drawColor = _attributes.drawColor( doc );
  779. objectType = objectType.constructor.name;
  780. objectType = objectType.substring( 11, objectType.length );
  781. attributes.geometry.objectType = objectType;
  782. return { geometry, attributes, objectType };
  783. } else {
  784. console.warn( 'THREE.3DMLoader: Object has no mesh geometry. Consider opening this in Rhino, using a shaded display mode, and exporting again.' );
  785. }
  786. }
  787. function extractProperties( object ) {
  788. var result = {};
  789. for ( var property in object ) {
  790. if ( typeof object[ property ] !== 'function' ) {
  791. result[ property ] = object[ property ];
  792. } else {
  793. // console.log( `${property}: ${object[ property ]}` );
  794. }
  795. }
  796. return result;
  797. }
  798. function curveToPoints( curve, pointLimit ) {
  799. var pointCount = pointLimit;
  800. var rc = [];
  801. var ts = [];
  802. if ( curve instanceof rhino.LineCurve ) {
  803. return [ curve.pointAtStart, curve.pointAtEnd ];
  804. }
  805. if ( curve instanceof rhino.PolylineCurve ) {
  806. pointCount = curve.pointCount;
  807. for ( var i = 0; i < pointCount; i ++ ) {
  808. rc.push( curve.point( i ) );
  809. }
  810. return rc;
  811. }
  812. if ( curve instanceof rhino.PolyCurve ) {
  813. var segmentCount = curve.segmentCount;
  814. for ( var i = 0; i < segmentCount; i ++ ) {
  815. var segment = curve.segmentCurve( i );
  816. var segmentArray = curveToPoints( segment, pointCount );
  817. rc = rc.concat( segmentArray );
  818. segment.delete();
  819. }
  820. return rc;
  821. }
  822. if ( curve instanceof rhino.ArcCurve ) {
  823. pointCount = Math.floor( curve.angleDegrees / 5 );
  824. pointCount = pointCount < 2 ? 2 : pointCount;
  825. // alternative to this hardcoded version: https://stackoverflow.com/a/18499923/2179399
  826. }
  827. if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {
  828. if ( curve.segmentCount === undefined || curve.segmentCount === 1 ) {
  829. return [ curve.pointAtStart, curve.pointAtEnd ];
  830. }
  831. }
  832. var domain = curve.domain;
  833. var divisions = pointCount - 1.0;
  834. for ( var j = 0; j < pointCount; j ++ ) {
  835. var t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );
  836. if ( t === domain[ 0 ] || t === domain[ 1 ] ) {
  837. ts.push( t );
  838. continue;
  839. }
  840. var tan = curve.tangentAt( t );
  841. var prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );
  842. // Duplicaated from THREE.Vector3
  843. // How to pass imports to worker?
  844. var tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];
  845. var ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];
  846. var denominator = Math.sqrt( tS * ptS );
  847. var angle;
  848. if ( denominator === 0 ) {
  849. angle = Math.PI / 2;
  850. } else {
  851. var theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;
  852. angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );
  853. }
  854. if ( angle < 0.1 ) continue;
  855. ts.push( t );
  856. }
  857. rc = ts.map( t => curve.pointAt( t ) );
  858. return rc;
  859. }
  860. };
  861. export { Rhino3dmLoader };