3DMLoader.js 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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. } from "../../../build/three.module.js";
  20. import { CSS2DObject } from '../renderers/CSS2DRenderer.js';
  21. var Rhino3dmLoader = function ( manager ) {
  22. Loader.call( this, manager );
  23. this.libraryPath = '';
  24. this.libraryPending = null;
  25. this.libraryBinary = null;
  26. this.libraryConfig = {};
  27. this.workerLimit = 4;
  28. this.workerPool = [];
  29. this.workerNextTaskID = 1;
  30. this.workerSourceURL = '';
  31. this.workerConfig = {};
  32. this.materials = [];
  33. };
  34. Rhino3dmLoader.taskCache = new WeakMap();
  35. Rhino3dmLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  36. constructor: Rhino3dmLoader,
  37. setLibraryPath: function ( path ) {
  38. this.libraryPath = path;
  39. return this;
  40. },
  41. setWorkerLimit: function ( workerLimit ) {
  42. this.workerLimit = workerLimit;
  43. return this;
  44. },
  45. load: function ( url, onLoad, onProgress, onError ) {
  46. var loader = new FileLoader( this.manager );
  47. loader.setPath( this.path );
  48. loader.setResponseType( 'arraybuffer' );
  49. loader.setRequestHeader( this.requestHeader );
  50. loader.load( url, ( buffer ) => {
  51. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  52. // again from this thread.
  53. if ( Rhino3dmLoader.taskCache.has( buffer ) ) {
  54. var cachedTask = Rhino3dmLoader.taskCache.get( buffer );
  55. return cachedTask.promise.then( onLoad ).catch( onError );
  56. }
  57. this.decodeObjects( buffer, url )
  58. .then( onLoad )
  59. .catch( onError );
  60. }, onProgress, onError );
  61. },
  62. debug: function () {
  63. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  64. },
  65. decodeObjects: function ( buffer, url ) {
  66. var worker;
  67. var taskID;
  68. var taskCost = buffer.byteLength;
  69. var objectPending = this._getWorker( taskCost )
  70. .then( ( _worker ) => {
  71. worker = _worker;
  72. taskID = this.workerNextTaskID ++; //hmmm
  73. return new Promise( ( resolve, reject ) => {
  74. worker._callbacks[ taskID ] = { resolve, reject };
  75. worker.postMessage( { type: 'decode', id: taskID, buffer }, [ buffer ] );
  76. //this.debug();
  77. } );
  78. } )
  79. .then( ( message ) => this._createGeometry( message.data ) );
  80. // Remove task from the task list.
  81. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  82. objectPending
  83. .catch( () => true )
  84. .then( () => {
  85. if ( worker && taskID ) {
  86. this._releaseTask( worker, taskID );
  87. //this.debug();
  88. }
  89. } );
  90. // Cache the task result.
  91. Rhino3dmLoader.taskCache.set( buffer, {
  92. url: url,
  93. promise: objectPending
  94. } );
  95. return objectPending;
  96. },
  97. parse: function ( data, onLoad, onError ) {
  98. this.decodeObjects( data, '' )
  99. .then( onLoad )
  100. .catch( onError );
  101. },
  102. _compareMaterials: function ( material ) {
  103. var mat = {};
  104. mat.name = material.name;
  105. mat.color = {};
  106. mat.color.r = material.color.r;
  107. mat.color.g = material.color.g;
  108. mat.color.b = material.color.b;
  109. mat.type = material.type;
  110. for ( var i = 0; i < this.materials.length; i ++ ) {
  111. var m = this.materials[ i ];
  112. var _mat = {};
  113. _mat.name = m.name;
  114. _mat.color = {};
  115. _mat.color.r = m.color.r;
  116. _mat.color.g = m.color.g;
  117. _mat.color.b = m.color.b;
  118. _mat.type = m.type;
  119. if ( JSON.stringify( mat ) === JSON.stringify( _mat ) ) {
  120. return m;
  121. }
  122. }
  123. return null;
  124. },
  125. _createMaterial: function ( material ) {
  126. if ( material === undefined ) {
  127. return new MeshStandardMaterial( {
  128. color: new Color( 1, 1, 1 ),
  129. metalness: 0.8,
  130. name: 'default',
  131. side: 2
  132. } );
  133. }
  134. var _diffuseColor = material.diffuseColor;
  135. var diffusecolor = new Color( _diffuseColor.r / 255.0, _diffuseColor.g / 255.0, _diffuseColor.b / 255.0 );
  136. if ( _diffuseColor.r === 0 && _diffuseColor.g === 0 && _diffuseColor.b === 0 ) {
  137. diffusecolor.r = 1;
  138. diffusecolor.g = 1;
  139. diffusecolor.b = 1;
  140. }
  141. return new MeshStandardMaterial( {
  142. color: diffusecolor,
  143. metalness: 0.8,
  144. name: material.name,
  145. side: 2
  146. } );
  147. },
  148. _createGeometry: function ( data ) {
  149. // console.log(data);
  150. var object = new Object3D();
  151. var instanceDefinitionObjects = [];
  152. var instanceDefinitions = [];
  153. var instanceReferences = [];
  154. object.userData[ 'layers' ] = data.layers;
  155. object.userData[ 'groups' ] = data.groups;
  156. var objects = data.objects;
  157. var materials = data.materials;
  158. for ( var i = 0; i < objects.length; i ++ ) {
  159. var obj = objects[ i ];
  160. var attributes = obj.attributes;
  161. switch ( obj.objectType ) {
  162. case 'InstanceDefinition':
  163. instanceDefinitions.push( obj );
  164. break;
  165. case 'InstanceReference':
  166. instanceReferences.push( obj );
  167. break;
  168. default:
  169. var material = this._createMaterial( materials[ attributes.materialIndex ] );
  170. var m = this._compareMaterials( material );
  171. if ( m === null ) {
  172. this.materials.push( material );
  173. } else {
  174. material = m;
  175. }
  176. var _object = this._createObject( obj, material );
  177. if ( ! this.materials.includes( material ) ) {
  178. this.materials.push( material );
  179. }
  180. if ( _object === undefined ) {
  181. continue;
  182. }
  183. _object.visible = data.layers[ attributes.layerIndex ].visible;
  184. if ( attributes.isInstanceDefinitionObject ) {
  185. instanceDefinitionObjects.push( _object );
  186. } else {
  187. object.add( _object );
  188. }
  189. break;
  190. }
  191. }
  192. for ( var i = 0; i < instanceDefinitions.length; i ++ ) {
  193. var iDef = instanceDefinitions[ i ];
  194. var objects = [];
  195. for ( var j = 0; j < iDef.attributes.objectIds.length; j ++ ) {
  196. var objId = iDef.attributes.objectIds[ j ];
  197. for ( var p = 0; p < instanceDefinitionObjects.length; p ++ ) {
  198. var idoId = instanceDefinitionObjects[ p ].userData.attributes.id;
  199. if ( objId === idoId ) {
  200. objects.push( instanceDefinitionObjects[ p ] );
  201. }
  202. }
  203. }
  204. // Currently clones geometry and does not take advantage of instancing
  205. for ( var j = 0; j < instanceReferences.length; j ++ ) {
  206. var iRef = instanceReferences[ j ];
  207. if ( iRef.geometry.parentIdefId === iDef.attributes.id ) {
  208. var iRefObject = new Object3D();
  209. var xf = iRef.geometry.xform.array;
  210. var matrix = new Matrix4();
  211. 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 ] );
  212. iRefObject.applyMatrix4( matrix );
  213. for ( var p = 0; p < objects.length; p ++ ) {
  214. iRefObject.add( objects[ p ].clone( true ) );
  215. }
  216. object.add( iRefObject );
  217. }
  218. }
  219. }
  220. console.log( this.materials );
  221. return object;
  222. },
  223. _createObject: function ( obj, mat ) {
  224. var loader = new BufferGeometryLoader();
  225. var attributes = obj.attributes;
  226. switch ( obj.objectType ) {
  227. case 'Point':
  228. case 'PointSet':
  229. var geometry = loader.parse( obj.geometry );
  230. var material = new PointsMaterial( { sizeAttenuation: true, vertexColors: true } );
  231. var m = this._compareMaterials( material );
  232. if ( m === null ) {
  233. this.materials.push( material );
  234. } else {
  235. material = m;
  236. }
  237. var points = new Points( geometry, material );
  238. points.userData[ 'attributes' ] = attributes;
  239. points.userData[ 'objectType' ] = obj.objectType;
  240. return points;
  241. case 'Mesh':
  242. case 'Extrusion':
  243. var geometry = loader.parse( obj.geometry );
  244. var mesh = new Mesh( geometry, mat );
  245. mesh.castShadow = attributes.castsShadows;
  246. mesh.receiveShadow = attributes.receivesShadows;
  247. mesh.userData[ 'attributes' ] = attributes;
  248. mesh.userData[ 'objectType' ] = obj.objectType;
  249. return mesh;
  250. case 'Brep':
  251. var brepObject = new Object3D();
  252. for ( var j = 0; j < obj.geometry.length; j ++ ) {
  253. geometry = loader.parse( obj.geometry[ j ] );
  254. var mesh = new Mesh( geometry, mat );
  255. mesh.castShadow = attributes.castsShadows;
  256. mesh.receiveShadow = attributes.receivesShadows;
  257. brepObject.add( mesh );
  258. }
  259. brepObject.userData[ 'attributes' ] = attributes;
  260. brepObject.userData[ 'objectType' ] = obj.objectType;
  261. return brepObject;
  262. case 'Curve':
  263. geometry = loader.parse( obj.geometry );
  264. var _color = attributes.drawColor;
  265. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  266. var material = new LineBasicMaterial( { color: color } );
  267. var m = this._compareMaterials( material );
  268. if ( m === null ) {
  269. this.materials.push( material );
  270. } else {
  271. material = m;
  272. }
  273. var lines = new Line( geometry, material );
  274. lines.userData[ 'attributes' ] = attributes;
  275. lines.userData[ 'objectType' ] = obj.objectType;
  276. return lines;
  277. case 'TextDot':
  278. geometry = obj.geometry;
  279. var dotDiv = document.createElement( 'div' );
  280. dotDiv.style.fontFamily = geometry.fontFace;
  281. dotDiv.style.fontSize = `${geometry.fontHeight}px`;
  282. dotDiv.style.marginTop = '-1em';
  283. dotDiv.style.color = '#FFF';
  284. dotDiv.style.padding = '2px';
  285. dotDiv.style.paddingRight = '5px';
  286. dotDiv.style.paddingLeft = '5px';
  287. dotDiv.style.borderRadius = '5px';
  288. var color = attributes.drawColor;
  289. dotDiv.style.background = `rgba(${color.r},${color.g},${color.b},${color.a})`;
  290. dotDiv.textContent = geometry.text;
  291. var dot = new CSS2DObject( dotDiv );
  292. var location = geometry.point;
  293. dot.position.set( location[ 0 ], location[ 1 ], location[ 2 ] );
  294. dot.userData[ 'attributes' ] = attributes;
  295. dot.userData[ 'objectType' ] = obj.objectType;
  296. return dot;
  297. case 'Light':
  298. geometry = obj.geometry;
  299. var light;
  300. if ( geometry.isDirectionalLight ) {
  301. light = new DirectionalLight();
  302. light.castShadow = attributes.castsShadows;
  303. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  304. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  305. light.shadow.normalBias = 0.1;
  306. } else if ( geometry.isPointLight ) {
  307. light = new PointLight();
  308. light.castShadow = attributes.castsShadows;
  309. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  310. light.shadow.normalBias = 0.1;
  311. } else if ( geometry.isRectangularLight ) {
  312. light = new RectAreaLight();
  313. var width = Math.abs( geometry.width[ 2 ] );
  314. var height = Math.abs( geometry.length[ 0 ] );
  315. light.position.set( geometry.location[ 0 ] - ( height / 2 ), geometry.location[ 1 ], geometry.location[ 2 ] - ( width / 2 ) );
  316. light.height = height;
  317. light.width = width;
  318. light.lookAt( new Vector3( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] ) );
  319. } else if ( geometry.isSpotLight ) {
  320. light = new SpotLight();
  321. light.castShadow = attributes.castsShadows;
  322. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  323. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  324. light.angle = geometry.spotAngleRadians;
  325. light.shadow.normalBias = 0.1;
  326. } else if ( geometry.isLinearLight ) {
  327. console.warn( `THREE.3DMLoader: No conversion exists for linear lights.` );
  328. return;
  329. }
  330. if ( light ) {
  331. light.intensity = geometry.intensity;
  332. light.userData[ 'attributes' ] = attributes;
  333. light.userData[ 'objectType' ] = obj.objectType;
  334. }
  335. return light;
  336. }
  337. },
  338. _initLibrary: function () {
  339. if ( ! this.libraryPending ) {
  340. // Load rhino3dm wrapper.
  341. var jsLoader = new FileLoader( this.manager );
  342. jsLoader.setPath( this.libraryPath );
  343. var jsContent = new Promise( ( resolve, reject ) => {
  344. jsLoader.load( 'rhino3dm.js', resolve, undefined, reject );
  345. } );
  346. // Load rhino3dm WASM binary.
  347. var binaryLoader = new FileLoader( this.manager );
  348. binaryLoader.setPath( this.libraryPath );
  349. binaryLoader.setResponseType( 'arraybuffer' );
  350. var binaryContent = new Promise( ( resolve, reject ) => {
  351. binaryLoader.load( 'rhino3dm.wasm', resolve, undefined, reject );
  352. } );
  353. this.libraryPending = Promise.all( [ jsContent, binaryContent ] )
  354. .then( ( [ jsContent, binaryContent ] ) => {
  355. //this.libraryBinary = binaryContent;
  356. this.libraryConfig.wasmBinary = binaryContent;
  357. var fn = Rhino3dmLoader.Rhino3dmWorker.toString();
  358. var body = [
  359. '/* rhino3dm.js */',
  360. jsContent,
  361. '/* worker */',
  362. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  363. ].join( '\n' );
  364. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  365. } );
  366. }
  367. return this.libraryPending;
  368. },
  369. _getWorker: function ( taskCost ) {
  370. return this._initLibrary().then( () => {
  371. if ( this.workerPool.length < this.workerLimit ) {
  372. var worker = new Worker( this.workerSourceURL );
  373. worker._callbacks = {};
  374. worker._taskCosts = {};
  375. worker._taskLoad = 0;
  376. worker.postMessage( {
  377. type: 'init',
  378. libraryConfig: this.libraryConfig
  379. } );
  380. worker.onmessage = function ( e ) {
  381. var message = e.data;
  382. switch ( message.type ) {
  383. case 'decode':
  384. worker._callbacks[ message.id ].resolve( message );
  385. break;
  386. case 'error':
  387. worker._callbacks[ message.id ].reject( message );
  388. break;
  389. default:
  390. console.error( 'THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"' );
  391. }
  392. };
  393. this.workerPool.push( worker );
  394. } else {
  395. this.workerPool.sort( function ( a, b ) {
  396. return a._taskLoad > b._taskLoad ? - 1 : 1;
  397. } );
  398. }
  399. var worker = this.workerPool[ this.workerPool.length - 1 ];
  400. worker._taskLoad += taskCost;
  401. return worker;
  402. } );
  403. },
  404. _releaseTask: function ( worker, taskID ) {
  405. worker._taskLoad -= worker._taskCosts[ taskID ];
  406. delete worker._callbacks[ taskID ];
  407. delete worker._taskCosts[ taskID ];
  408. },
  409. dispose: function () {
  410. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  411. this.workerPool[ i ].terminate();
  412. }
  413. this.workerPool.length = 0;
  414. return this;
  415. }
  416. } );
  417. /* WEB WORKER */
  418. Rhino3dmLoader.Rhino3dmWorker = function () {
  419. var libraryPending;
  420. var libraryConfig;
  421. var rhino;
  422. onmessage = function ( e ) {
  423. var message = e.data;
  424. switch ( message.type ) {
  425. case 'init':
  426. libraryConfig = message.libraryConfig;
  427. var wasmBinary = libraryConfig.wasmBinary;
  428. var RhinoModule;
  429. libraryPending = new Promise( function ( resolve ) {
  430. /* Like Basis Loader */
  431. RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };
  432. rhino3dm( RhinoModule );
  433. } ).then( () => {
  434. rhino = RhinoModule;
  435. } );
  436. break;
  437. case 'decode':
  438. var buffer = message.buffer;
  439. libraryPending.then( () => {
  440. var data = decodeObjects( rhino, buffer );
  441. self.postMessage( { type: 'decode', id: message.id, data } );
  442. } );
  443. break;
  444. }
  445. };
  446. function decodeObjects( rhino, buffer ) {
  447. var arr = new Uint8Array( buffer );
  448. var doc = rhino.File3dm.fromByteArray( arr );
  449. var objects = [];
  450. var materials = [];
  451. var layers = [];
  452. var views = [];
  453. var namedViews = [];
  454. var groups = [];
  455. //Handle objects
  456. for ( var i = 0; i < doc.objects().count; i ++ ) {
  457. var _object = doc.objects().get( i );
  458. var object = extractObjectData( _object, doc );
  459. if ( object !== undefined ) {
  460. objects.push( object );
  461. }
  462. _object.delete();
  463. }
  464. // Handle instance definitions
  465. for ( var i = 0; i < doc.instanceDefinitions().count(); i ++ ) {
  466. var idef = doc.instanceDefinitions().get( i );
  467. var idefAttributes = extractProperties( idef );
  468. idefAttributes.objectIds = idef.getObjectIds();
  469. objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );
  470. }
  471. // Handle materials
  472. for ( var i = 0; i < doc.materials().count(); i ++ ) {
  473. var _material = doc.materials().get( i );
  474. var materialProperties = extractProperties( _material );
  475. var pbMaterialProperties = extractProperties( _material.physicallyBased() );
  476. var material = Object.assign( materialProperties, pbMaterialProperties );
  477. materials.push( material );
  478. _material.delete();
  479. }
  480. // Handle layers
  481. for ( var i = 0; i < doc.layers().count(); i ++ ) {
  482. var _layer = doc.layers().get( i );
  483. var layer = extractProperties( _layer );
  484. layers.push( layer );
  485. _layer.delete();
  486. }
  487. // Handle views
  488. for ( var i = 0; i < doc.views().count(); i ++ ) {
  489. var _view = doc.views().get( i );
  490. var view = extractProperties( _view );
  491. views.push( view );
  492. _view.delete();
  493. }
  494. // Handle named views
  495. for ( var i = 0; i < doc.namedViews().count(); i ++ ) {
  496. var _namedView = doc.namedViews().get( i );
  497. var namedView = extractProperties( _namedView );
  498. namedViews.push( namedView );
  499. _namedView.delete();
  500. }
  501. // Handle groups
  502. for ( var i = 0; i < doc.groups().count(); i ++ ) {
  503. var _group = doc.groups().get( i );
  504. var group = extractProperties( _group );
  505. groups.push( group );
  506. _group.delete();
  507. }
  508. // Handle settings
  509. var settings = extractProperties( doc.settings() );
  510. //TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.
  511. // Handle dimstyles
  512. // console.log(`Dimstyle Count: ${doc.dimstyles().count()}`);
  513. // Handle bitmaps
  514. // console.log(`Bitmap Count: ${doc.bitmaps().count()}`);
  515. // Handle instance definitions
  516. // console.log(`Instance Definitions Count: ${doc.instanceDefinitions().count()}`);
  517. // Handle strings -- this seems to be broken at the moment in rhino3dm
  518. // console.log(`Strings Count: ${doc.strings().count()}`);
  519. /*
  520. for( var i = 0; i < doc.strings().count(); i++ ){
  521. var _string= doc.strings().get( i );
  522. console.log(_string);
  523. var string = extractProperties( _group );
  524. strings.push( string );
  525. _string.delete();
  526. }
  527. */
  528. doc.delete();
  529. return { objects, materials, layers, views, namedViews, groups, settings };
  530. }
  531. function extractObjectData( object, doc ) {
  532. var _geometry = object.geometry();
  533. var _attributes = object.attributes();
  534. var objectType = _geometry.objectType;
  535. var geometry = null;
  536. var attributes = null;
  537. // skip instance definition objects
  538. //if( _attributes.isInstanceDefinitionObject ) { continue; }
  539. // TODO: handle other geometry types
  540. switch ( objectType ) {
  541. case rhino.ObjectType.Curve:
  542. var pts = curveToPoints( _geometry, 100 );
  543. var position = {};
  544. var color = {};
  545. var attributes = {};
  546. var data = {};
  547. position.itemSize = 3;
  548. position.type = 'Float32Array';
  549. position.array = [];
  550. for ( var j = 0; j < pts.length; j ++ ) {
  551. position.array.push( pts[ j ][ 0 ] );
  552. position.array.push( pts[ j ][ 1 ] );
  553. position.array.push( pts[ j ][ 2 ] );
  554. }
  555. attributes.position = position;
  556. data.attributes = attributes;
  557. geometry = { data };
  558. break;
  559. case rhino.ObjectType.Point:
  560. var pt = _geometry.location;
  561. var position = {};
  562. var color = {};
  563. var attributes = {};
  564. var data = {};
  565. position.itemSize = 3;
  566. position.type = 'Float32Array';
  567. position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];
  568. var _color = _attributes.drawColor( doc );
  569. color.itemSize = 3;
  570. color.type = 'Float32Array';
  571. color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];
  572. attributes.position = position;
  573. attributes.color = color;
  574. data.attributes = attributes;
  575. geometry = { data };
  576. break;
  577. case rhino.ObjectType.PointSet:
  578. case rhino.ObjectType.Mesh:
  579. geometry = _geometry.toThreejsJSON();
  580. break;
  581. case rhino.ObjectType.Brep:
  582. var faces = _geometry.faces();
  583. geometry = [];
  584. for ( var faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {
  585. var face = faces.get( faceIndex );
  586. var mesh = face.getMesh( rhino.MeshType.Any );
  587. if ( mesh ) {
  588. geometry.push( mesh.toThreejsJSON() );
  589. mesh.delete();
  590. }
  591. face.delete();
  592. }
  593. faces.delete();
  594. break;
  595. case rhino.ObjectType.Extrusion:
  596. var mesh = _geometry.getMesh( rhino.MeshType.Any );
  597. if ( mesh ) {
  598. geometry = mesh.toThreejsJSON();
  599. mesh.delete();
  600. }
  601. break;
  602. case rhino.ObjectType.TextDot:
  603. geometry = extractProperties( _geometry );
  604. break;
  605. case rhino.ObjectType.Light:
  606. geometry = extractProperties( _geometry );
  607. break;
  608. case rhino.ObjectType.InstanceReference:
  609. geometry = extractProperties( _geometry );
  610. geometry.xform = extractProperties( _geometry.xform );
  611. geometry.xform.array = _geometry.xform.toFloatArray( true );
  612. break;
  613. /*
  614. case rhino.ObjectType.Annotation:
  615. case rhino.ObjectType.Hatch:
  616. case rhino.ObjectType.SubD:
  617. case rhino.ObjectType.ClipPlane:
  618. */
  619. default:
  620. console.warn( `THREE.3DMLoader: TODO: Implement ${objectType.constructor.name}` );
  621. break;
  622. }
  623. if ( geometry ) {
  624. var attributes = extractProperties( _attributes );
  625. if ( _attributes.groupCount > 0 ) {
  626. attributes.groupIds = _attributes.getGroupList();
  627. }
  628. attributes.drawColor = _attributes.drawColor( doc );
  629. objectType = objectType.constructor.name;
  630. objectType = objectType.substring( 11, objectType.length );
  631. return { geometry, attributes, objectType };
  632. }
  633. }
  634. function extractProperties( object ) {
  635. var result = {};
  636. for ( var property in object ) {
  637. if ( typeof object[ property ] !== 'function' ) {
  638. result[ property ] = object[ property ];
  639. } else {
  640. // console.log(`${property}: ${object[property]}`);
  641. }
  642. }
  643. return result;
  644. }
  645. function curveToPoints( curve, pointLimit ) {
  646. var pointCount = pointLimit;
  647. var rc = [];
  648. var ts = [];
  649. if ( curve instanceof rhino.LineCurve ) {
  650. return [ curve.pointAtStart, curve.pointAtEnd ];
  651. }
  652. if ( curve instanceof rhino.PolylineCurve ) {
  653. pointCount = curve.pointCount;
  654. for ( var i = 0; i < pointCount; i ++ ) {
  655. rc.push( curve.point( i ) );
  656. }
  657. return rc;
  658. }
  659. if ( curve instanceof rhino.PolyCurve ) {
  660. var segmentCount = curve.segmentCount;
  661. for ( var i = 0; i < segmentCount; i ++ ) {
  662. var segment = curve.segmentCurve( i );
  663. var segmentArray = curveToPoints( segment );
  664. rc = rc.concat( segmentArray );
  665. segment.delete();
  666. }
  667. return rc;
  668. }
  669. if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {
  670. // console.info( 'degree 1 curve' );
  671. }
  672. var domain = curve.domain;
  673. var divisions = pointCount - 1.0;
  674. for ( var j = 0; j < pointCount; j ++ ) {
  675. var t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );
  676. if ( t === domain[ 0 ] || t === domain[ 1 ] ) {
  677. ts.push( t );
  678. continue;
  679. }
  680. var tan = curve.tangentAt( t );
  681. var prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );
  682. // Duplicaated from THREE.Vector3
  683. // How to pass imports to worker?
  684. var tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];
  685. var ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];
  686. var denominator = Math.sqrt( tS * ptS );
  687. var angle;
  688. if ( denominator === 0 ) {
  689. angle = Math.PI / 2;
  690. } else {
  691. var theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;
  692. angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );
  693. }
  694. if ( angle < 0.1 ) continue;
  695. ts.push( t );
  696. }
  697. rc = ts.map( t => curve.pointAt( t ) );
  698. return rc;
  699. }
  700. };
  701. export { Rhino3dmLoader };