12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421 |
- import {
- BufferGeometryLoader,
- FileLoader,
- Loader,
- Object3D,
- MeshStandardMaterial,
- Mesh,
- Color,
- Points,
- PointsMaterial,
- Line,
- LineBasicMaterial,
- Matrix4,
- DirectionalLight,
- PointLight,
- SpotLight,
- RectAreaLight,
- Vector3,
- Sprite,
- SpriteMaterial,
- CanvasTexture,
- LinearFilter,
- ClampToEdgeWrapping,
- TextureLoader
- } from '../../../build/three.module.js';
- var Rhino3dmLoader = function ( manager ) {
- Loader.call( this, manager );
- this.libraryPath = '';
- this.libraryPending = null;
- this.libraryBinary = null;
- this.libraryConfig = {};
- this.url = '';
- this.workerLimit = 4;
- this.workerPool = [];
- this.workerNextTaskID = 1;
- this.workerSourceURL = '';
- this.workerConfig = {};
- this.materials = [];
- };
- Rhino3dmLoader.taskCache = new WeakMap();
- Rhino3dmLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
- constructor: Rhino3dmLoader,
- setLibraryPath: function ( path ) {
- this.libraryPath = path;
- return this;
- },
- setWorkerLimit: function ( workerLimit ) {
- this.workerLimit = workerLimit;
- return this;
- },
- load: function ( url, onLoad, onProgress, onError ) {
- var loader = new FileLoader( this.manager );
- loader.setPath( this.path );
- loader.setResponseType( 'arraybuffer' );
- loader.setRequestHeader( this.requestHeader );
- this.url = url;
- loader.load( url, ( buffer ) => {
- // Check for an existing task using this buffer. A transferred buffer cannot be transferred
- // again from this thread.
- if ( Rhino3dmLoader.taskCache.has( buffer ) ) {
- var cachedTask = Rhino3dmLoader.taskCache.get( buffer );
- return cachedTask.promise.then( onLoad ).catch( onError );
- }
- this.decodeObjects( buffer, url )
- .then( onLoad )
- .catch( onError );
- }, onProgress, onError );
- },
- debug: function () {
- console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
- },
- decodeObjects: function ( buffer, url ) {
- var worker;
- var taskID;
- var taskCost = buffer.byteLength;
- var objectPending = this._getWorker( taskCost )
- .then( ( _worker ) => {
- worker = _worker;
- taskID = this.workerNextTaskID ++; //hmmm
- return new Promise( ( resolve, reject ) => {
- worker._callbacks[ taskID ] = { resolve, reject };
- worker.postMessage( { type: 'decode', id: taskID, buffer }, [ buffer ] );
- //this.debug();
- } );
- } )
- .then( ( message ) => this._createGeometry( message.data ) );
- // Remove task from the task list.
- // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
- objectPending
- .catch( () => true )
- .then( () => {
- if ( worker && taskID ) {
- this._releaseTask( worker, taskID );
- //this.debug();
- }
- } );
- // Cache the task result.
- Rhino3dmLoader.taskCache.set( buffer, {
- url: url,
- promise: objectPending
- } );
- return objectPending;
- },
- parse: function ( data, onLoad, onError ) {
- this.decodeObjects( data, '' )
- .then( onLoad )
- .catch( onError );
- },
- _compareMaterials: function ( material ) {
- var mat = {};
- mat.name = material.name;
- mat.color = {};
- mat.color.r = material.color.r;
- mat.color.g = material.color.g;
- mat.color.b = material.color.b;
- mat.type = material.type;
- for ( var i = 0; i < this.materials.length; i ++ ) {
- var m = this.materials[ i ];
- var _mat = {};
- _mat.name = m.name;
- _mat.color = {};
- _mat.color.r = m.color.r;
- _mat.color.g = m.color.g;
- _mat.color.b = m.color.b;
- _mat.type = m.type;
- if ( JSON.stringify( mat ) === JSON.stringify( _mat ) ) {
- return m;
- }
- }
- this.materials.push( material );
- return material;
- },
- _createMaterial: function ( material ) {
- if ( material === undefined ) {
- return new MeshStandardMaterial( {
- color: new Color( 1, 1, 1 ),
- metalness: 0.8,
- name: 'default',
- side: 2
- } );
- }
- var _diffuseColor = material.diffuseColor;
- var diffusecolor = new Color( _diffuseColor.r / 255.0, _diffuseColor.g / 255.0, _diffuseColor.b / 255.0 );
- if ( _diffuseColor.r === 0 && _diffuseColor.g === 0 && _diffuseColor.b === 0 ) {
- diffusecolor.r = 1;
- diffusecolor.g = 1;
- diffusecolor.b = 1;
- }
- // console.log( material );
- var mat = new MeshStandardMaterial( {
- color: diffusecolor,
- name: material.name,
- side: 2,
- transparent: material.transparency > 0 ? true : false,
- opacity: 1.0 - material.transparency
- } );
- var textureLoader = new TextureLoader();
- for ( var i = 0; i < material.textures.length; i ++ ) {
- var texture = material.textures[ i ];
- if ( texture.image !== null ) {
- var map = textureLoader.load( texture.image );
- switch ( texture.type ) {
- case 'Diffuse':
- mat.map = map;
- break;
- case 'Bump':
- mat.bumpMap = map;
- break;
- case 'Transparency':
- mat.alphaMap = map;
- mat.transparent = true;
- break;
- case 'Emap':
- mat.envMap = map;
- break;
- }
- }
- }
- return mat;
- },
- _createGeometry: function ( data ) {
- // console.log(data);
- var object = new Object3D();
- var instanceDefinitionObjects = [];
- var instanceDefinitions = [];
- var instanceReferences = [];
- object.userData[ 'layers' ] = data.layers;
- object.userData[ 'groups' ] = data.groups;
- object.userData[ 'settings' ] = data.settings;
- object.userData[ 'objectType' ] = 'File3dm';
- object.userData[ 'materials' ] = null;
- object.name = this.url;
- var objects = data.objects;
- var materials = data.materials;
- for ( var i = 0; i < objects.length; i ++ ) {
- var obj = objects[ i ];
- var attributes = obj.attributes;
- switch ( obj.objectType ) {
- case 'InstanceDefinition':
- instanceDefinitions.push( obj );
- break;
- case 'InstanceReference':
- instanceReferences.push( obj );
- break;
- default:
- if ( attributes.materialIndex >= 0 ) {
- var rMaterial = materials[ attributes.materialIndex ];
- var material = this._createMaterial( rMaterial );
- material = this._compareMaterials( material );
- var _object = this._createObject( obj, material );
- } else {
- var material = this._createMaterial( );
- var _object = this._createObject( obj, material );
- }
- if ( _object === undefined ) {
- continue;
- }
- var layer = data.layers[ attributes.layerIndex ];
- _object.visible = layer ? data.layers[ attributes.layerIndex ].visible : true;
- if ( attributes.isInstanceDefinitionObject ) {
- instanceDefinitionObjects.push( _object );
- } else {
- object.add( _object );
- }
- break;
- }
- }
- for ( var i = 0; i < instanceDefinitions.length; i ++ ) {
- var iDef = instanceDefinitions[ i ];
- var objects = [];
- for ( var j = 0; j < iDef.attributes.objectIds.length; j ++ ) {
- var objId = iDef.attributes.objectIds[ j ];
- for ( var p = 0; p < instanceDefinitionObjects.length; p ++ ) {
- var idoId = instanceDefinitionObjects[ p ].userData.attributes.id;
- if ( objId === idoId ) {
- objects.push( instanceDefinitionObjects[ p ] );
- }
- }
- }
- // Currently clones geometry and does not take advantage of instancing
- for ( var j = 0; j < instanceReferences.length; j ++ ) {
- var iRef = instanceReferences[ j ];
- if ( iRef.geometry.parentIdefId === iDef.attributes.id ) {
- var iRefObject = new Object3D();
- var xf = iRef.geometry.xform.array;
- var matrix = new Matrix4();
- 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 ] );
- iRefObject.applyMatrix4( matrix );
- for ( var p = 0; p < objects.length; p ++ ) {
- iRefObject.add( objects[ p ].clone( true ) );
- }
- object.add( iRefObject );
- }
- }
- }
- object.userData[ 'materials' ] = this.materials;
- return object;
- },
- _createObject: function ( obj, mat ) {
- var loader = new BufferGeometryLoader();
- var attributes = obj.attributes;
- switch ( obj.objectType ) {
- case 'Point':
- case 'PointSet':
- var geometry = loader.parse( obj.geometry );
- var material = null;
- if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
- material = new PointsMaterial( { vertexColors: true, sizeAttenuation: false, size: 2 } );
- } else {
- var _color = attributes.drawColor;
- var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
- material = new PointsMaterial( { color: color, sizeAttenuation: false, size: 2 } );
- }
- material = this._compareMaterials( material );
- var points = new Points( geometry, material );
- points.userData[ 'attributes' ] = attributes;
- points.userData[ 'objectType' ] = obj.objectType;
- if ( attributes.name ) {
- points.name = attributes.name;
- }
- return points;
- case 'Mesh':
- case 'Extrusion':
- case 'SubD':
- case 'Brep':
- if ( obj.geometry === null ) return;
- var geometry = loader.parse( obj.geometry );
- if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
- mat.vertexColors = true;
- }
- if ( mat === null ) {
- mat = this._createMaterial();
- mat = this._compareMaterials( mat );
- }
- var mesh = new Mesh( geometry, mat );
- mesh.castShadow = attributes.castsShadows;
- mesh.receiveShadow = attributes.receivesShadows;
- mesh.userData[ 'attributes' ] = attributes;
- mesh.userData[ 'objectType' ] = obj.objectType;
- if ( attributes.name ) {
- mesh.name = attributes.name;
- }
- return mesh;
- case 'Curve':
- geometry = loader.parse( obj.geometry );
- var _color = attributes.drawColor;
- var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
- var material = new LineBasicMaterial( { color: color } );
- material = this._compareMaterials( material );
- var lines = new Line( geometry, material );
- lines.userData[ 'attributes' ] = attributes;
- lines.userData[ 'objectType' ] = obj.objectType;
- if ( attributes.name ) {
- lines.name = attributes.name;
- }
- return lines;
- case 'TextDot':
- geometry = obj.geometry;
- var ctx = document.createElement( 'canvas' ).getContext( '2d' );
- var font = `${geometry.fontHeight}px ${geometry.fontFace}`;
- ctx.font = font;
- var width = ctx.measureText( geometry.text ).width + 10;
- var height = geometry.fontHeight + 10;
- var r = window.devicePixelRatio;
- ctx.canvas.width = width * r;
- ctx.canvas.height = height * r;
- ctx.canvas.style.width = width + 'px';
- ctx.canvas.style.height = height + 'px';
- ctx.setTransform( r, 0, 0, r, 0, 0 );
- ctx.font = font;
- ctx.textBaseline = 'middle';
- ctx.textAlign = 'center';
- var color = attributes.drawColor;
- ctx.fillStyle = `rgba(${color.r},${color.g},${color.b},${color.a})`;
- ctx.fillRect( 0, 0, width, height );
- ctx.fillStyle = 'white';
- ctx.fillText( geometry.text, width / 2, height / 2 );
- var texture = new CanvasTexture( ctx.canvas );
- texture.minFilter = LinearFilter;
- texture.wrapS = ClampToEdgeWrapping;
- texture.wrapT = ClampToEdgeWrapping;
- var material = new SpriteMaterial( { map: texture, depthTest: false } );
- var sprite = new Sprite( material );
- sprite.position.set( geometry.point[ 0 ], geometry.point[ 1 ], geometry.point[ 2 ] );
- sprite.scale.set( width / 10, height / 10, 1.0 );
- sprite.userData[ 'attributes' ] = attributes;
- sprite.userData[ 'objectType' ] = obj.objectType;
- if ( attributes.name ) {
- sprite.name = attributes.name;
- }
- return sprite;
- case 'Light':
- geometry = obj.geometry;
- var light;
- if ( geometry.isDirectionalLight ) {
- light = new DirectionalLight();
- light.castShadow = attributes.castsShadows;
- light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
- light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
- light.shadow.normalBias = 0.1;
- } else if ( geometry.isPointLight ) {
- light = new PointLight();
- light.castShadow = attributes.castsShadows;
- light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
- light.shadow.normalBias = 0.1;
- } else if ( geometry.isRectangularLight ) {
- light = new RectAreaLight();
- var width = Math.abs( geometry.width[ 2 ] );
- var height = Math.abs( geometry.length[ 0 ] );
- light.position.set( geometry.location[ 0 ] - ( height / 2 ), geometry.location[ 1 ], geometry.location[ 2 ] - ( width / 2 ) );
- light.height = height;
- light.width = width;
- light.lookAt( new Vector3( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] ) );
- } else if ( geometry.isSpotLight ) {
- light = new SpotLight();
- light.castShadow = attributes.castsShadows;
- light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
- light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
- light.angle = geometry.spotAngleRadians;
- light.shadow.normalBias = 0.1;
- } else if ( geometry.isLinearLight ) {
- console.warn( 'THREE.3DMLoader: No conversion exists for linear lights.' );
- return;
- }
- if ( light ) {
- light.intensity = geometry.intensity;
- var _color = geometry.diffuse;
- var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
- light.color = color;
- light.userData[ 'attributes' ] = attributes;
- light.userData[ 'objectType' ] = obj.objectType;
- }
- return light;
- }
- },
- _initLibrary: function () {
- if ( ! this.libraryPending ) {
- // Load rhino3dm wrapper.
- var jsLoader = new FileLoader( this.manager );
- jsLoader.setPath( this.libraryPath );
- var jsContent = new Promise( ( resolve, reject ) => {
- jsLoader.load( 'rhino3dm.js', resolve, undefined, reject );
- } );
- // Load rhino3dm WASM binary.
- var binaryLoader = new FileLoader( this.manager );
- binaryLoader.setPath( this.libraryPath );
- binaryLoader.setResponseType( 'arraybuffer' );
- var binaryContent = new Promise( ( resolve, reject ) => {
- binaryLoader.load( 'rhino3dm.wasm', resolve, undefined, reject );
- } );
- this.libraryPending = Promise.all( [ jsContent, binaryContent ] )
- .then( ( [ jsContent, binaryContent ] ) => {
- //this.libraryBinary = binaryContent;
- this.libraryConfig.wasmBinary = binaryContent;
- var fn = Rhino3dmLoader.Rhino3dmWorker.toString();
- var body = [
- '/* rhino3dm.js */',
- jsContent,
- '/* worker */',
- fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
- ].join( '\n' );
- this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
- } );
- }
- return this.libraryPending;
- },
- _getWorker: function ( taskCost ) {
- return this._initLibrary().then( () => {
- if ( this.workerPool.length < this.workerLimit ) {
- var worker = new Worker( this.workerSourceURL );
- worker._callbacks = {};
- worker._taskCosts = {};
- worker._taskLoad = 0;
- worker.postMessage( {
- type: 'init',
- libraryConfig: this.libraryConfig
- } );
- worker.onmessage = function ( e ) {
- var message = e.data;
- switch ( message.type ) {
- case 'decode':
- worker._callbacks[ message.id ].resolve( message );
- break;
- case 'error':
- worker._callbacks[ message.id ].reject( message );
- break;
- default:
- console.error( 'THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"' );
- }
- };
- this.workerPool.push( worker );
- } else {
- this.workerPool.sort( function ( a, b ) {
- return a._taskLoad > b._taskLoad ? - 1 : 1;
- } );
- }
- var worker = this.workerPool[ this.workerPool.length - 1 ];
- worker._taskLoad += taskCost;
- return worker;
- } );
- },
- _releaseTask: function ( worker, taskID ) {
- worker._taskLoad -= worker._taskCosts[ taskID ];
- delete worker._callbacks[ taskID ];
- delete worker._taskCosts[ taskID ];
- },
- dispose: function () {
- for ( var i = 0; i < this.workerPool.length; ++ i ) {
- this.workerPool[ i ].terminate();
- }
- this.workerPool.length = 0;
- return this;
- }
- } );
- /* WEB WORKER */
- Rhino3dmLoader.Rhino3dmWorker = function () {
- var libraryPending;
- var libraryConfig;
- var rhino;
- onmessage = function ( e ) {
- var message = e.data;
- switch ( message.type ) {
- case 'init':
- libraryConfig = message.libraryConfig;
- var wasmBinary = libraryConfig.wasmBinary;
- var RhinoModule;
- libraryPending = new Promise( function ( resolve ) {
- /* Like Basis Loader */
- RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };
- rhino3dm( RhinoModule ); // eslint-disable-line no-undef
- } ).then( () => {
- rhino = RhinoModule;
- } );
- break;
- case 'decode':
- var buffer = message.buffer;
- libraryPending.then( () => {
- var data = decodeObjects( rhino, buffer );
- self.postMessage( { type: 'decode', id: message.id, data } );
- } );
- break;
- }
- };
- function decodeObjects( rhino, buffer ) {
- var arr = new Uint8Array( buffer );
- var doc = rhino.File3dm.fromByteArray( arr );
- var objects = [];
- var materials = [];
- var layers = [];
- var views = [];
- var namedViews = [];
- var groups = [];
- //Handle objects
- var objs = doc.objects();
- var cnt = objs.count;
- for ( var i = 0; i < cnt; i ++ ) {
- var _object = objs.get( i );
- var object = extractObjectData( _object, doc );
- _object.delete();
- if ( object ) {
- objects.push( object );
- }
- }
- // Handle instance definitions
- // console.log( `Instance Definitions Count: ${doc.instanceDefinitions().count()}` );
- for ( var i = 0; i < doc.instanceDefinitions().count(); i ++ ) {
- var idef = doc.instanceDefinitions().get( i );
- var idefAttributes = extractProperties( idef );
- idefAttributes.objectIds = idef.getObjectIds();
- objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );
- }
- // Handle materials
- var textureTypes = [
- // rhino.TextureType.Bitmap,
- rhino.TextureType.Diffuse,
- rhino.TextureType.Bump,
- rhino.TextureType.Transparency,
- rhino.TextureType.Opacity,
- rhino.TextureType.Emap
- ];
- var pbrTextureTypes = [
- rhino.TextureType.PBR_BaseColor,
- rhino.TextureType.PBR_Subsurface,
- rhino.TextureType.PBR_SubsurfaceScattering,
- rhino.TextureType.PBR_SubsurfaceScatteringRadius,
- rhino.TextureType.PBR_Metallic,
- rhino.TextureType.PBR_Specular,
- rhino.TextureType.PBR_SpecularTint,
- rhino.TextureType.PBR_Roughness,
- rhino.TextureType.PBR_Anisotropic,
- rhino.TextureType.PBR_Anisotropic_Rotation,
- rhino.TextureType.PBR_Sheen,
- rhino.TextureType.PBR_SheenTint,
- rhino.TextureType.PBR_Clearcoat,
- rhino.TextureType.PBR_ClearcoatBump,
- rhino.TextureType.PBR_ClearcoatRoughness,
- rhino.TextureType.PBR_OpacityIor,
- rhino.TextureType.PBR_OpacityRoughness,
- rhino.TextureType.PBR_Emission,
- rhino.TextureType.PBR_AmbientOcclusion,
- rhino.TextureType.PBR_Displacement
- ];
- for ( var i = 0; i < doc.materials().count(); i ++ ) {
- var _material = doc.materials().get( i );
- var _pbrMaterial = _material.physicallyBased();
- var material = extractProperties( _material );
- var textures = [];
- for ( var j = 0; j < textureTypes.length; j ++ ) {
- var _texture = _material.getTexture( textureTypes[ j ] );
- if ( _texture ) {
- var textureType = textureTypes[ j ].constructor.name;
- textureType = textureType.substring( 12, textureType.length );
- var texture = { type: textureType };
- var image = doc.getEmbeddedFileAsBase64( _texture.fileName );
- if ( image ) {
- texture.image = 'data:image/png;base64,' + image;
- } else {
- console.warn( `THREE.3DMLoader: Image for ${textureType} texture not embedded in file.` );
- texture.image = null;
- }
- textures.push( texture );
- _texture.delete();
- }
- }
- material.textures = textures;
- if ( _pbrMaterial.supported ) {
- console.log( 'pbr true' );
- for ( var j = 0; j < pbrTextureTypes.length; j ++ ) {
- var _texture = _material.getTexture( textureTypes[ j ] );
- if ( _texture ) {
- var image = doc.getEmbeddedFileAsBase64( _texture.fileName );
- var textureType = textureTypes[ j ].constructor.name;
- textureType = textureType.substring( 12, textureType.length );
- var texture = { type: textureType, image: 'data:image/png;base64,' + image };
- textures.push( texture );
- _texture.delete();
- }
- }
- var pbMaterialProperties = extractProperties( _material.physicallyBased() );
- material = Object.assign( pbMaterialProperties, material );
- }
- materials.push( material );
- _material.delete();
- _pbrMaterial.delete();
- }
- // Handle layers
- for ( var i = 0; i < doc.layers().count(); i ++ ) {
- var _layer = doc.layers().get( i );
- var layer = extractProperties( _layer );
- layers.push( layer );
- _layer.delete();
- }
- // Handle views
- for ( var i = 0; i < doc.views().count(); i ++ ) {
- var _view = doc.views().get( i );
- var view = extractProperties( _view );
- views.push( view );
- _view.delete();
- }
- // Handle named views
- for ( var i = 0; i < doc.namedViews().count(); i ++ ) {
- var _namedView = doc.namedViews().get( i );
- var namedView = extractProperties( _namedView );
- namedViews.push( namedView );
- _namedView.delete();
- }
- // Handle groups
- for ( var i = 0; i < doc.groups().count(); i ++ ) {
- var _group = doc.groups().get( i );
- var group = extractProperties( _group );
- groups.push( group );
- _group.delete();
- }
- // Handle settings
- var settings = extractProperties( doc.settings() );
- //TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.
- // Handle dimstyles
- // console.log( `Dimstyle Count: ${doc.dimstyles().count()}` );
- // Handle bitmaps
- // console.log( `Bitmap Count: ${doc.bitmaps().count()}` );
- // Handle strings -- this seems to be broken at the moment in rhino3dm
- // console.log( `Document Strings Count: ${doc.strings().count()}` );
- /*
- for( var i = 0; i < doc.strings().count(); i++ ){
- var _string= doc.strings().get( i );
- console.log(_string);
- var string = extractProperties( _group );
- strings.push( string );
- _string.delete();
- }
- */
- doc.delete();
- return { objects, materials, layers, views, namedViews, groups, settings };
- }
- function extractObjectData( object, doc ) {
- var _geometry = object.geometry();
- var _attributes = object.attributes();
- var objectType = _geometry.objectType;
- var geometry = null;
- var attributes = null;
- // skip instance definition objects
- //if( _attributes.isInstanceDefinitionObject ) { continue; }
- // TODO: handle other geometry types
- switch ( objectType ) {
- case rhino.ObjectType.Curve:
- var pts = curveToPoints( _geometry, 100 );
- var position = {};
- var attributes = {};
- var data = {};
- position.itemSize = 3;
- position.type = 'Float32Array';
- position.array = [];
- for ( var j = 0; j < pts.length; j ++ ) {
- position.array.push( pts[ j ][ 0 ] );
- position.array.push( pts[ j ][ 1 ] );
- position.array.push( pts[ j ][ 2 ] );
- }
- attributes.position = position;
- data.attributes = attributes;
- geometry = { data };
- break;
- case rhino.ObjectType.Point:
- var pt = _geometry.location;
- var position = {};
- var color = {};
- var attributes = {};
- var data = {};
- position.itemSize = 3;
- position.type = 'Float32Array';
- position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];
- var _color = _attributes.drawColor( doc );
- color.itemSize = 3;
- color.type = 'Float32Array';
- color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];
- attributes.position = position;
- attributes.color = color;
- data.attributes = attributes;
- geometry = { data };
- break;
- case rhino.ObjectType.PointSet:
- case rhino.ObjectType.Mesh:
- geometry = _geometry.toThreejsJSON();
- break;
- case rhino.ObjectType.Brep:
- var faces = _geometry.faces();
- var mesh = new rhino.Mesh();
- for ( var faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {
- var face = faces.get( faceIndex );
- var _mesh = face.getMesh( rhino.MeshType.Any );
- if ( _mesh ) {
- mesh.append( _mesh );
- _mesh.delete();
- }
- face.delete();
- }
- if ( mesh.faces().count > 0 ) {
- mesh.compact();
- geometry = mesh.toThreejsJSON();
- faces.delete();
- }
- mesh.delete();
- break;
- case rhino.ObjectType.Extrusion:
- var mesh = _geometry.getMesh( rhino.MeshType.Any );
- if ( mesh ) {
- geometry = mesh.toThreejsJSON();
- mesh.delete();
- }
- break;
- case rhino.ObjectType.TextDot:
- geometry = extractProperties( _geometry );
- break;
- case rhino.ObjectType.Light:
- geometry = extractProperties( _geometry );
- break;
- case rhino.ObjectType.InstanceReference:
- geometry = extractProperties( _geometry );
- geometry.xform = extractProperties( _geometry.xform );
- geometry.xform.array = _geometry.xform.toFloatArray( true );
- break;
- case rhino.ObjectType.SubD:
- // TODO: precalculate resulting vertices and faces and warn on excessive results
- _geometry.subdivide( 3 );
- var mesh = rhino.Mesh.createFromSubDControlNet( _geometry );
- if ( mesh ) {
- geometry = mesh.toThreejsJSON();
- mesh.delete();
- }
- break;
- /*
- case rhino.ObjectType.Annotation:
- case rhino.ObjectType.Hatch:
- case rhino.ObjectType.ClipPlane:
- */
- default:
- console.warn( `THREE.3DMLoader: TODO: Implement ${objectType.constructor.name}` );
- break;
- }
- if ( geometry ) {
- var attributes = extractProperties( _attributes );
- attributes.geometry = extractProperties( _geometry );
- if ( _attributes.groupCount > 0 ) {
- attributes.groupIds = _attributes.getGroupList();
- }
- if ( _attributes.userStringCount > 0 ) {
- attributes.userStrings = _attributes.getUserStrings();
- }
- if ( _geometry.userStringCount > 0 ) {
- attributes.geometry.userStrings = _geometry.getUserStrings();
- }
- attributes.drawColor = _attributes.drawColor( doc );
- objectType = objectType.constructor.name;
- objectType = objectType.substring( 11, objectType.length );
- return { geometry, attributes, objectType };
- } else {
- console.warn( `THREE.3DMLoader: ${objectType.constructor.name} has no associated mesh geometry.` );
- }
- }
- function extractProperties( object ) {
- var result = {};
- for ( var property in object ) {
- var value = object[ property ];
- if ( typeof value !== 'function' ) {
- if ( typeof value === 'object' && value !== null && value.hasOwnProperty( 'constructor' ) ) {
- result[ property ] = { name: value.constructor.name, value: value.value };
- } else {
- result[ property ] = value;
- }
- } else {
- // these are functions that could be called to extract more data.
- //console.log( `${property}: ${object[ property ].constructor.name}` );
- }
- }
- return result;
- }
- function curveToPoints( curve, pointLimit ) {
- var pointCount = pointLimit;
- var rc = [];
- var ts = [];
- if ( curve instanceof rhino.LineCurve ) {
- return [ curve.pointAtStart, curve.pointAtEnd ];
- }
- if ( curve instanceof rhino.PolylineCurve ) {
- pointCount = curve.pointCount;
- for ( var i = 0; i < pointCount; i ++ ) {
- rc.push( curve.point( i ) );
- }
- return rc;
- }
- if ( curve instanceof rhino.PolyCurve ) {
- var segmentCount = curve.segmentCount;
- for ( var i = 0; i < segmentCount; i ++ ) {
- var segment = curve.segmentCurve( i );
- var segmentArray = curveToPoints( segment, pointCount );
- rc = rc.concat( segmentArray );
- segment.delete();
- }
- return rc;
- }
- if ( curve instanceof rhino.ArcCurve ) {
- pointCount = Math.floor( curve.angleDegrees / 5 );
- pointCount = pointCount < 2 ? 2 : pointCount;
- // alternative to this hardcoded version: https://stackoverflow.com/a/18499923/2179399
- }
- if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {
- const pLine = curve.tryGetPolyline();
- for ( var i = 0; i < pLine.count; i ++ ) {
- rc.push( pLine.get( i ) );
- }
- pLine.delete();
- return rc;
- }
- var domain = curve.domain;
- var divisions = pointCount - 1.0;
- for ( var j = 0; j < pointCount; j ++ ) {
- var t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );
- if ( t === domain[ 0 ] || t === domain[ 1 ] ) {
- ts.push( t );
- continue;
- }
- var tan = curve.tangentAt( t );
- var prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );
- // Duplicated from THREE.Vector3
- // How to pass imports to worker?
- var tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];
- var ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];
- var denominator = Math.sqrt( tS * ptS );
- var angle;
- if ( denominator === 0 ) {
- angle = Math.PI / 2;
- } else {
- var theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;
- angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );
- }
- if ( angle < 0.1 ) continue;
- ts.push( t );
- }
- rc = ts.map( t => curve.pointAt( t ) );
- return rc;
- }
- };
- export { Rhino3dmLoader };
|