3DMLoader.js 20 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. /**
  2. * @author Luis Fraguada / https://github.com/fraguada
  3. */
  4. import {
  5. BufferGeometryLoader,
  6. FileLoader,
  7. Loader,
  8. Object3D,
  9. MeshStandardMaterial,
  10. Mesh,
  11. Color,
  12. Points,
  13. PointsMaterial,
  14. Line,
  15. LineBasicMaterial,
  16. Matrix4
  17. } from "../../../build/three.module.js";
  18. import { CSS2DObject } from '../renderers/CSS2DRenderer.js';
  19. var Rhino3dmLoader = function ( manager ) {
  20. Loader.call( this, manager );
  21. this.libraryPath = '';
  22. this.libraryPending = null;
  23. this.libraryBinary = null;
  24. this.libraryConfig = {};
  25. this.workerLimit = 4;
  26. this.workerPool = [];
  27. this.workerNextTaskID = 1;
  28. this.workerSourceURL = '';
  29. this.workerConfig = {};
  30. };
  31. Rhino3dmLoader.taskCache = new WeakMap();
  32. Rhino3dmLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  33. constructor: Rhino3dmLoader,
  34. setLibraryPath: function ( path ) {
  35. this.libraryPath = path;
  36. return this;
  37. },
  38. setWorkerLimit: function ( workerLimit ) {
  39. this.workerLimit = workerLimit;
  40. return this;
  41. },
  42. load: function ( url, onLoad, onProgress, onError ) {
  43. var loader = new FileLoader( this.manager );
  44. loader.setPath( this.path );
  45. loader.setResponseType( 'arraybuffer' );
  46. loader.load( url, ( buffer ) => {
  47. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  48. // again from this thread.
  49. if ( Rhino3dmLoader.taskCache.has( buffer ) ) {
  50. var cachedTask = Rhino3dmLoader.taskCache.get( buffer );
  51. return cachedTask.promise.then( onLoad ).catch( onError );
  52. }
  53. this.decodeObjects( buffer, url )
  54. .then( onLoad )
  55. .catch( onError );
  56. }, onProgress, onError );
  57. },
  58. debug: function () {
  59. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  60. },
  61. decodeObjects: function ( buffer, url ) {
  62. var worker;
  63. var taskID;
  64. var taskCost = buffer.byteLength;
  65. var objectPending = this._getWorker( taskCost )
  66. .then( ( _worker ) => {
  67. worker = _worker;
  68. taskID = this.workerNextTaskID ++; //hmmm
  69. return new Promise( ( resolve, reject ) => {
  70. worker._callbacks[ taskID ] = { resolve, reject };
  71. worker.postMessage( { type: 'decode', id: taskID, buffer }, [ buffer ] );
  72. //this.debug();
  73. } );
  74. } )
  75. .then( ( message ) => this._createGeometry( message.data ) );
  76. // Remove task from the task list.
  77. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  78. objectPending
  79. .catch( () => true )
  80. .then( () => {
  81. if ( worker && taskID ) {
  82. this._releaseTask( worker, taskID );
  83. //this.debug();
  84. }
  85. } );
  86. // Cache the task result.
  87. Rhino3dmLoader.taskCache.set( buffer, {
  88. url: url,
  89. promise: objectPending
  90. } );
  91. return objectPending;
  92. },
  93. parse: function () {
  94. // parsing logic goes here
  95. console.warn( 'THREE.3DMLoader: TODO: Implement parse function' );
  96. },
  97. _createMaterial: function ( material ) {
  98. if ( material === undefined ) {
  99. return new MeshStandardMaterial( {
  100. color: new Color( 1, 1, 1 ),
  101. metalness: 0.8,
  102. name: 'default',
  103. side: 2
  104. } );
  105. }
  106. var _diffuseColor = material.diffuseColor;
  107. var diffusecolor = new Color( _diffuseColor.r / 255.0, _diffuseColor.g / 255.0, _diffuseColor.b / 255.0 );
  108. if ( _diffuseColor.r === 0 && _diffuseColor.g === 0 && _diffuseColor.b === 0 ) {
  109. diffusecolor.r = 1;
  110. diffusecolor.g = 1;
  111. diffusecolor.b = 1;
  112. }
  113. return new MeshStandardMaterial( {
  114. color: diffusecolor,
  115. metalness: 0.8,
  116. name: material.name,
  117. side: 2
  118. } );
  119. },
  120. _createGeometry: function ( data ) {
  121. // console.log(data);
  122. var object = new Object3D();
  123. var instanceDefinitionObjects = [];
  124. var instanceDefinitions = [];
  125. var instanceReferences = [];
  126. object.userData[ 'layers' ] = data.layers;
  127. object.userData[ 'groups' ] = data.groups;
  128. var objects = data.objects;
  129. var materials = data.materials;
  130. for ( var i = 0; i < objects.length; i ++ ) {
  131. var obj = objects[ i ];
  132. var attributes = obj.attributes;
  133. switch ( obj.objectType ) {
  134. case 'InstanceDefinition':
  135. instanceDefinitions.push( obj );
  136. break;
  137. case 'InstanceReference':
  138. instanceReferences.push( obj );
  139. break;
  140. default:
  141. var material = this._createMaterial( materials[ attributes.materialIndex ] );
  142. var _object = this._createObject( obj, material );
  143. if ( attributes.isInstanceDefinitionObject ) {
  144. instanceDefinitionObjects.push( _object );
  145. } else {
  146. object.add( _object );
  147. }
  148. break;
  149. }
  150. }
  151. for ( var i = 0; i < instanceDefinitions.length; i ++ ) {
  152. var iDef = instanceDefinitions[ i ];
  153. var objects = [];
  154. for ( var j = 0; j < iDef.attributes.objectIds.length; j ++ ) {
  155. var objId = iDef.attributes.objectIds[ j ];
  156. for ( var p = 0; p < instanceDefinitionObjects.length; p ++ ) {
  157. var idoId = instanceDefinitionObjects[ p ].userData.attributes.id;
  158. if ( objId === idoId ) {
  159. objects.push( instanceDefinitionObjects[ p ] );
  160. }
  161. }
  162. }
  163. // Currently clones geometry and does not take advantage of instancing
  164. for ( var j = 0; j < instanceReferences.length; j ++ ) {
  165. var iRef = instanceReferences[ j ];
  166. if ( iRef.geometry.parentIdefId === iDef.attributes.id ) {
  167. var iRefObject = new Object3D();
  168. var xf = iRef.geometry.xform.array;
  169. var matrix = new Matrix4();
  170. 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 ] );
  171. iRefObject.applyMatrix4( matrix );
  172. for ( var p = 0; p < objects.length; p ++ ) {
  173. iRefObject.add( objects[ p ].clone( true ) );
  174. }
  175. object.add( iRefObject );
  176. }
  177. }
  178. }
  179. return object;
  180. },
  181. _createObject: function ( obj, mat ) {
  182. var loader = new BufferGeometryLoader();
  183. var attributes = obj.attributes;
  184. switch ( obj.objectType ) {
  185. case 'Point':
  186. case 'PointSet':
  187. var geometry = loader.parse( obj.geometry );
  188. var material = new PointsMaterial( { sizeAttenuation: true, vertexColors: true } );
  189. var points = new Points( geometry, material );
  190. points.userData[ 'attributes' ] = attributes;
  191. points.userData[ 'objectType' ] = obj.objectType;
  192. return points;
  193. case 'Mesh':
  194. case 'Extrusion':
  195. var geometry = loader.parse( obj.geometry );
  196. var mesh = new Mesh( geometry, mat );
  197. mesh.castShadow = attributes.castsShadows;
  198. mesh.receiveShadow = attributes.receivesShadows;
  199. mesh.userData[ 'attributes' ] = attributes;
  200. mesh.userData[ 'objectType' ] = obj.objectType;
  201. return mesh;
  202. case 'Brep':
  203. var brepObject = new Object3D();
  204. for ( var j = 0; j < obj.geometry.length; j ++ ) {
  205. geometry = loader.parse( obj.geometry[ j ] );
  206. var mesh = new Mesh( geometry, mat );
  207. mesh.castShadow = attributes.castsShadows;
  208. mesh.receiveShadow = attributes.receivesShadows;
  209. brepObject.add( mesh );
  210. }
  211. brepObject.userData[ 'attributes' ] = attributes;
  212. brepObject.userData[ 'objectType' ] = obj.objectType;
  213. return brepObject;
  214. case 'Curve':
  215. geometry = loader.parse( obj.geometry );
  216. var _color = attributes.drawColor;
  217. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  218. var lines = new Line( geometry, new LineBasicMaterial( { color: color } ) );
  219. lines.userData[ 'attributes' ] = attributes;
  220. lines.userData[ 'objectType' ] = obj.objectType;
  221. return lines;
  222. case 'TextDot':
  223. geometry = obj.geometry;
  224. var dotDiv = document.createElement( 'div' );
  225. dotDiv.style.fontFamily = geometry.fontFace;
  226. dotDiv.style.fontSize = `${geometry.fontHeight}px`;
  227. dotDiv.style.marginTop = '-1em';
  228. dotDiv.style.color = '#FFF';
  229. dotDiv.style.padding = '2px';
  230. dotDiv.style.paddingRight = '5px';
  231. dotDiv.style.paddingLeft = '5px';
  232. dotDiv.style.borderRadius = '5px';
  233. var color = attributes.drawColor;
  234. dotDiv.style.background = `rgba(${color.r},${color.g},${color.b},${color.a})`;
  235. dotDiv.textContent = geometry.text;
  236. var dot = new CSS2DObject( dotDiv );
  237. var location = geometry.point;
  238. dot.position.set( location[ 0 ], location[ 1 ], location[ 2 ] );
  239. dot.userData[ 'attributes' ] = attributes;
  240. dot.userData[ 'objectType' ] = obj.objectType;
  241. return dot;
  242. }
  243. },
  244. _initLibrary: function () {
  245. if ( ! this.libraryPending ) {
  246. // Load rhino3dm wrapper.
  247. var jsLoader = new FileLoader( this.manager );
  248. jsLoader.setPath( this.libraryPath );
  249. var jsContent = new Promise( ( resolve, reject ) => {
  250. jsLoader.load( 'rhino3dm.js', resolve, undefined, reject );
  251. } );
  252. // Load rhino3dm WASM binary.
  253. var binaryLoader = new FileLoader( this.manager );
  254. binaryLoader.setPath( this.libraryPath );
  255. binaryLoader.setResponseType( 'arraybuffer' );
  256. var binaryContent = new Promise( ( resolve, reject ) => {
  257. binaryLoader.load( 'rhino3dm.wasm', resolve, undefined, reject );
  258. } );
  259. this.libraryPending = Promise.all( [ jsContent, binaryContent ] )
  260. .then( ( [ jsContent, binaryContent ] ) => {
  261. //this.libraryBinary = binaryContent;
  262. this.libraryConfig.wasmBinary = binaryContent;
  263. var fn = Rhino3dmLoader.Rhino3dmWorker.toString();
  264. var body = [
  265. '/* rhino3dm.js */',
  266. jsContent,
  267. '/* worker */',
  268. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  269. ].join( '\n' );
  270. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  271. } );
  272. }
  273. return this.libraryPending;
  274. },
  275. _getWorker: function ( taskCost ) {
  276. return this._initLibrary().then( () => {
  277. if ( this.workerPool.length < this.workerLimit ) {
  278. var worker = new Worker( this.workerSourceURL );
  279. worker._callbacks = {};
  280. worker._taskCosts = {};
  281. worker._taskLoad = 0;
  282. worker.postMessage( {
  283. type: 'init',
  284. libraryConfig: this.libraryConfig
  285. } );
  286. worker.onmessage = function ( e ) {
  287. var message = e.data;
  288. switch ( message.type ) {
  289. case 'decode':
  290. worker._callbacks[ message.id ].resolve( message );
  291. break;
  292. case 'error':
  293. worker._callbacks[ message.id ].reject( message );
  294. break;
  295. default:
  296. console.error( 'THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"' );
  297. }
  298. };
  299. this.workerPool.push( worker );
  300. } else {
  301. this.workerPool.sort( function ( a, b ) {
  302. return a._taskLoad > b._taskLoad ? - 1 : 1;
  303. } );
  304. }
  305. var worker = this.workerPool[ this.workerPool.length - 1 ];
  306. worker._taskLoad += taskCost;
  307. return worker;
  308. } );
  309. },
  310. _releaseTask: function ( worker, taskID ) {
  311. worker._taskLoad -= worker._taskCosts[ taskID ];
  312. delete worker._callbacks[ taskID ];
  313. delete worker._taskCosts[ taskID ];
  314. },
  315. dispose: function () {
  316. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  317. this.workerPool[ i ].terminate();
  318. }
  319. this.workerPool.length = 0;
  320. return this;
  321. }
  322. } );
  323. /* WEB WORKER */
  324. Rhino3dmLoader.Rhino3dmWorker = function () {
  325. var libraryPending;
  326. var libraryConfig;
  327. var rhino;
  328. onmessage = function ( e ) {
  329. var message = e.data;
  330. switch ( message.type ) {
  331. case 'init':
  332. libraryConfig = message.libraryConfig;
  333. var wasmBinary = libraryConfig.wasmBinary;
  334. var RhinoModule;
  335. libraryPending = new Promise( function ( resolve ) {
  336. /* Like Basis Loader */
  337. RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };
  338. rhino3dm( RhinoModule );
  339. } ).then( () => {
  340. rhino = RhinoModule;
  341. } );
  342. break;
  343. case 'decode':
  344. var buffer = message.buffer;
  345. libraryPending.then( () => {
  346. var data = decodeObjects( rhino, buffer );
  347. self.postMessage( { type: 'decode', id: message.id, data } );
  348. } );
  349. break;
  350. }
  351. };
  352. function decodeObjects( rhino, buffer ) {
  353. var arr = new Uint8Array( buffer );
  354. var doc = rhino.File3dm.fromByteArray( arr );
  355. var objects = [];
  356. var materials = [];
  357. var layers = [];
  358. var views = [];
  359. var namedViews = [];
  360. var groups = [];
  361. var strings = [];
  362. //Handle objects
  363. for ( var i = 0; i < doc.objects().count; i ++ ) {
  364. var _object = doc.objects().get( i );
  365. var object = extractObjectData( _object, doc );
  366. if ( object !== undefined ) {
  367. objects.push( object );
  368. }
  369. _object.delete();
  370. }
  371. // Handle instance definitions
  372. for ( var i = 0; i < doc.instanceDefinitions().count(); i ++ ) {
  373. var idef = doc.instanceDefinitions().get( i );
  374. var idefAttributes = extractProperties( idef );
  375. idefAttributes.objectIds = idef.getObjectIds();
  376. objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );
  377. }
  378. // Handle materials
  379. for ( var i = 0; i < doc.materials().count(); i ++ ) {
  380. var _material = doc.materials().get( i );
  381. var materialProperties = extractProperties( _material );
  382. var pbMaterialProperties = extractProperties( _material.physicallyBased() );
  383. var material = Object.assign( materialProperties, pbMaterialProperties );
  384. materials.push( material );
  385. _material.delete();
  386. }
  387. // Handle layers
  388. for ( var i = 0; i < doc.layers().count(); i ++ ) {
  389. var _layer = doc.layers().get( i );
  390. var layer = extractProperties( _layer );
  391. layers.push( layer );
  392. _layer.delete();
  393. }
  394. // Handle views
  395. for ( var i = 0; i < doc.views().count(); i ++ ) {
  396. var _view = doc.views().get( i );
  397. var view = extractProperties( _view );
  398. views.push( view );
  399. _view.delete();
  400. }
  401. // Handle named views
  402. for ( var i = 0; i < doc.namedViews().count(); i ++ ) {
  403. var _namedView = doc.namedViews().get( i );
  404. var namedView = extractProperties( _namedView );
  405. namedViews.push( namedView );
  406. _namedView.delete();
  407. }
  408. // Handle groups
  409. for ( var i = 0; i < doc.groups().count(); i ++ ) {
  410. var _group = doc.groups().get( i );
  411. var group = extractProperties( _group );
  412. groups.push( group );
  413. _group.delete();
  414. }
  415. // Handle settings
  416. var settings = extractProperties( doc.settings() );
  417. //TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.
  418. // Handle dimstyles
  419. // console.log(`Dimstyle Count: ${doc.dimstyles().count()}`);
  420. // Handle bitmaps
  421. // console.log(`Bitmap Count: ${doc.bitmaps().count()}`);
  422. // Handle instance definitions
  423. // console.log(`Instance Definitions Count: ${doc.instanceDefinitions().count()}`);
  424. // Handle strings -- this seems to be broken at the moment in rhino3dm
  425. // console.log(`Strings Count: ${doc.strings().count()}`);
  426. /*
  427. for( var i = 0; i < doc.strings().count(); i++ ){
  428. var _string= doc.strings().get( i );
  429. console.log(_string);
  430. var string = extractProperties( _group );
  431. strings.push( string );
  432. _string.delete();
  433. }
  434. */
  435. doc.delete();
  436. return { objects, materials, layers, views, namedViews, groups, settings };
  437. }
  438. function extractObjectData( object, doc ) {
  439. var _geometry = object.geometry();
  440. var _attributes = object.attributes();
  441. var objectType = _geometry.objectType;
  442. var geometry = null;
  443. var attributes = null;
  444. // skip instance definition objects
  445. //if( _attributes.isInstanceDefinitionObject ) { continue; }
  446. // TODO: handle other geometry types
  447. switch ( objectType ) {
  448. case rhino.ObjectType.Curve:
  449. var pts = curveToPoints( _geometry, 100 );
  450. var position = {};
  451. var color = {};
  452. var attributes = {};
  453. var data = {};
  454. position.itemSize = 3;
  455. position.type = 'Float32Array';
  456. position.array = [];
  457. for ( var j = 0; j < pts.length; j ++ ) {
  458. position.array.push( pts[ j ][ 0 ] );
  459. position.array.push( pts[ j ][ 1 ] );
  460. position.array.push( pts[ j ][ 2 ] );
  461. }
  462. attributes.position = position;
  463. data.attributes = attributes;
  464. geometry = { data };
  465. break;
  466. case rhino.ObjectType.Point:
  467. var pt = _geometry.location;
  468. var position = {};
  469. var color = {};
  470. var attributes = {};
  471. var data = {};
  472. position.itemSize = 3;
  473. position.type = 'Float32Array';
  474. position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];
  475. _color = _attributes.drawColor( doc );
  476. color.itemSize = 3;
  477. color.type = 'Float32Array';
  478. color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];
  479. attributes.position = position;
  480. attributes.color = color;
  481. data.attributes = attributes;
  482. geometry = { data };
  483. break;
  484. case rhino.ObjectType.PointSet:
  485. case rhino.ObjectType.Mesh:
  486. geometry = _geometry.toThreejsJSON();
  487. break;
  488. case rhino.ObjectType.Brep:
  489. var faces = _geometry.faces();
  490. geometry = [];
  491. for ( var faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {
  492. var face = faces.get( faceIndex );
  493. var mesh = face.getMesh( rhino.MeshType.Any );
  494. if ( mesh ) {
  495. geometry.push( mesh.toThreejsJSON() );
  496. mesh.delete();
  497. }
  498. face.delete();
  499. }
  500. faces.delete();
  501. break;
  502. case rhino.ObjectType.Extrusion:
  503. var mesh = _geometry.getMesh( rhino.MeshType.Any );
  504. if ( mesh ) {
  505. geometry = mesh.toThreejsJSON();
  506. mesh.delete();
  507. }
  508. break;
  509. case rhino.ObjectType.TextDot:
  510. geometry = extractProperties( _geometry );
  511. break;
  512. case rhino.ObjectType.InstanceReference:
  513. geometry = extractProperties( _geometry );
  514. geometry.xform = extractProperties( _geometry.xform );
  515. geometry.xform.array = _geometry.xform.toFloatArray( true );
  516. break;
  517. /*
  518. case rhino.ObjectType.Light:
  519. case rhino.ObjectType.Annotation:
  520. case rhino.ObjectType.Hatch:
  521. case rhino.ObjectType.SubD:
  522. case rhino.ObjectType.ClipPlane:
  523. */
  524. default:
  525. console.warn( `THREE.3DMLoader: TODO: Implement ${objectType.constructor.name}` );
  526. break;
  527. }
  528. if ( geometry ) {
  529. var attributes = extractProperties( _attributes );
  530. if ( _attributes.groupCount > 0 ) {
  531. attributes.groupIds = _attributes.getGroupList();
  532. }
  533. attributes.drawColor = _attributes.drawColor( doc );
  534. objectType = objectType.constructor.name;
  535. objectType = objectType.substring( 11, objectType.length );
  536. return { geometry, attributes, objectType };
  537. }
  538. }
  539. function extractProperties( object ) {
  540. var result = {};
  541. for ( var property in object ) {
  542. if ( typeof object[ property ] !== 'function' ) {
  543. result[ property ] = object[ property ];
  544. } else {
  545. // console.log(`${property}: ${object[property]}`);
  546. }
  547. }
  548. return result;
  549. }
  550. function curveToPoints( curve, pointLimit ) {
  551. var pointCount = pointLimit;
  552. var rc = [];
  553. var ts = [];
  554. if ( curve instanceof rhino.LineCurve ) {
  555. return [ curve.pointAtStart, curve.pointAtEnd ];
  556. }
  557. if ( curve instanceof rhino.PolylineCurve ) {
  558. pointCount = curve.pointCount;
  559. for ( var i = 0; i < pointCount; i ++ ) {
  560. rc.push( curve.point( i ) );
  561. }
  562. return rc;
  563. }
  564. if ( curve instanceof rhino.PolyCurve ) {
  565. var segmentCount = curve.segmentCount;
  566. for ( var i = 0; i < segmentCount; i ++ ) {
  567. var segment = curve.segmentCurve( i );
  568. var segmentArray = curveToPoints( segment );
  569. rc = rc.concat( segmentArray );
  570. segment.delete();
  571. }
  572. return rc;
  573. }
  574. if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {
  575. console.info( 'degree 1 curve' );
  576. }
  577. var domain = curve.domain;
  578. var divisions = pointCount - 1.0;
  579. for ( var j = 0; j < pointCount; j ++ ) {
  580. var t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );
  581. if ( t === domain[ 0 ] || t === domain[ 1 ] ) {
  582. ts.push( t );
  583. continue;
  584. }
  585. var tan = curve.tangentAt( t );
  586. var prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );
  587. // Duplicaated from THREE.Vector3
  588. // How to pass imports to worker?
  589. tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];
  590. ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];
  591. var denominator = Math.sqrt( tS * ptS );
  592. var angle;
  593. if ( denominator === 0 ) {
  594. angle = Math.PI / 2;
  595. } else {
  596. var theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;
  597. angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );
  598. }
  599. if ( angle < 0.1 ) continue;
  600. ts.push( t );
  601. }
  602. rc = ts.map( t => curve.pointAt( t ) );
  603. return rc;
  604. }
  605. };
  606. export { Rhino3dmLoader };