3DMLoader.js 29 KB

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