3DMLoader.js 29 KB

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