3DMLoader.js 29 KB

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