3DMLoader.js 29 KB

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