2
0

3DMLoader.js 29 KB

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