3DMLoader.js 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  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. case 'Brep':
  285. var geometry = loader.parse( obj.geometry );
  286. if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
  287. mat.vertexColors = true;
  288. }
  289. if ( mat === null ) {
  290. mat = this._createMaterial();
  291. mat = this._compareMaterials( mat );
  292. }
  293. var mesh = new Mesh( geometry, mat );
  294. mesh.castShadow = attributes.castsShadows;
  295. mesh.receiveShadow = attributes.receivesShadows;
  296. mesh.userData[ 'attributes' ] = attributes;
  297. mesh.userData[ 'objectType' ] = obj.objectType;
  298. if ( attributes.name ) {
  299. mesh.name = attributes.name;
  300. }
  301. return mesh;
  302. case 'Curve':
  303. geometry = loader.parse( obj.geometry );
  304. var _color = attributes.drawColor;
  305. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  306. var material = new LineBasicMaterial( { color: color } );
  307. material = this._compareMaterials( material );
  308. var lines = new Line( geometry, material );
  309. lines.userData[ 'attributes' ] = attributes;
  310. lines.userData[ 'objectType' ] = obj.objectType;
  311. if ( attributes.name ) {
  312. lines.name = attributes.name;
  313. }
  314. return lines;
  315. case 'TextDot':
  316. geometry = obj.geometry;
  317. var ctx = document.createElement( 'canvas' ).getContext( '2d' );
  318. var font = `${geometry.fontHeight}px ${geometry.fontFace}`;
  319. ctx.font = font;
  320. var width = ctx.measureText( geometry.text ).width + 10;
  321. var height = geometry.fontHeight + 10;
  322. var r = window.devicePixelRatio;
  323. ctx.canvas.width = width * r;
  324. ctx.canvas.height = height * r;
  325. ctx.canvas.style.width = width + 'px';
  326. ctx.canvas.style.height = height + 'px';
  327. ctx.setTransform( r, 0, 0, r, 0, 0 );
  328. ctx.font = font;
  329. ctx.textBaseline = 'middle';
  330. ctx.textAlign = 'center';
  331. var color = attributes.drawColor;
  332. ctx.fillStyle = `rgba(${color.r},${color.g},${color.b},${color.a})`;
  333. ctx.fillRect( 0, 0, width, height );
  334. ctx.fillStyle = 'white';
  335. ctx.fillText( geometry.text, width / 2, height / 2 );
  336. var texture = new CanvasTexture( ctx.canvas );
  337. texture.minFilter = LinearFilter;
  338. texture.wrapS = ClampToEdgeWrapping;
  339. texture.wrapT = ClampToEdgeWrapping;
  340. var material = new SpriteMaterial( { map: texture, depthTest: false } );
  341. var sprite = new Sprite( material );
  342. sprite.position.set( geometry.point[ 0 ], geometry.point[ 1 ], geometry.point[ 2 ] );
  343. sprite.scale.set( width / 10, height / 10, 1.0 );
  344. sprite.userData[ 'attributes' ] = attributes;
  345. sprite.userData[ 'objectType' ] = obj.objectType;
  346. if ( attributes.name ) {
  347. sprite.name = attributes.name;
  348. }
  349. return sprite;
  350. case 'Light':
  351. geometry = obj.geometry;
  352. var light;
  353. if ( geometry.isDirectionalLight ) {
  354. light = new DirectionalLight();
  355. light.castShadow = attributes.castsShadows;
  356. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  357. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  358. light.shadow.normalBias = 0.1;
  359. } else if ( geometry.isPointLight ) {
  360. light = new PointLight();
  361. light.castShadow = attributes.castsShadows;
  362. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  363. light.shadow.normalBias = 0.1;
  364. } else if ( geometry.isRectangularLight ) {
  365. light = new RectAreaLight();
  366. var width = Math.abs( geometry.width[ 2 ] );
  367. var height = Math.abs( geometry.length[ 0 ] );
  368. light.position.set( geometry.location[ 0 ] - ( height / 2 ), geometry.location[ 1 ], geometry.location[ 2 ] - ( width / 2 ) );
  369. light.height = height;
  370. light.width = width;
  371. light.lookAt( new Vector3( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] ) );
  372. } else if ( geometry.isSpotLight ) {
  373. light = new SpotLight();
  374. light.castShadow = attributes.castsShadows;
  375. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  376. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  377. light.angle = geometry.spotAngleRadians;
  378. light.shadow.normalBias = 0.1;
  379. } else if ( geometry.isLinearLight ) {
  380. console.warn( 'THREE.3DMLoader: No conversion exists for linear lights.' );
  381. return;
  382. }
  383. if ( light ) {
  384. light.intensity = geometry.intensity;
  385. var _color = geometry.diffuse;
  386. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  387. light.color = color;
  388. light.userData[ 'attributes' ] = attributes;
  389. light.userData[ 'objectType' ] = obj.objectType;
  390. }
  391. return light;
  392. }
  393. },
  394. _initLibrary: function () {
  395. if ( ! this.libraryPending ) {
  396. // Load rhino3dm wrapper.
  397. var jsLoader = new FileLoader( this.manager );
  398. jsLoader.setPath( this.libraryPath );
  399. var jsContent = new Promise( ( resolve, reject ) => {
  400. jsLoader.load( 'rhino3dm.js', resolve, undefined, reject );
  401. } );
  402. // Load rhino3dm WASM binary.
  403. var binaryLoader = new FileLoader( this.manager );
  404. binaryLoader.setPath( this.libraryPath );
  405. binaryLoader.setResponseType( 'arraybuffer' );
  406. var binaryContent = new Promise( ( resolve, reject ) => {
  407. binaryLoader.load( 'rhino3dm.wasm', resolve, undefined, reject );
  408. } );
  409. this.libraryPending = Promise.all( [ jsContent, binaryContent ] )
  410. .then( ( [ jsContent, binaryContent ] ) => {
  411. //this.libraryBinary = binaryContent;
  412. this.libraryConfig.wasmBinary = binaryContent;
  413. var fn = Rhino3dmLoader.Rhino3dmWorker.toString();
  414. var body = [
  415. '/* rhino3dm.js */',
  416. jsContent,
  417. '/* worker */',
  418. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  419. ].join( '\n' );
  420. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  421. } );
  422. }
  423. return this.libraryPending;
  424. },
  425. _getWorker: function ( taskCost ) {
  426. return this._initLibrary().then( () => {
  427. if ( this.workerPool.length < this.workerLimit ) {
  428. var worker = new Worker( this.workerSourceURL );
  429. worker._callbacks = {};
  430. worker._taskCosts = {};
  431. worker._taskLoad = 0;
  432. worker.postMessage( {
  433. type: 'init',
  434. libraryConfig: this.libraryConfig
  435. } );
  436. worker.onmessage = function ( e ) {
  437. var message = e.data;
  438. switch ( message.type ) {
  439. case 'decode':
  440. worker._callbacks[ message.id ].resolve( message );
  441. break;
  442. case 'error':
  443. worker._callbacks[ message.id ].reject( message );
  444. break;
  445. default:
  446. console.error( 'THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"' );
  447. }
  448. };
  449. this.workerPool.push( worker );
  450. } else {
  451. this.workerPool.sort( function ( a, b ) {
  452. return a._taskLoad > b._taskLoad ? - 1 : 1;
  453. } );
  454. }
  455. var worker = this.workerPool[ this.workerPool.length - 1 ];
  456. worker._taskLoad += taskCost;
  457. return worker;
  458. } );
  459. },
  460. _releaseTask: function ( worker, taskID ) {
  461. worker._taskLoad -= worker._taskCosts[ taskID ];
  462. delete worker._callbacks[ taskID ];
  463. delete worker._taskCosts[ taskID ];
  464. },
  465. dispose: function () {
  466. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  467. this.workerPool[ i ].terminate();
  468. }
  469. this.workerPool.length = 0;
  470. return this;
  471. }
  472. } );
  473. /* WEB WORKER */
  474. Rhino3dmLoader.Rhino3dmWorker = function () {
  475. var libraryPending;
  476. var libraryConfig;
  477. var rhino;
  478. onmessage = function ( e ) {
  479. var message = e.data;
  480. switch ( message.type ) {
  481. case 'init':
  482. libraryConfig = message.libraryConfig;
  483. var wasmBinary = libraryConfig.wasmBinary;
  484. var RhinoModule;
  485. libraryPending = new Promise( function ( resolve ) {
  486. /* Like Basis Loader */
  487. RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };
  488. rhino3dm( RhinoModule ); // eslint-disable-line no-undef
  489. } ).then( () => {
  490. rhino = RhinoModule;
  491. } );
  492. break;
  493. case 'decode':
  494. var buffer = message.buffer;
  495. libraryPending.then( () => {
  496. var data = decodeObjects( rhino, buffer );
  497. self.postMessage( { type: 'decode', id: message.id, data } );
  498. } );
  499. break;
  500. }
  501. };
  502. function decodeObjects( rhino, buffer ) {
  503. var arr = new Uint8Array( buffer );
  504. var doc = rhino.File3dm.fromByteArray( arr );
  505. var objects = [];
  506. var materials = [];
  507. var layers = [];
  508. var views = [];
  509. var namedViews = [];
  510. var groups = [];
  511. //Handle objects
  512. var objs = doc.objects();
  513. var cnt = objs.count;
  514. for ( var i = 0; i < cnt; i ++ ) {
  515. var _object = objs.get( i );
  516. var object = extractObjectData( _object, doc );
  517. _object.delete();
  518. if ( object !== undefined ) {
  519. if ( object.attributes.materialIndex >= 0 ) {
  520. var mId = doc.materials().findIndex( object.attributes.materialIndex ).id;
  521. object.attributes.materialUUID = mId;
  522. }
  523. objects.push( object );
  524. }
  525. }
  526. // Handle instance definitions
  527. // console.log( `Instance Definitions Count: ${doc.instanceDefinitions().count()}` );
  528. for ( var i = 0; i < doc.instanceDefinitions().count(); i ++ ) {
  529. var idef = doc.instanceDefinitions().get( i );
  530. var idefAttributes = extractProperties( idef );
  531. idefAttributes.objectIds = idef.getObjectIds();
  532. objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );
  533. }
  534. // Handle materials
  535. var textureTypes = [
  536. // rhino.TextureType.Bitmap,
  537. rhino.TextureType.Diffuse,
  538. rhino.TextureType.Bump,
  539. rhino.TextureType.Transparency,
  540. rhino.TextureType.Opacity,
  541. rhino.TextureType.Emap
  542. ];
  543. var pbrTextureTypes = [
  544. rhino.TextureType.PBR_BaseColor,
  545. rhino.TextureType.PBR_Subsurface,
  546. rhino.TextureType.PBR_SubsurfaceScattering,
  547. rhino.TextureType.PBR_SubsurfaceScatteringRadius,
  548. rhino.TextureType.PBR_Metallic,
  549. rhino.TextureType.PBR_Specular,
  550. rhino.TextureType.PBR_SpecularTint,
  551. rhino.TextureType.PBR_Roughness,
  552. rhino.TextureType.PBR_Anisotropic,
  553. rhino.TextureType.PBR_Anisotropic_Rotation,
  554. rhino.TextureType.PBR_Sheen,
  555. rhino.TextureType.PBR_SheenTint,
  556. rhino.TextureType.PBR_Clearcoat,
  557. rhino.TextureType.PBR_ClearcoatBump,
  558. rhino.TextureType.PBR_ClearcoatRoughness,
  559. rhino.TextureType.PBR_OpacityIor,
  560. rhino.TextureType.PBR_OpacityRoughness,
  561. rhino.TextureType.PBR_Emission,
  562. rhino.TextureType.PBR_AmbientOcclusion,
  563. rhino.TextureType.PBR_Displacement
  564. ];
  565. for ( var i = 0; i < doc.materials().count(); i ++ ) {
  566. var _material = doc.materials().get( i );
  567. var _pbrMaterial = _material.physicallyBased();
  568. var material = extractProperties( _material );
  569. var textures = [];
  570. for ( var j = 0; j < textureTypes.length; j ++ ) {
  571. var _texture = _material.getTexture( textureTypes[ j ] );
  572. if ( _texture ) {
  573. var textureType = textureTypes[ j ].constructor.name;
  574. textureType = textureType.substring( 12, textureType.length );
  575. var texture = { type: textureType };
  576. var image = doc.getEmbeddedFileAsBase64( _texture.fileName );
  577. if ( image ) {
  578. texture.image = 'data:image/png;base64,' + image;
  579. } else {
  580. console.warn( `THREE.3DMLoader: Image for ${textureType} texture not embedded in file.` );
  581. texture.image = null;
  582. }
  583. textures.push( texture );
  584. _texture.delete();
  585. }
  586. }
  587. material.textures = textures;
  588. if ( _pbrMaterial.supported ) {
  589. console.log( 'pbr true' );
  590. for ( var j = 0; j < pbrTextureTypes.length; j ++ ) {
  591. var _texture = _material.getTexture( textureTypes[ j ] );
  592. if ( _texture ) {
  593. var image = doc.getEmbeddedFileAsBase64( _texture.fileName );
  594. var textureType = textureTypes[ j ].constructor.name;
  595. textureType = textureType.substring( 12, textureType.length );
  596. var texture = { type: textureType, image: 'data:image/png;base64,' + image };
  597. textures.push( texture );
  598. _texture.delete();
  599. }
  600. }
  601. var pbMaterialProperties = extractProperties( _material.physicallyBased() );
  602. material = Object.assign( pbMaterialProperties, material );
  603. }
  604. materials.push( material );
  605. _material.delete();
  606. _pbrMaterial.delete();
  607. }
  608. // Handle layers
  609. for ( var i = 0; i < doc.layers().count(); i ++ ) {
  610. var _layer = doc.layers().get( i );
  611. var layer = extractProperties( _layer );
  612. layers.push( layer );
  613. _layer.delete();
  614. }
  615. // Handle views
  616. for ( var i = 0; i < doc.views().count(); i ++ ) {
  617. var _view = doc.views().get( i );
  618. var view = extractProperties( _view );
  619. views.push( view );
  620. _view.delete();
  621. }
  622. // Handle named views
  623. for ( var i = 0; i < doc.namedViews().count(); i ++ ) {
  624. var _namedView = doc.namedViews().get( i );
  625. var namedView = extractProperties( _namedView );
  626. namedViews.push( namedView );
  627. _namedView.delete();
  628. }
  629. // Handle groups
  630. for ( var i = 0; i < doc.groups().count(); i ++ ) {
  631. var _group = doc.groups().get( i );
  632. var group = extractProperties( _group );
  633. groups.push( group );
  634. _group.delete();
  635. }
  636. // Handle settings
  637. var settings = extractProperties( doc.settings() );
  638. //TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.
  639. // Handle dimstyles
  640. // console.log( `Dimstyle Count: ${doc.dimstyles().count()}` );
  641. // Handle bitmaps
  642. // console.log( `Bitmap Count: ${doc.bitmaps().count()}` );
  643. // Handle strings -- this seems to be broken at the moment in rhino3dm
  644. // console.log( `Document Strings Count: ${doc.strings().count()}` );
  645. /*
  646. for( var i = 0; i < doc.strings().count(); i++ ){
  647. var _string= doc.strings().get( i );
  648. console.log(_string);
  649. var string = extractProperties( _group );
  650. strings.push( string );
  651. _string.delete();
  652. }
  653. */
  654. doc.delete();
  655. return { objects, materials, layers, views, namedViews, groups, settings };
  656. }
  657. function extractObjectData( object, doc ) {
  658. var _geometry = object.geometry();
  659. var _attributes = object.attributes();
  660. var objectType = _geometry.objectType;
  661. var geometry = null;
  662. var attributes = null;
  663. // skip instance definition objects
  664. //if( _attributes.isInstanceDefinitionObject ) { continue; }
  665. // TODO: handle other geometry types
  666. switch ( objectType ) {
  667. case rhino.ObjectType.Curve:
  668. var pts = curveToPoints( _geometry, 100 );
  669. var position = {};
  670. var attributes = {};
  671. var data = {};
  672. position.itemSize = 3;
  673. position.type = 'Float32Array';
  674. position.array = [];
  675. for ( var j = 0; j < pts.length; j ++ ) {
  676. position.array.push( pts[ j ][ 0 ] );
  677. position.array.push( pts[ j ][ 1 ] );
  678. position.array.push( pts[ j ][ 2 ] );
  679. }
  680. attributes.position = position;
  681. data.attributes = attributes;
  682. geometry = { data };
  683. break;
  684. case rhino.ObjectType.Point:
  685. var pt = _geometry.location;
  686. var position = {};
  687. var color = {};
  688. var attributes = {};
  689. var data = {};
  690. position.itemSize = 3;
  691. position.type = 'Float32Array';
  692. position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];
  693. var _color = _attributes.drawColor( doc );
  694. color.itemSize = 3;
  695. color.type = 'Float32Array';
  696. color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];
  697. attributes.position = position;
  698. attributes.color = color;
  699. data.attributes = attributes;
  700. geometry = { data };
  701. break;
  702. case rhino.ObjectType.PointSet:
  703. case rhino.ObjectType.Mesh:
  704. geometry = _geometry.toThreejsJSON();
  705. break;
  706. case rhino.ObjectType.Brep:
  707. var faces = _geometry.faces();
  708. var mesh = new rhino.Mesh();
  709. for ( var faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {
  710. var face = faces.get( faceIndex );
  711. var _mesh = face.getMesh( rhino.MeshType.Any );
  712. if ( _mesh ) {
  713. mesh.append( _mesh );
  714. _mesh.delete();
  715. }
  716. face.delete();
  717. }
  718. mesh.compact();
  719. geometry = mesh.toThreejsJSON();
  720. faces.delete();
  721. mesh.delete();
  722. break;
  723. case rhino.ObjectType.Extrusion:
  724. var mesh = _geometry.getMesh( rhino.MeshType.Any );
  725. if ( mesh ) {
  726. geometry = mesh.toThreejsJSON();
  727. mesh.delete();
  728. }
  729. break;
  730. case rhino.ObjectType.TextDot:
  731. geometry = extractProperties( _geometry );
  732. break;
  733. case rhino.ObjectType.Light:
  734. geometry = extractProperties( _geometry );
  735. break;
  736. case rhino.ObjectType.InstanceReference:
  737. geometry = extractProperties( _geometry );
  738. geometry.xform = extractProperties( _geometry.xform );
  739. geometry.xform.array = _geometry.xform.toFloatArray( true );
  740. break;
  741. case rhino.ObjectType.SubD:
  742. // TODO: precalculate resulting vertices and faces and warn on excessive results
  743. _geometry.subdivide( 3 );
  744. var mesh = rhino.Mesh.createFromSubDControlNet( _geometry );
  745. if ( mesh ) {
  746. geometry = mesh.toThreejsJSON();
  747. mesh.delete();
  748. }
  749. break;
  750. /*
  751. case rhino.ObjectType.Annotation:
  752. case rhino.ObjectType.Hatch:
  753. case rhino.ObjectType.ClipPlane:
  754. */
  755. default:
  756. console.warn( `THREE.3DMLoader: TODO: Implement ${objectType.constructor.name}` );
  757. break;
  758. }
  759. if ( Array.isArray( geometry ) === false || geometry.length > 0 ) {
  760. var attributes = extractProperties( _attributes );
  761. attributes.geometry = extractProperties( _geometry );
  762. if ( _attributes.groupCount > 0 ) {
  763. attributes.groupIds = _attributes.getGroupList();
  764. }
  765. if ( _attributes.userStringCount > 0 ) {
  766. attributes.userStrings = _attributes.getUserStrings();
  767. }
  768. attributes.drawColor = _attributes.drawColor( doc );
  769. objectType = objectType.constructor.name;
  770. objectType = objectType.substring( 11, objectType.length );
  771. attributes.geometry.objectType = objectType;
  772. return { geometry, attributes, objectType };
  773. } else {
  774. console.warn( 'THREE.3DMLoader: Object has no associated mesh geometry.' );
  775. }
  776. }
  777. function extractProperties( object ) {
  778. var result = {};
  779. for ( var property in object ) {
  780. if ( typeof object[ property ] !== 'function' ) {
  781. result[ property ] = object[ property ];
  782. } else {
  783. // console.log( `${property}: ${object[ property ]}` );
  784. }
  785. }
  786. return result;
  787. }
  788. function curveToPoints( curve, pointLimit ) {
  789. var pointCount = pointLimit;
  790. var rc = [];
  791. var ts = [];
  792. if ( curve instanceof rhino.LineCurve ) {
  793. return [ curve.pointAtStart, curve.pointAtEnd ];
  794. }
  795. if ( curve instanceof rhino.PolylineCurve ) {
  796. pointCount = curve.pointCount;
  797. for ( var i = 0; i < pointCount; i ++ ) {
  798. rc.push( curve.point( i ) );
  799. }
  800. return rc;
  801. }
  802. if ( curve instanceof rhino.PolyCurve ) {
  803. var segmentCount = curve.segmentCount;
  804. for ( var i = 0; i < segmentCount; i ++ ) {
  805. var segment = curve.segmentCurve( i );
  806. var segmentArray = curveToPoints( segment, pointCount );
  807. rc = rc.concat( segmentArray );
  808. segment.delete();
  809. }
  810. return rc;
  811. }
  812. if ( curve instanceof rhino.ArcCurve ) {
  813. pointCount = Math.floor( curve.angleDegrees / 5 );
  814. pointCount = pointCount < 2 ? 2 : pointCount;
  815. // alternative to this hardcoded version: https://stackoverflow.com/a/18499923/2179399
  816. }
  817. if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {
  818. const pLine = curve.tryGetPolyline();
  819. for ( var i = 0; i < pLine.count; i ++ ) {
  820. rc.push( pLine.get( i ) );
  821. }
  822. pLine.delete();
  823. return rc;
  824. }
  825. var domain = curve.domain;
  826. var divisions = pointCount - 1.0;
  827. for ( var j = 0; j < pointCount; j ++ ) {
  828. var t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );
  829. if ( t === domain[ 0 ] || t === domain[ 1 ] ) {
  830. ts.push( t );
  831. continue;
  832. }
  833. var tan = curve.tangentAt( t );
  834. var prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );
  835. // Duplicaated from THREE.Vector3
  836. // How to pass imports to worker?
  837. var tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];
  838. var ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];
  839. var denominator = Math.sqrt( tS * ptS );
  840. var angle;
  841. if ( denominator === 0 ) {
  842. angle = Math.PI / 2;
  843. } else {
  844. var theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;
  845. angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );
  846. }
  847. if ( angle < 0.1 ) continue;
  848. ts.push( t );
  849. }
  850. rc = ts.map( t => curve.pointAt( t ) );
  851. return rc;
  852. }
  853. };
  854. export { Rhino3dmLoader };