3DMLoader.js 31 KB

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