3DMLoader.js 31 KB

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