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