3DMLoader.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  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[ attributes.materialIndex ];
  208. var material = this._createMaterial( rMaterial );
  209. material = this._compareMaterials( material );
  210. var _object = this._createObject( obj, material );
  211. } else {
  212. var material = this._createMaterial( );
  213. var _object = this._createObject( obj, material );
  214. }
  215. if ( _object === undefined ) {
  216. continue;
  217. }
  218. var layer = data.layers[ attributes.layerIndex ];
  219. _object.visible = layer ? data.layers[ attributes.layerIndex ].visible : true;
  220. if ( attributes.isInstanceDefinitionObject ) {
  221. instanceDefinitionObjects.push( _object );
  222. } else {
  223. object.add( _object );
  224. }
  225. break;
  226. }
  227. }
  228. for ( var i = 0; i < instanceDefinitions.length; i ++ ) {
  229. var iDef = instanceDefinitions[ i ];
  230. var objects = [];
  231. for ( var j = 0; j < iDef.attributes.objectIds.length; j ++ ) {
  232. var objId = iDef.attributes.objectIds[ j ];
  233. for ( var p = 0; p < instanceDefinitionObjects.length; p ++ ) {
  234. var idoId = instanceDefinitionObjects[ p ].userData.attributes.id;
  235. if ( objId === idoId ) {
  236. objects.push( instanceDefinitionObjects[ p ] );
  237. }
  238. }
  239. }
  240. // Currently clones geometry and does not take advantage of instancing
  241. for ( var j = 0; j < instanceReferences.length; j ++ ) {
  242. var iRef = instanceReferences[ j ];
  243. if ( iRef.geometry.parentIdefId === iDef.attributes.id ) {
  244. var iRefObject = new Object3D();
  245. var xf = iRef.geometry.xform.array;
  246. var matrix = new Matrix4();
  247. 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 ] );
  248. iRefObject.applyMatrix4( matrix );
  249. for ( var p = 0; p < objects.length; p ++ ) {
  250. iRefObject.add( objects[ p ].clone( true ) );
  251. }
  252. object.add( iRefObject );
  253. }
  254. }
  255. }
  256. object.userData[ 'materials' ] = this.materials;
  257. return object;
  258. },
  259. _createObject: function ( obj, mat ) {
  260. var loader = new BufferGeometryLoader();
  261. var attributes = obj.attributes;
  262. switch ( obj.objectType ) {
  263. case 'Point':
  264. case 'PointSet':
  265. var geometry = loader.parse( obj.geometry );
  266. var material = null;
  267. if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
  268. material = new PointsMaterial( { vertexColors: true, sizeAttenuation: false, size: 2 } );
  269. } else {
  270. var _color = attributes.drawColor;
  271. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  272. material = new PointsMaterial( { color: color, sizeAttenuation: false, size: 2 } );
  273. }
  274. material = this._compareMaterials( material );
  275. var points = new Points( geometry, material );
  276. points.userData[ 'attributes' ] = attributes;
  277. points.userData[ 'objectType' ] = obj.objectType;
  278. if ( attributes.name ) {
  279. points.name = attributes.name;
  280. }
  281. return points;
  282. case 'Mesh':
  283. case 'Extrusion':
  284. case 'SubD':
  285. case 'Brep':
  286. if ( obj.geometry === null ) return;
  287. var geometry = loader.parse( obj.geometry );
  288. if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
  289. mat.vertexColors = true;
  290. }
  291. if ( mat === null ) {
  292. mat = this._createMaterial();
  293. mat = this._compareMaterials( mat );
  294. }
  295. var mesh = new Mesh( geometry, mat );
  296. mesh.castShadow = attributes.castsShadows;
  297. mesh.receiveShadow = attributes.receivesShadows;
  298. mesh.userData[ 'attributes' ] = attributes;
  299. mesh.userData[ 'objectType' ] = obj.objectType;
  300. if ( attributes.name ) {
  301. mesh.name = attributes.name;
  302. }
  303. return mesh;
  304. case 'Curve':
  305. geometry = loader.parse( obj.geometry );
  306. var _color = attributes.drawColor;
  307. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  308. var material = new LineBasicMaterial( { color: color } );
  309. material = this._compareMaterials( material );
  310. var lines = new Line( geometry, material );
  311. lines.userData[ 'attributes' ] = attributes;
  312. lines.userData[ 'objectType' ] = obj.objectType;
  313. if ( attributes.name ) {
  314. lines.name = attributes.name;
  315. }
  316. return lines;
  317. case 'TextDot':
  318. geometry = obj.geometry;
  319. var ctx = document.createElement( 'canvas' ).getContext( '2d' );
  320. var font = `${geometry.fontHeight}px ${geometry.fontFace}`;
  321. ctx.font = font;
  322. var width = ctx.measureText( geometry.text ).width + 10;
  323. var height = geometry.fontHeight + 10;
  324. var r = window.devicePixelRatio;
  325. ctx.canvas.width = width * r;
  326. ctx.canvas.height = height * r;
  327. ctx.canvas.style.width = width + 'px';
  328. ctx.canvas.style.height = height + 'px';
  329. ctx.setTransform( r, 0, 0, r, 0, 0 );
  330. ctx.font = font;
  331. ctx.textBaseline = 'middle';
  332. ctx.textAlign = 'center';
  333. var color = attributes.drawColor;
  334. ctx.fillStyle = `rgba(${color.r},${color.g},${color.b},${color.a})`;
  335. ctx.fillRect( 0, 0, width, height );
  336. ctx.fillStyle = 'white';
  337. ctx.fillText( geometry.text, width / 2, height / 2 );
  338. var texture = new CanvasTexture( ctx.canvas );
  339. texture.minFilter = LinearFilter;
  340. texture.wrapS = ClampToEdgeWrapping;
  341. texture.wrapT = ClampToEdgeWrapping;
  342. var material = new SpriteMaterial( { map: texture, depthTest: false } );
  343. var sprite = new Sprite( material );
  344. sprite.position.set( geometry.point[ 0 ], geometry.point[ 1 ], geometry.point[ 2 ] );
  345. sprite.scale.set( width / 10, height / 10, 1.0 );
  346. sprite.userData[ 'attributes' ] = attributes;
  347. sprite.userData[ 'objectType' ] = obj.objectType;
  348. if ( attributes.name ) {
  349. sprite.name = attributes.name;
  350. }
  351. return sprite;
  352. case 'Light':
  353. geometry = obj.geometry;
  354. var light;
  355. if ( geometry.isDirectionalLight ) {
  356. light = new DirectionalLight();
  357. light.castShadow = attributes.castsShadows;
  358. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  359. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  360. light.shadow.normalBias = 0.1;
  361. } else if ( geometry.isPointLight ) {
  362. light = new PointLight();
  363. light.castShadow = attributes.castsShadows;
  364. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  365. light.shadow.normalBias = 0.1;
  366. } else if ( geometry.isRectangularLight ) {
  367. light = new RectAreaLight();
  368. var width = Math.abs( geometry.width[ 2 ] );
  369. var height = Math.abs( geometry.length[ 0 ] );
  370. light.position.set( geometry.location[ 0 ] - ( height / 2 ), geometry.location[ 1 ], geometry.location[ 2 ] - ( width / 2 ) );
  371. light.height = height;
  372. light.width = width;
  373. light.lookAt( new Vector3( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] ) );
  374. } else if ( geometry.isSpotLight ) {
  375. light = new SpotLight();
  376. light.castShadow = attributes.castsShadows;
  377. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  378. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  379. light.angle = geometry.spotAngleRadians;
  380. light.shadow.normalBias = 0.1;
  381. } else if ( geometry.isLinearLight ) {
  382. console.warn( 'THREE.3DMLoader: No conversion exists for linear lights.' );
  383. return;
  384. }
  385. if ( light ) {
  386. light.intensity = geometry.intensity;
  387. var _color = geometry.diffuse;
  388. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  389. light.color = color;
  390. light.userData[ 'attributes' ] = attributes;
  391. light.userData[ 'objectType' ] = obj.objectType;
  392. }
  393. return light;
  394. }
  395. },
  396. _initLibrary: function () {
  397. if ( ! this.libraryPending ) {
  398. // Load rhino3dm wrapper.
  399. var jsLoader = new FileLoader( this.manager );
  400. jsLoader.setPath( this.libraryPath );
  401. var jsContent = new Promise( ( resolve, reject ) => {
  402. jsLoader.load( 'rhino3dm.js', resolve, undefined, reject );
  403. } );
  404. // Load rhino3dm WASM binary.
  405. var binaryLoader = new FileLoader( this.manager );
  406. binaryLoader.setPath( this.libraryPath );
  407. binaryLoader.setResponseType( 'arraybuffer' );
  408. var binaryContent = new Promise( ( resolve, reject ) => {
  409. binaryLoader.load( 'rhino3dm.wasm', resolve, undefined, reject );
  410. } );
  411. this.libraryPending = Promise.all( [ jsContent, binaryContent ] )
  412. .then( ( [ jsContent, binaryContent ] ) => {
  413. //this.libraryBinary = binaryContent;
  414. this.libraryConfig.wasmBinary = binaryContent;
  415. var fn = Rhino3dmLoader.Rhino3dmWorker.toString();
  416. var body = [
  417. '/* rhino3dm.js */',
  418. jsContent,
  419. '/* worker */',
  420. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  421. ].join( '\n' );
  422. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  423. } );
  424. }
  425. return this.libraryPending;
  426. },
  427. _getWorker: function ( taskCost ) {
  428. return this._initLibrary().then( () => {
  429. if ( this.workerPool.length < this.workerLimit ) {
  430. var worker = new Worker( this.workerSourceURL );
  431. worker._callbacks = {};
  432. worker._taskCosts = {};
  433. worker._taskLoad = 0;
  434. worker.postMessage( {
  435. type: 'init',
  436. libraryConfig: this.libraryConfig
  437. } );
  438. worker.onmessage = function ( e ) {
  439. var message = e.data;
  440. switch ( message.type ) {
  441. case 'decode':
  442. worker._callbacks[ message.id ].resolve( message );
  443. break;
  444. case 'error':
  445. worker._callbacks[ message.id ].reject( message );
  446. break;
  447. default:
  448. console.error( 'THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"' );
  449. }
  450. };
  451. this.workerPool.push( worker );
  452. } else {
  453. this.workerPool.sort( function ( a, b ) {
  454. return a._taskLoad > b._taskLoad ? - 1 : 1;
  455. } );
  456. }
  457. var worker = this.workerPool[ this.workerPool.length - 1 ];
  458. worker._taskLoad += taskCost;
  459. return worker;
  460. } );
  461. },
  462. _releaseTask: function ( worker, taskID ) {
  463. worker._taskLoad -= worker._taskCosts[ taskID ];
  464. delete worker._callbacks[ taskID ];
  465. delete worker._taskCosts[ taskID ];
  466. },
  467. dispose: function () {
  468. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  469. this.workerPool[ i ].terminate();
  470. }
  471. this.workerPool.length = 0;
  472. return this;
  473. }
  474. } );
  475. /* WEB WORKER */
  476. Rhino3dmLoader.Rhino3dmWorker = function () {
  477. var libraryPending;
  478. var libraryConfig;
  479. var rhino;
  480. onmessage = function ( e ) {
  481. var message = e.data;
  482. switch ( message.type ) {
  483. case 'init':
  484. libraryConfig = message.libraryConfig;
  485. var wasmBinary = libraryConfig.wasmBinary;
  486. var RhinoModule;
  487. libraryPending = new Promise( function ( resolve ) {
  488. /* Like Basis Loader */
  489. RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };
  490. rhino3dm( RhinoModule ); // eslint-disable-line no-undef
  491. } ).then( () => {
  492. rhino = RhinoModule;
  493. } );
  494. break;
  495. case 'decode':
  496. var buffer = message.buffer;
  497. libraryPending.then( () => {
  498. var data = decodeObjects( rhino, buffer );
  499. self.postMessage( { type: 'decode', id: message.id, data } );
  500. } );
  501. break;
  502. }
  503. };
  504. function decodeObjects( rhino, buffer ) {
  505. var arr = new Uint8Array( buffer );
  506. var doc = rhino.File3dm.fromByteArray( arr );
  507. var objects = [];
  508. var materials = [];
  509. var layers = [];
  510. var views = [];
  511. var namedViews = [];
  512. var groups = [];
  513. //Handle objects
  514. var objs = doc.objects();
  515. var cnt = objs.count;
  516. for ( var i = 0; i < cnt; i ++ ) {
  517. var _object = objs.get( i );
  518. var object = extractObjectData( _object, doc );
  519. _object.delete();
  520. if ( object ) {
  521. objects.push( object );
  522. }
  523. }
  524. // Handle instance definitions
  525. // console.log( `Instance Definitions Count: ${doc.instanceDefinitions().count()}` );
  526. for ( var i = 0; i < doc.instanceDefinitions().count(); i ++ ) {
  527. var idef = doc.instanceDefinitions().get( i );
  528. var idefAttributes = extractProperties( idef );
  529. idefAttributes.objectIds = idef.getObjectIds();
  530. objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );
  531. }
  532. // Handle materials
  533. var textureTypes = [
  534. // rhino.TextureType.Bitmap,
  535. rhino.TextureType.Diffuse,
  536. rhino.TextureType.Bump,
  537. rhino.TextureType.Transparency,
  538. rhino.TextureType.Opacity,
  539. rhino.TextureType.Emap
  540. ];
  541. var pbrTextureTypes = [
  542. rhino.TextureType.PBR_BaseColor,
  543. rhino.TextureType.PBR_Subsurface,
  544. rhino.TextureType.PBR_SubsurfaceScattering,
  545. rhino.TextureType.PBR_SubsurfaceScatteringRadius,
  546. rhino.TextureType.PBR_Metallic,
  547. rhino.TextureType.PBR_Specular,
  548. rhino.TextureType.PBR_SpecularTint,
  549. rhino.TextureType.PBR_Roughness,
  550. rhino.TextureType.PBR_Anisotropic,
  551. rhino.TextureType.PBR_Anisotropic_Rotation,
  552. rhino.TextureType.PBR_Sheen,
  553. rhino.TextureType.PBR_SheenTint,
  554. rhino.TextureType.PBR_Clearcoat,
  555. rhino.TextureType.PBR_ClearcoatBump,
  556. rhino.TextureType.PBR_ClearcoatRoughness,
  557. rhino.TextureType.PBR_OpacityIor,
  558. rhino.TextureType.PBR_OpacityRoughness,
  559. rhino.TextureType.PBR_Emission,
  560. rhino.TextureType.PBR_AmbientOcclusion,
  561. rhino.TextureType.PBR_Displacement
  562. ];
  563. for ( var i = 0; i < doc.materials().count(); i ++ ) {
  564. var _material = doc.materials().get( i );
  565. var _pbrMaterial = _material.physicallyBased();
  566. var material = extractProperties( _material );
  567. var textures = [];
  568. for ( var j = 0; j < textureTypes.length; j ++ ) {
  569. var _texture = _material.getTexture( textureTypes[ j ] );
  570. if ( _texture ) {
  571. var textureType = textureTypes[ j ].constructor.name;
  572. textureType = textureType.substring( 12, textureType.length );
  573. var texture = { type: textureType };
  574. var image = doc.getEmbeddedFileAsBase64( _texture.fileName );
  575. if ( image ) {
  576. texture.image = 'data:image/png;base64,' + image;
  577. } else {
  578. console.warn( `THREE.3DMLoader: Image for ${textureType} texture not embedded in file.` );
  579. texture.image = null;
  580. }
  581. textures.push( texture );
  582. _texture.delete();
  583. }
  584. }
  585. material.textures = textures;
  586. if ( _pbrMaterial.supported ) {
  587. console.log( 'pbr true' );
  588. for ( var j = 0; j < pbrTextureTypes.length; j ++ ) {
  589. var _texture = _material.getTexture( textureTypes[ j ] );
  590. if ( _texture ) {
  591. var image = doc.getEmbeddedFileAsBase64( _texture.fileName );
  592. var textureType = textureTypes[ j ].constructor.name;
  593. textureType = textureType.substring( 12, textureType.length );
  594. var texture = { type: textureType, image: 'data:image/png;base64,' + image };
  595. textures.push( texture );
  596. _texture.delete();
  597. }
  598. }
  599. var pbMaterialProperties = extractProperties( _material.physicallyBased() );
  600. material = Object.assign( pbMaterialProperties, material );
  601. }
  602. materials.push( material );
  603. _material.delete();
  604. _pbrMaterial.delete();
  605. }
  606. // Handle layers
  607. for ( var i = 0; i < doc.layers().count(); i ++ ) {
  608. var _layer = doc.layers().get( i );
  609. var layer = extractProperties( _layer );
  610. layers.push( layer );
  611. _layer.delete();
  612. }
  613. // Handle views
  614. for ( var i = 0; i < doc.views().count(); i ++ ) {
  615. var _view = doc.views().get( i );
  616. var view = extractProperties( _view );
  617. views.push( view );
  618. _view.delete();
  619. }
  620. // Handle named views
  621. for ( var i = 0; i < doc.namedViews().count(); i ++ ) {
  622. var _namedView = doc.namedViews().get( i );
  623. var namedView = extractProperties( _namedView );
  624. namedViews.push( namedView );
  625. _namedView.delete();
  626. }
  627. // Handle groups
  628. for ( var i = 0; i < doc.groups().count(); i ++ ) {
  629. var _group = doc.groups().get( i );
  630. var group = extractProperties( _group );
  631. groups.push( group );
  632. _group.delete();
  633. }
  634. // Handle settings
  635. var settings = extractProperties( doc.settings() );
  636. //TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.
  637. // Handle dimstyles
  638. // console.log( `Dimstyle Count: ${doc.dimstyles().count()}` );
  639. // Handle bitmaps
  640. // console.log( `Bitmap Count: ${doc.bitmaps().count()}` );
  641. // Handle strings -- this seems to be broken at the moment in rhino3dm
  642. // console.log( `Document Strings Count: ${doc.strings().count()}` );
  643. /*
  644. for( var i = 0; i < doc.strings().count(); i++ ){
  645. var _string= doc.strings().get( i );
  646. console.log(_string);
  647. var string = extractProperties( _group );
  648. strings.push( string );
  649. _string.delete();
  650. }
  651. */
  652. doc.delete();
  653. return { objects, materials, layers, views, namedViews, groups, settings };
  654. }
  655. function extractObjectData( object, doc ) {
  656. var _geometry = object.geometry();
  657. var _attributes = object.attributes();
  658. var objectType = _geometry.objectType;
  659. var geometry = null;
  660. var attributes = null;
  661. // skip instance definition objects
  662. //if( _attributes.isInstanceDefinitionObject ) { continue; }
  663. // TODO: handle other geometry types
  664. switch ( objectType ) {
  665. case rhino.ObjectType.Curve:
  666. var pts = curveToPoints( _geometry, 100 );
  667. var position = {};
  668. var attributes = {};
  669. var data = {};
  670. position.itemSize = 3;
  671. position.type = 'Float32Array';
  672. position.array = [];
  673. for ( var j = 0; j < pts.length; j ++ ) {
  674. position.array.push( pts[ j ][ 0 ] );
  675. position.array.push( pts[ j ][ 1 ] );
  676. position.array.push( pts[ j ][ 2 ] );
  677. }
  678. attributes.position = position;
  679. data.attributes = attributes;
  680. geometry = { data };
  681. break;
  682. case rhino.ObjectType.Point:
  683. var pt = _geometry.location;
  684. var position = {};
  685. var color = {};
  686. var attributes = {};
  687. var data = {};
  688. position.itemSize = 3;
  689. position.type = 'Float32Array';
  690. position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];
  691. var _color = _attributes.drawColor( doc );
  692. color.itemSize = 3;
  693. color.type = 'Float32Array';
  694. color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];
  695. attributes.position = position;
  696. attributes.color = color;
  697. data.attributes = attributes;
  698. geometry = { data };
  699. break;
  700. case rhino.ObjectType.PointSet:
  701. case rhino.ObjectType.Mesh:
  702. geometry = _geometry.toThreejsJSON();
  703. break;
  704. case rhino.ObjectType.Brep:
  705. var faces = _geometry.faces();
  706. var mesh = new rhino.Mesh();
  707. for ( var faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {
  708. var face = faces.get( faceIndex );
  709. var _mesh = face.getMesh( rhino.MeshType.Any );
  710. if ( _mesh ) {
  711. mesh.append( _mesh );
  712. _mesh.delete();
  713. }
  714. face.delete();
  715. }
  716. if ( mesh.faces().count > 0 ) {
  717. mesh.compact();
  718. geometry = mesh.toThreejsJSON();
  719. faces.delete();
  720. }
  721. mesh.delete();
  722. break;
  723. case rhino.ObjectType.Extrusion:
  724. var mesh = _geometry.getMesh( rhino.MeshType.Any );
  725. if ( mesh ) {
  726. geometry = mesh.toThreejsJSON();
  727. mesh.delete();
  728. }
  729. break;
  730. case rhino.ObjectType.TextDot:
  731. geometry = extractProperties( _geometry );
  732. break;
  733. case rhino.ObjectType.Light:
  734. geometry = extractProperties( _geometry );
  735. break;
  736. case rhino.ObjectType.InstanceReference:
  737. geometry = extractProperties( _geometry );
  738. geometry.xform = extractProperties( _geometry.xform );
  739. geometry.xform.array = _geometry.xform.toFloatArray( true );
  740. break;
  741. case rhino.ObjectType.SubD:
  742. // TODO: precalculate resulting vertices and faces and warn on excessive results
  743. _geometry.subdivide( 3 );
  744. var mesh = rhino.Mesh.createFromSubDControlNet( _geometry );
  745. if ( mesh ) {
  746. geometry = mesh.toThreejsJSON();
  747. mesh.delete();
  748. }
  749. break;
  750. /*
  751. case rhino.ObjectType.Annotation:
  752. case rhino.ObjectType.Hatch:
  753. case rhino.ObjectType.ClipPlane:
  754. */
  755. default:
  756. console.warn( `THREE.3DMLoader: TODO: Implement ${objectType.constructor.name}` );
  757. break;
  758. }
  759. if ( geometry ) {
  760. var attributes = extractProperties( _attributes );
  761. attributes.geometry = extractProperties( _geometry );
  762. if ( _attributes.groupCount > 0 ) {
  763. attributes.groupIds = _attributes.getGroupList();
  764. }
  765. if ( _attributes.userStringCount > 0 ) {
  766. attributes.userStrings = _attributes.getUserStrings();
  767. }
  768. if ( _geometry.userStringCount > 0 ) {
  769. attributes.geometry.userStrings = _geometry.getUserStrings();
  770. }
  771. attributes.drawColor = _attributes.drawColor( doc );
  772. objectType = objectType.constructor.name;
  773. objectType = objectType.substring( 11, objectType.length );
  774. return { geometry, attributes, objectType };
  775. } else {
  776. console.warn( `THREE.3DMLoader: ${objectType.constructor.name} has no associated mesh geometry.` );
  777. }
  778. }
  779. function extractProperties( object ) {
  780. var result = {};
  781. for ( var property in object ) {
  782. var value = object[ property ];
  783. if ( typeof value !== 'function' ) {
  784. if ( typeof value === 'object' && value !== null && value.hasOwnProperty( 'constructor' ) ) {
  785. result[ property ] = { name: value.constructor.name, value: value.value };
  786. } else {
  787. result[ property ] = value;
  788. }
  789. } else {
  790. // these are functions that could be called to extract more data.
  791. //console.log( `${property}: ${object[ property ].constructor.name}` );
  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. // Duplicated 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 };