From d1a513329d771d5667e39af7473a3eacf321ce99 Mon Sep 17 00:00:00 2001 From: Michael Herzog Date: Thu, 8 Apr 2021 20:06:30 +0200 Subject: [PATCH] Examples: Convert loaders to ES6 Part I. (#21612) --- examples/js/loaders/3MFLoader.js | 592 +-- examples/js/loaders/AMFLoader.js | 160 +- examples/js/loaders/BVHLoader.js | 96 +- examples/js/loaders/BasisTextureLoader.js | 237 +- examples/js/loaders/ColladaLoader.js | 1008 +++-- examples/js/loaders/DDSLoader.js | 165 +- examples/js/loaders/KMZLoader.js | 46 +- examples/js/loaders/MD2Loader.js | 281 +- examples/js/loaders/MDDLoader.js | 54 +- examples/js/loaders/PCDLoader.js | 108 +- examples/js/loaders/PDBLoader.js | 121 +- examples/js/loaders/PLYLoader.js | 130 +- examples/js/loaders/PVRLoader.js | 81 +- examples/js/loaders/RGBELoader.js | 139 +- examples/js/loaders/STLLoader.js | 141 +- examples/js/loaders/TDSLoader.js | 642 ++-- examples/js/loaders/TGALoader.js | 69 +- examples/js/loaders/TTFLoader.js | 58 +- examples/js/loaders/VRMLLoader.js | 3899 ++++++++++---------- examples/js/loaders/VRMLoader.js | 68 +- examples/jsm/loaders/3MFLoader.js | 581 ++- examples/jsm/loaders/AMFLoader.js | 158 +- examples/jsm/loaders/BVHLoader.js | 94 +- examples/jsm/loaders/BasisTextureLoader.js | 223 +- examples/jsm/loaders/ColladaLoader.js | 1012 +++-- examples/jsm/loaders/DDSLoader.js | 176 +- examples/jsm/loaders/KMZLoader.js | 44 +- examples/jsm/loaders/MD2Loader.js | 524 ++- examples/jsm/loaders/MDDLoader.js | 52 +- examples/jsm/loaders/PCDLoader.js | 107 +- examples/jsm/loaders/PDBLoader.js | 115 +- examples/jsm/loaders/PLYLoader.js | 127 +- examples/jsm/loaders/PVRLoader.js | 81 +- examples/jsm/loaders/RGBELoader.js | 127 +- examples/jsm/loaders/STLLoader.js | 139 +- examples/jsm/loaders/TDSLoader.js | 707 ++-- examples/jsm/loaders/TGALoader.js | 71 +- examples/jsm/loaders/TTFLoader.js | 57 +- examples/jsm/loaders/VRMLLoader.js | 3872 ++++++++++--------- examples/jsm/loaders/VRMLoader.js | 68 +- 40 files changed, 8209 insertions(+), 8221 deletions(-) diff --git a/examples/js/loaders/3MFLoader.js b/examples/js/loaders/3MFLoader.js index a4fffad080bddc..c5ddcc33531f89 100644 --- a/examples/js/loaders/3MFLoader.js +++ b/examples/js/loaders/3MFLoader.js @@ -18,19 +18,19 @@ * - Metallic Display Properties (PBR) */ - var ThreeMFLoader = function ( manager ) { + class ThreeMFLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); - this.availableExtensions = []; + constructor( manager ) { - }; + super( manager ); + this.availableExtensions = []; - ThreeMFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: ThreeMFLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new THREE.FileLoader( scope.manager ); + const scope = this; + const loader = new THREE.FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( scope.requestHeader ); @@ -59,28 +59,28 @@ }, onProgress, onError ); - }, - parse: function ( data ) { + } + + parse( data ) { - var scope = this; - var textureLoader = new THREE.TextureLoader( this.manager ); + const scope = this; + const textureLoader = new THREE.TextureLoader( this.manager ); function loadDocument( data ) { - var zip = null; - var file = null; - var relsName; - var modelRelsName; - var modelPartNames = []; - var printTicketPartNames = []; - var texturesPartNames = []; - var otherPartNames = []; - var rels; - var modelRels; - var modelParts = {}; - var printTicketParts = {}; - var texturesParts = {}; - var otherParts = {}; + let zip = null; + let file = null; + let relsName; + let modelRelsName; + const modelPartNames = []; + const printTicketPartNames = []; + const texturesPartNames = []; + const otherPartNames = []; + let modelRels; + const modelParts = {}; + const printTicketParts = {}; + const texturesParts = {}; + const otherParts = {}; try { @@ -128,25 +128,25 @@ } // - var relsView = zip[ relsName ]; - var relsFileText = THREE.LoaderUtils.decodeText( relsView ); - rels = parseRelsXml( relsFileText ); // + const relsView = zip[ relsName ]; + const relsFileText = THREE.LoaderUtils.decodeText( relsView ); + const rels = parseRelsXml( relsFileText ); // if ( modelRelsName ) { - var relsView = zip[ modelRelsName ]; - var relsFileText = THREE.LoaderUtils.decodeText( relsView ); + const relsView = zip[ modelRelsName ]; + const relsFileText = THREE.LoaderUtils.decodeText( relsView ); modelRels = parseRelsXml( relsFileText ); } // - for ( var i = 0; i < modelPartNames.length; i ++ ) { + for ( let i = 0; i < modelPartNames.length; i ++ ) { - var modelPart = modelPartNames[ i ]; - var view = zip[ modelPart ]; - var fileText = THREE.LoaderUtils.decodeText( view ); - var xmlData = new DOMParser().parseFromString( fileText, 'application/xml' ); + const modelPart = modelPartNames[ i ]; + const view = zip[ modelPart ]; + const fileText = THREE.LoaderUtils.decodeText( view ); + const xmlData = new DOMParser().parseFromString( fileText, 'application/xml' ); if ( xmlData.documentElement.nodeName.toLowerCase() !== 'model' ) { @@ -154,12 +154,12 @@ } - var modelNode = xmlData.querySelector( 'model' ); - var extensions = {}; + const modelNode = xmlData.querySelector( 'model' ); + const extensions = {}; - for ( var i = 0; i < modelNode.attributes.length; i ++ ) { + for ( let i = 0; i < modelNode.attributes.length; i ++ ) { - var attr = modelNode.attributes[ i ]; + const attr = modelNode.attributes[ i ]; if ( attr.name.match( /^xmlns:(.+)$/ ) ) { @@ -169,7 +169,7 @@ } - var modelData = parseModelNode( modelNode ); + const modelData = parseModelNode( modelNode ); modelData[ 'xml' ] = modelNode; if ( 0 < Object.keys( extensions ).length ) { @@ -183,9 +183,9 @@ } // - for ( var i = 0; i < texturesPartNames.length; i ++ ) { + for ( let i = 0; i < texturesPartNames.length; i ++ ) { - var texturesPartName = texturesPartNames[ i ]; + const texturesPartName = texturesPartNames[ i ]; texturesParts[ texturesPartName ] = zip[ texturesPartName ].buffer; } @@ -203,14 +203,14 @@ function parseRelsXml( relsFileText ) { - var relationships = []; - var relsXmlData = new DOMParser().parseFromString( relsFileText, 'application/xml' ); - var relsNodes = relsXmlData.querySelectorAll( 'Relationship' ); + const relationships = []; + const relsXmlData = new DOMParser().parseFromString( relsFileText, 'application/xml' ); + const relsNodes = relsXmlData.querySelectorAll( 'Relationship' ); - for ( var i = 0; i < relsNodes.length; i ++ ) { + for ( let i = 0; i < relsNodes.length; i ++ ) { - var relsNode = relsNodes[ i ]; - var relationship = { + const relsNode = relsNodes[ i ]; + const relationship = { target: relsNode.getAttribute( 'Target' ), //required id: relsNode.getAttribute( 'Id' ), @@ -228,13 +228,13 @@ function parseMetadataNodes( metadataNodes ) { - var metadataData = {}; + const metadataData = {}; - for ( var i = 0; i < metadataNodes.length; i ++ ) { + for ( let i = 0; i < metadataNodes.length; i ++ ) { - var metadataNode = metadataNodes[ i ]; - var name = metadataNode.getAttribute( 'name' ); - var validNames = [ 'Title', 'Designer', 'Description', 'Copyright', 'LicenseTerms', 'Rating', 'CreationDate', 'ModificationDate' ]; + const metadataNode = metadataNodes[ i ]; + const name = metadataNode.getAttribute( 'name' ); + const validNames = [ 'Title', 'Designer', 'Description', 'Copyright', 'LicenseTerms', 'Rating', 'CreationDate', 'ModificationDate' ]; if ( 0 <= validNames.indexOf( name ) ) { @@ -250,17 +250,17 @@ function parseBasematerialsNode( basematerialsNode ) { - var basematerialsData = { + const basematerialsData = { id: basematerialsNode.getAttribute( 'id' ), // required basematerials: [] }; - var basematerialNodes = basematerialsNode.querySelectorAll( 'base' ); + const basematerialNodes = basematerialsNode.querySelectorAll( 'base' ); - for ( var i = 0; i < basematerialNodes.length; i ++ ) { + for ( let i = 0; i < basematerialNodes.length; i ++ ) { - var basematerialNode = basematerialNodes[ i ]; - var basematerialData = parseBasematerialNode( basematerialNode ); + const basematerialNode = basematerialNodes[ i ]; + const basematerialData = parseBasematerialNode( basematerialNode ); basematerialData.index = i; // the order and count of the material nodes form an implicit 0-based index basematerialsData.basematerials.push( basematerialData ); @@ -273,7 +273,7 @@ function parseTexture2DNode( texture2DNode ) { - var texture2dData = { + const texture2dData = { id: texture2DNode.getAttribute( 'id' ), // required path: texture2DNode.getAttribute( 'path' ), @@ -290,21 +290,21 @@ function parseTextures2DGroupNode( texture2DGroupNode ) { - var texture2DGroupData = { + const texture2DGroupData = { id: texture2DGroupNode.getAttribute( 'id' ), // required texid: texture2DGroupNode.getAttribute( 'texid' ), // required displaypropertiesid: texture2DGroupNode.getAttribute( 'displaypropertiesid' ) }; - var tex2coordNodes = texture2DGroupNode.querySelectorAll( 'tex2coord' ); - var uvs = []; + const tex2coordNodes = texture2DGroupNode.querySelectorAll( 'tex2coord' ); + const uvs = []; - for ( var i = 0; i < tex2coordNodes.length; i ++ ) { + for ( let i = 0; i < tex2coordNodes.length; i ++ ) { - var tex2coordNode = tex2coordNodes[ i ]; - var u = tex2coordNode.getAttribute( 'u' ); - var v = tex2coordNode.getAttribute( 'v' ); + const tex2coordNode = tex2coordNodes[ i ]; + const u = tex2coordNode.getAttribute( 'u' ); + const v = tex2coordNode.getAttribute( 'v' ); uvs.push( parseFloat( u ), parseFloat( v ) ); } @@ -316,19 +316,19 @@ function parseColorGroupNode( colorGroupNode ) { - var colorGroupData = { + const colorGroupData = { id: colorGroupNode.getAttribute( 'id' ), // required displaypropertiesid: colorGroupNode.getAttribute( 'displaypropertiesid' ) }; - var colorNodes = colorGroupNode.querySelectorAll( 'color' ); - var colors = []; - var colorObject = new THREE.Color(); + const colorNodes = colorGroupNode.querySelectorAll( 'color' ); + const colors = []; + const colorObject = new THREE.Color(); - for ( var i = 0; i < colorNodes.length; i ++ ) { + for ( let i = 0; i < colorNodes.length; i ++ ) { - var colorNode = colorNodes[ i ]; - var color = colorNode.getAttribute( 'color' ); + const colorNode = colorNodes[ i ]; + const color = colorNode.getAttribute( 'color' ); colorObject.setStyle( color.substring( 0, 7 ) ); colorObject.convertSRGBToLinear(); // color is in sRGB @@ -343,16 +343,16 @@ function parseMetallicDisplaypropertiesNode( metallicDisplaypropetiesNode ) { - var metallicDisplaypropertiesData = { + const metallicDisplaypropertiesData = { id: metallicDisplaypropetiesNode.getAttribute( 'id' ) // required }; - var metallicNodes = metallicDisplaypropetiesNode.querySelectorAll( 'pbmetallic' ); - var metallicData = []; + const metallicNodes = metallicDisplaypropetiesNode.querySelectorAll( 'pbmetallic' ); + const metallicData = []; - for ( var i = 0; i < metallicNodes.length; i ++ ) { + for ( let i = 0; i < metallicNodes.length; i ++ ) { - var metallicNode = metallicNodes[ i ]; + const metallicNode = metallicNodes[ i ]; metallicData.push( { name: metallicNode.getAttribute( 'name' ), // required @@ -371,7 +371,7 @@ function parseBasematerialNode( basematerialNode ) { - var basematerialData = {}; + const basematerialData = {}; basematerialData[ 'name' ] = basematerialNode.getAttribute( 'name' ); // required basematerialData[ 'displaycolor' ] = basematerialNode.getAttribute( 'displaycolor' ); // required @@ -383,36 +383,36 @@ function parseMeshNode( meshNode ) { - var meshData = {}; - var vertices = []; - var vertexNodes = meshNode.querySelectorAll( 'vertices vertex' ); + const meshData = {}; + const vertices = []; + const vertexNodes = meshNode.querySelectorAll( 'vertices vertex' ); - for ( var i = 0; i < vertexNodes.length; i ++ ) { + for ( let i = 0; i < vertexNodes.length; i ++ ) { - var vertexNode = vertexNodes[ i ]; - var x = vertexNode.getAttribute( 'x' ); - var y = vertexNode.getAttribute( 'y' ); - var z = vertexNode.getAttribute( 'z' ); + const vertexNode = vertexNodes[ i ]; + const x = vertexNode.getAttribute( 'x' ); + const y = vertexNode.getAttribute( 'y' ); + const z = vertexNode.getAttribute( 'z' ); vertices.push( parseFloat( x ), parseFloat( y ), parseFloat( z ) ); } meshData[ 'vertices' ] = new Float32Array( vertices ); - var triangleProperties = []; - var triangles = []; - var triangleNodes = meshNode.querySelectorAll( 'triangles triangle' ); - - for ( var i = 0; i < triangleNodes.length; i ++ ) { - - var triangleNode = triangleNodes[ i ]; - var v1 = triangleNode.getAttribute( 'v1' ); - var v2 = triangleNode.getAttribute( 'v2' ); - var v3 = triangleNode.getAttribute( 'v3' ); - var p1 = triangleNode.getAttribute( 'p1' ); - var p2 = triangleNode.getAttribute( 'p2' ); - var p3 = triangleNode.getAttribute( 'p3' ); - var pid = triangleNode.getAttribute( 'pid' ); - var triangleProperty = {}; + const triangleProperties = []; + const triangles = []; + const triangleNodes = meshNode.querySelectorAll( 'triangles triangle' ); + + for ( let i = 0; i < triangleNodes.length; i ++ ) { + + const triangleNode = triangleNodes[ i ]; + const v1 = triangleNode.getAttribute( 'v1' ); + const v2 = triangleNode.getAttribute( 'v2' ); + const v3 = triangleNode.getAttribute( 'v3' ); + const p1 = triangleNode.getAttribute( 'p1' ); + const p2 = triangleNode.getAttribute( 'p2' ); + const p3 = triangleNode.getAttribute( 'p3' ); + const pid = triangleNode.getAttribute( 'pid' ); + const triangleProperty = {}; triangleProperty[ 'v1' ] = parseInt( v1, 10 ); triangleProperty[ 'v2' ] = parseInt( v2, 10 ); triangleProperty[ 'v3' ] = parseInt( v3, 10 ); @@ -458,13 +458,13 @@ function parseComponentsNode( componentsNode ) { - var components = []; - var componentNodes = componentsNode.querySelectorAll( 'component' ); + const components = []; + const componentNodes = componentsNode.querySelectorAll( 'component' ); - for ( var i = 0; i < componentNodes.length; i ++ ) { + for ( let i = 0; i < componentNodes.length; i ++ ) { - var componentNode = componentNodes[ i ]; - var componentData = parseComponentNode( componentNode ); + const componentNode = componentNodes[ i ]; + const componentData = parseComponentNode( componentNode ); components.push( componentData ); } @@ -475,10 +475,10 @@ function parseComponentNode( componentNode ) { - var componentData = {}; + const componentData = {}; componentData[ 'objectId' ] = componentNode.getAttribute( 'objectid' ); // required - var transform = componentNode.getAttribute( 'transform' ); + const transform = componentNode.getAttribute( 'transform' ); if ( transform ) { @@ -492,13 +492,13 @@ function parseTransform( transform ) { - var t = []; + const t = []; transform.split( ' ' ).forEach( function ( s ) { t.push( parseFloat( s ) ); } ); - var matrix = new THREE.Matrix4(); + const matrix = new THREE.Matrix4(); matrix.set( t[ 0 ], t[ 3 ], t[ 6 ], t[ 9 ], t[ 1 ], t[ 4 ], t[ 7 ], t[ 10 ], t[ 2 ], t[ 5 ], t[ 8 ], t[ 11 ], 0.0, 0.0, 0.0, 1.0 ); return matrix; @@ -506,10 +506,10 @@ function parseObjectNode( objectNode ) { - var objectData = { + const objectData = { type: objectNode.getAttribute( 'type' ) }; - var id = objectNode.getAttribute( 'id' ); + const id = objectNode.getAttribute( 'id' ); if ( id ) { @@ -517,7 +517,7 @@ } - var pid = objectNode.getAttribute( 'pid' ); + const pid = objectNode.getAttribute( 'pid' ); if ( pid ) { @@ -525,7 +525,7 @@ } - var pindex = objectNode.getAttribute( 'pindex' ); + const pindex = objectNode.getAttribute( 'pindex' ); if ( pindex ) { @@ -533,7 +533,7 @@ } - var thumbnail = objectNode.getAttribute( 'thumbnail' ); + const thumbnail = objectNode.getAttribute( 'thumbnail' ); if ( thumbnail ) { @@ -541,7 +541,7 @@ } - var partnumber = objectNode.getAttribute( 'partnumber' ); + const partnumber = objectNode.getAttribute( 'partnumber' ); if ( partnumber ) { @@ -549,7 +549,7 @@ } - var name = objectNode.getAttribute( 'name' ); + const name = objectNode.getAttribute( 'name' ); if ( name ) { @@ -557,7 +557,7 @@ } - var meshNode = objectNode.querySelector( 'mesh' ); + const meshNode = objectNode.querySelector( 'mesh' ); if ( meshNode ) { @@ -565,7 +565,7 @@ } - var componentsNode = objectNode.querySelector( 'components' ); + const componentsNode = objectNode.querySelector( 'components' ); if ( componentsNode ) { @@ -579,74 +579,74 @@ function parseResourcesNode( resourcesNode ) { - var resourcesData = {}; + const resourcesData = {}; resourcesData[ 'basematerials' ] = {}; - var basematerialsNodes = resourcesNode.querySelectorAll( 'basematerials' ); + const basematerialsNodes = resourcesNode.querySelectorAll( 'basematerials' ); - for ( var i = 0; i < basematerialsNodes.length; i ++ ) { + for ( let i = 0; i < basematerialsNodes.length; i ++ ) { - var basematerialsNode = basematerialsNodes[ i ]; - var basematerialsData = parseBasematerialsNode( basematerialsNode ); + const basematerialsNode = basematerialsNodes[ i ]; + const basematerialsData = parseBasematerialsNode( basematerialsNode ); resourcesData[ 'basematerials' ][ basematerialsData[ 'id' ] ] = basematerialsData; } // resourcesData[ 'texture2d' ] = {}; - var textures2DNodes = resourcesNode.querySelectorAll( 'texture2d' ); + const textures2DNodes = resourcesNode.querySelectorAll( 'texture2d' ); - for ( var i = 0; i < textures2DNodes.length; i ++ ) { + for ( let i = 0; i < textures2DNodes.length; i ++ ) { - var textures2DNode = textures2DNodes[ i ]; - var texture2DData = parseTexture2DNode( textures2DNode ); + const textures2DNode = textures2DNodes[ i ]; + const texture2DData = parseTexture2DNode( textures2DNode ); resourcesData[ 'texture2d' ][ texture2DData[ 'id' ] ] = texture2DData; } // resourcesData[ 'colorgroup' ] = {}; - var colorGroupNodes = resourcesNode.querySelectorAll( 'colorgroup' ); + const colorGroupNodes = resourcesNode.querySelectorAll( 'colorgroup' ); - for ( var i = 0; i < colorGroupNodes.length; i ++ ) { + for ( let i = 0; i < colorGroupNodes.length; i ++ ) { - var colorGroupNode = colorGroupNodes[ i ]; - var colorGroupData = parseColorGroupNode( colorGroupNode ); + const colorGroupNode = colorGroupNodes[ i ]; + const colorGroupData = parseColorGroupNode( colorGroupNode ); resourcesData[ 'colorgroup' ][ colorGroupData[ 'id' ] ] = colorGroupData; } // resourcesData[ 'pbmetallicdisplayproperties' ] = {}; - var pbmetallicdisplaypropertiesNodes = resourcesNode.querySelectorAll( 'pbmetallicdisplayproperties' ); + const pbmetallicdisplaypropertiesNodes = resourcesNode.querySelectorAll( 'pbmetallicdisplayproperties' ); - for ( var i = 0; i < pbmetallicdisplaypropertiesNodes.length; i ++ ) { + for ( let i = 0; i < pbmetallicdisplaypropertiesNodes.length; i ++ ) { - var pbmetallicdisplaypropertiesNode = pbmetallicdisplaypropertiesNodes[ i ]; - var pbmetallicdisplaypropertiesData = parseMetallicDisplaypropertiesNode( pbmetallicdisplaypropertiesNode ); + const pbmetallicdisplaypropertiesNode = pbmetallicdisplaypropertiesNodes[ i ]; + const pbmetallicdisplaypropertiesData = parseMetallicDisplaypropertiesNode( pbmetallicdisplaypropertiesNode ); resourcesData[ 'pbmetallicdisplayproperties' ][ pbmetallicdisplaypropertiesData[ 'id' ] ] = pbmetallicdisplaypropertiesData; } // resourcesData[ 'texture2dgroup' ] = {}; - var textures2DGroupNodes = resourcesNode.querySelectorAll( 'texture2dgroup' ); + const textures2DGroupNodes = resourcesNode.querySelectorAll( 'texture2dgroup' ); - for ( var i = 0; i < textures2DGroupNodes.length; i ++ ) { + for ( let i = 0; i < textures2DGroupNodes.length; i ++ ) { - var textures2DGroupNode = textures2DGroupNodes[ i ]; - var textures2DGroupData = parseTextures2DGroupNode( textures2DGroupNode ); + const textures2DGroupNode = textures2DGroupNodes[ i ]; + const textures2DGroupData = parseTextures2DGroupNode( textures2DGroupNode ); resourcesData[ 'texture2dgroup' ][ textures2DGroupData[ 'id' ] ] = textures2DGroupData; } // resourcesData[ 'object' ] = {}; - var objectNodes = resourcesNode.querySelectorAll( 'object' ); + const objectNodes = resourcesNode.querySelectorAll( 'object' ); - for ( var i = 0; i < objectNodes.length; i ++ ) { + for ( let i = 0; i < objectNodes.length; i ++ ) { - var objectNode = objectNodes[ i ]; - var objectData = parseObjectNode( objectNode ); + const objectNode = objectNodes[ i ]; + const objectData = parseObjectNode( objectNode ); resourcesData[ 'object' ][ objectData[ 'id' ] ] = objectData; } @@ -657,16 +657,16 @@ function parseBuildNode( buildNode ) { - var buildData = []; - var itemNodes = buildNode.querySelectorAll( 'item' ); + const buildData = []; + const itemNodes = buildNode.querySelectorAll( 'item' ); - for ( var i = 0; i < itemNodes.length; i ++ ) { + for ( let i = 0; i < itemNodes.length; i ++ ) { - var itemNode = itemNodes[ i ]; - var buildItem = { + const itemNode = itemNodes[ i ]; + const buildItem = { objectId: itemNode.getAttribute( 'objectid' ) }; - var transform = itemNode.getAttribute( 'transform' ); + const transform = itemNode.getAttribute( 'transform' ); if ( transform ) { @@ -684,10 +684,10 @@ function parseModelNode( modelNode ) { - var modelData = { + const modelData = { unit: modelNode.getAttribute( 'unit' ) || 'millimeter' }; - var metadataNodes = modelNode.querySelectorAll( 'metadata' ); + const metadataNodes = modelNode.querySelectorAll( 'metadata' ); if ( metadataNodes ) { @@ -695,7 +695,7 @@ } - var resourcesNode = modelNode.querySelector( 'resources' ); + const resourcesNode = modelNode.querySelector( 'resources' ); if ( resourcesNode ) { @@ -703,7 +703,7 @@ } - var buildNode = modelNode.querySelector( 'build' ); + const buildNode = modelNode.querySelector( 'build' ); if ( buildNode ) { @@ -717,19 +717,19 @@ function buildTexture( texture2dgroup, objects, modelData, textureData ) { - var texid = texture2dgroup.texid; - var texture2ds = modelData.resources.texture2d; - var texture2d = texture2ds[ texid ]; + const texid = texture2dgroup.texid; + const texture2ds = modelData.resources.texture2d; + const texture2d = texture2ds[ texid ]; if ( texture2d ) { - var data = textureData[ texture2d.path ]; - var type = texture2d.contenttype; - var blob = new Blob( [ data ], { + const data = textureData[ texture2d.path ]; + const type = texture2d.contenttype; + const blob = new Blob( [ data ], { type: type } ); - var sourceURI = URL.createObjectURL( blob ); - var texture = textureLoader.load( sourceURI, function () { + const sourceURI = URL.createObjectURL( blob ); + const texture = textureLoader.load( sourceURI, function () { URL.revokeObjectURL( sourceURI ); @@ -809,38 +809,38 @@ } - function buildBasematerialsMeshes( basematerials, triangleProperties, modelData, meshData, textureData, objectData ) { + function buildBasematerialsMeshes( basematerials, triangleProperties, meshData, objects, modelData, textureData, objectData ) { - var objectPindex = objectData.pindex; - var materialMap = {}; + const objectPindex = objectData.pindex; + const materialMap = {}; - for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) { + for ( let i = 0, l = triangleProperties.length; i < l; i ++ ) { - var triangleProperty = triangleProperties[ i ]; - var pindex = triangleProperty.p1 !== undefined ? triangleProperty.p1 : objectPindex; + const triangleProperty = triangleProperties[ i ]; + const pindex = triangleProperty.p1 !== undefined ? triangleProperty.p1 : objectPindex; if ( materialMap[ pindex ] === undefined ) materialMap[ pindex ] = []; materialMap[ pindex ].push( triangleProperty ); } // - var keys = Object.keys( materialMap ); - var meshes = []; + const keys = Object.keys( materialMap ); + const meshes = []; - for ( var i = 0, l = keys.length; i < l; i ++ ) { + for ( let i = 0, l = keys.length; i < l; i ++ ) { - var materialIndex = keys[ i ]; - var trianglePropertiesProps = materialMap[ materialIndex ]; - var basematerialData = basematerials.basematerials[ materialIndex ]; - var material = getBuild( basematerialData, objects, modelData, textureData, objectData, buildBasematerial ); // + const materialIndex = keys[ i ]; + const trianglePropertiesProps = materialMap[ materialIndex ]; + const basematerialData = basematerials.basematerials[ materialIndex ]; + const material = getBuild( basematerialData, objects, modelData, textureData, objectData, buildBasematerial ); // - var geometry = new THREE.BufferGeometry(); - var positionData = []; - var vertices = meshData.vertices; + const geometry = new THREE.BufferGeometry(); + const positionData = []; + const vertices = meshData.vertices; - for ( var j = 0, jl = trianglePropertiesProps.length; j < jl; j ++ ) { + for ( let j = 0, jl = trianglePropertiesProps.length; j < jl; j ++ ) { - var triangleProperty = trianglePropertiesProps[ j ]; + const triangleProperty = trianglePropertiesProps[ j ]; positionData.push( vertices[ triangleProperty.v1 * 3 + 0 ] ); positionData.push( vertices[ triangleProperty.v1 * 3 + 1 ] ); positionData.push( vertices[ triangleProperty.v1 * 3 + 2 ] ); @@ -855,7 +855,7 @@ geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positionData, 3 ) ); // - var mesh = new THREE.Mesh( geometry, material ); + const mesh = new THREE.Mesh( geometry, material ); meshes.push( mesh ); } @@ -864,18 +864,18 @@ } - function buildTexturedMesh( texture2dgroup, triangleProperties, modelData, meshData, textureData, objectData ) { + function buildTexturedMesh( texture2dgroup, triangleProperties, meshData, objects, modelData, textureData, objectData ) { // geometry - var geometry = new THREE.BufferGeometry(); - var positionData = []; - var uvData = []; - var vertices = meshData.vertices; - var uvs = texture2dgroup.uvs; + const geometry = new THREE.BufferGeometry(); + const positionData = []; + const uvData = []; + const vertices = meshData.vertices; + const uvs = texture2dgroup.uvs; - for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) { + for ( let i = 0, l = triangleProperties.length; i < l; i ++ ) { - var triangleProperty = triangleProperties[ i ]; + const triangleProperty = triangleProperties[ i ]; positionData.push( vertices[ triangleProperty.v1 * 3 + 0 ] ); positionData.push( vertices[ triangleProperty.v1 * 3 + 1 ] ); positionData.push( vertices[ triangleProperty.v1 * 3 + 2 ] ); @@ -898,32 +898,32 @@ geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positionData, 3 ) ); geometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( uvData, 2 ) ); // material - var texture = getBuild( texture2dgroup, objects, modelData, textureData, objectData, buildTexture ); - var material = new THREE.MeshPhongMaterial( { + const texture = getBuild( texture2dgroup, objects, modelData, textureData, objectData, buildTexture ); + const material = new THREE.MeshPhongMaterial( { map: texture, flatShading: true } ); // mesh - var mesh = new THREE.Mesh( geometry, material ); + const mesh = new THREE.Mesh( geometry, material ); return mesh; } - function buildVertexColorMesh( colorgroup, triangleProperties, modelData, meshData, objectData ) { + function buildVertexColorMesh( colorgroup, triangleProperties, meshData, objects, modelData, objectData ) { // geometry - var geometry = new THREE.BufferGeometry(); - var positionData = []; - var colorData = []; - var vertices = meshData.vertices; - var colors = colorgroup.colors; - - for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) { - - var triangleProperty = triangleProperties[ i ]; - var v1 = triangleProperty.v1; - var v2 = triangleProperty.v2; - var v3 = triangleProperty.v3; + const geometry = new THREE.BufferGeometry(); + const positionData = []; + const colorData = []; + const vertices = meshData.vertices; + const colors = colorgroup.colors; + + for ( let i = 0, l = triangleProperties.length; i < l; i ++ ) { + + const triangleProperty = triangleProperties[ i ]; + const v1 = triangleProperty.v1; + const v2 = triangleProperty.v2; + const v3 = triangleProperty.v3; positionData.push( vertices[ v1 * 3 + 0 ] ); positionData.push( vertices[ v1 * 3 + 1 ] ); positionData.push( vertices[ v1 * 3 + 2 ] ); @@ -934,9 +934,9 @@ positionData.push( vertices[ v3 * 3 + 1 ] ); positionData.push( vertices[ v3 * 3 + 2 ] ); // - var p1 = triangleProperty.p1 !== undefined ? triangleProperty.p1 : objectData.pindex; - var p2 = triangleProperty.p2 !== undefined ? triangleProperty.p2 : p1; - var p3 = triangleProperty.p3 !== undefined ? triangleProperty.p3 : p1; + const p1 = triangleProperty.p1 !== undefined ? triangleProperty.p1 : objectData.pindex; + const p2 = triangleProperty.p2 !== undefined ? triangleProperty.p2 : p1; + const p3 = triangleProperty.p3 !== undefined ? triangleProperty.p3 : p1; colorData.push( colors[ p1 * 3 + 0 ] ); colorData.push( colors[ p1 * 3 + 1 ] ); colorData.push( colors[ p1 * 3 + 2 ] ); @@ -952,48 +952,48 @@ geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positionData, 3 ) ); geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colorData, 3 ) ); // material - var material = new THREE.MeshPhongMaterial( { + const material = new THREE.MeshPhongMaterial( { vertexColors: true, flatShading: true } ); // mesh - var mesh = new THREE.Mesh( geometry, material ); + const mesh = new THREE.Mesh( geometry, material ); return mesh; } function buildDefaultMesh( meshData ) { - var geometry = new THREE.BufferGeometry(); + const geometry = new THREE.BufferGeometry(); geometry.setIndex( new THREE.BufferAttribute( meshData[ 'triangles' ], 1 ) ); geometry.setAttribute( 'position', new THREE.BufferAttribute( meshData[ 'vertices' ], 3 ) ); - var material = new THREE.MeshPhongMaterial( { + const material = new THREE.MeshPhongMaterial( { color: 0xaaaaff, flatShading: true } ); - var mesh = new THREE.Mesh( geometry, material ); + const mesh = new THREE.Mesh( geometry, material ); return mesh; } - function buildMeshes( resourceMap, modelData, meshData, textureData, objectData ) { + function buildMeshes( resourceMap, meshData, objects, modelData, textureData, objectData ) { - var keys = Object.keys( resourceMap ); - var meshes = []; + const keys = Object.keys( resourceMap ); + const meshes = []; - for ( var i = 0, il = keys.length; i < il; i ++ ) { + for ( let i = 0, il = keys.length; i < il; i ++ ) { - var resourceId = keys[ i ]; - var triangleProperties = resourceMap[ resourceId ]; - var resourceType = getResourceType( resourceId, modelData ); + const resourceId = keys[ i ]; + const triangleProperties = resourceMap[ resourceId ]; + const resourceType = getResourceType( resourceId, modelData ); switch ( resourceType ) { case 'material': - var basematerials = modelData.resources.basematerials[ resourceId ]; - var newMeshes = buildBasematerialsMeshes( basematerials, triangleProperties, modelData, meshData, textureData, objectData ); + const basematerials = modelData.resources.basematerials[ resourceId ]; + const newMeshes = buildBasematerialsMeshes( basematerials, triangleProperties, meshData, objects, modelData, textureData, objectData ); - for ( var j = 0, jl = newMeshes.length; j < jl; j ++ ) { + for ( let j = 0, jl = newMeshes.length; j < jl; j ++ ) { meshes.push( newMeshes[ j ] ); @@ -1002,13 +1002,13 @@ break; case 'texture': - var texture2dgroup = modelData.resources.texture2dgroup[ resourceId ]; - meshes.push( buildTexturedMesh( texture2dgroup, triangleProperties, modelData, meshData, textureData, objectData ) ); + const texture2dgroup = modelData.resources.texture2dgroup[ resourceId ]; + meshes.push( buildTexturedMesh( texture2dgroup, triangleProperties, meshData, objects, modelData, textureData, objectData ) ); break; case 'vertexColors': - var colorgroup = modelData.resources.colorgroup[ resourceId ]; - meshes.push( buildVertexColorMesh( colorgroup, triangleProperties, modelData, meshData, objectData ) ); + const colorgroup = modelData.resources.colorgroup[ resourceId ]; + meshes.push( buildVertexColorMesh( colorgroup, triangleProperties, meshData, objects, modelData, objectData ) ); break; case 'default': @@ -1054,14 +1054,14 @@ function analyzeObject( modelData, meshData, objectData ) { - var resourceMap = {}; - var triangleProperties = meshData[ 'triangleProperties' ]; - var objectPid = objectData.pid; + const resourceMap = {}; + const triangleProperties = meshData[ 'triangleProperties' ]; + const objectPid = objectData.pid; - for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) { + for ( let i = 0, l = triangleProperties.length; i < l; i ++ ) { - var triangleProperty = triangleProperties[ i ]; - var pid = triangleProperty.pid !== undefined ? triangleProperty.pid : objectPid; + const triangleProperty = triangleProperties[ i ]; + let pid = triangleProperty.pid !== undefined ? triangleProperty.pid : objectPid; if ( pid === undefined ) pid = 'default'; if ( resourceMap[ pid ] === undefined ) resourceMap[ pid ] = []; resourceMap[ pid ].push( triangleProperty ); @@ -1074,11 +1074,11 @@ function buildGroup( meshData, objects, modelData, textureData, objectData ) { - var group = new THREE.Group(); - var resourceMap = analyzeObject( modelData, meshData, objectData ); - var meshes = buildMeshes( resourceMap, modelData, meshData, textureData, objectData ); + const group = new THREE.Group(); + const resourceMap = analyzeObject( modelData, meshData, objectData ); + const meshes = buildMeshes( resourceMap, meshData, objects, modelData, textureData, objectData ); - for ( var i = 0, l = meshes.length; i < l; i ++ ) { + for ( let i = 0, l = meshes.length; i < l; i ++ ) { group.add( meshes[ i ] ); @@ -1096,16 +1096,16 @@ } - var availableExtensions = []; - var keys = Object.keys( extensions ); + const availableExtensions = []; + const keys = Object.keys( extensions ); - for ( var i = 0; i < keys.length; i ++ ) { + for ( let i = 0; i < keys.length; i ++ ) { - var ns = keys[ i ]; + const ns = keys[ i ]; - for ( var j = 0; j < scope.availableExtensions.length; j ++ ) { + for ( let j = 0; j < scope.availableExtensions.length; j ++ ) { - var extension = scope.availableExtensions[ j ]; + const extension = scope.availableExtensions[ j ]; if ( extension.ns === ns ) { @@ -1117,9 +1117,9 @@ } - for ( var i = 0; i < availableExtensions.length; i ++ ) { + for ( let i = 0; i < availableExtensions.length; i ++ ) { - var extension = availableExtensions[ i ]; + const extension = availableExtensions[ i ]; extension.apply( modelXml, extensions[ extension[ 'ns' ] ], meshData ); } @@ -1136,15 +1136,15 @@ function buildBasematerial( materialData, objects, modelData ) { - var material; - var displaypropertiesid = materialData.displaypropertiesid; - var pbmetallicdisplayproperties = modelData.resources.pbmetallicdisplayproperties; + let material; + const displaypropertiesid = materialData.displaypropertiesid; + const pbmetallicdisplayproperties = modelData.resources.pbmetallicdisplayproperties; if ( displaypropertiesid !== null && pbmetallicdisplayproperties[ displaypropertiesid ] !== undefined ) { // metallic display property, use StandardMaterial - var pbmetallicdisplayproperty = pbmetallicdisplayproperties[ displaypropertiesid ]; - var metallicData = pbmetallicdisplayproperty.data[ materialData.index ]; + const pbmetallicdisplayproperty = pbmetallicdisplayproperties[ displaypropertiesid ]; + const metallicData = pbmetallicdisplayproperty.data[ materialData.index ]; material = new THREE.MeshStandardMaterial( { flatShading: true, roughness: metallicData.roughness, @@ -1162,8 +1162,8 @@ material.name = materialData.name; // displaycolor MUST be specified with a value of a 6 or 8 digit hexadecimal number, e.g. "#RRGGBB" or "#RRGGBBAA" - var displaycolor = materialData.displaycolor; - var color = displaycolor.substring( 0, 7 ); + const displaycolor = materialData.displaycolor; + const color = displaycolor.substring( 0, 7 ); material.color.setStyle( color ); material.color.convertSRGBToLinear(); // displaycolor is in sRGB // process alpha if set @@ -1180,12 +1180,12 @@ function buildComposite( compositeData, objects, modelData, textureData ) { - var composite = new THREE.Group(); + const composite = new THREE.Group(); - for ( var j = 0; j < compositeData.length; j ++ ) { + for ( let j = 0; j < compositeData.length; j ++ ) { - var component = compositeData[ j ]; - var build = objects[ component.objectId ]; + const component = compositeData[ j ]; + let build = objects[ component.objectId ]; if ( build === undefined ) { @@ -1194,9 +1194,9 @@ } - var object3D = build.clone(); // apply component transform + const object3D = build.clone(); // apply component transform - var transform = component.transform; + const transform = component.transform; if ( transform ) { @@ -1214,19 +1214,19 @@ function buildObject( objectId, objects, modelData, textureData ) { - var objectData = modelData[ 'resources' ][ 'object' ][ objectId ]; + const objectData = modelData[ 'resources' ][ 'object' ][ objectId ]; if ( objectData[ 'mesh' ] ) { - var meshData = objectData[ 'mesh' ]; - var extensions = modelData[ 'extensions' ]; - var modelXml = modelData[ 'xml' ]; + const meshData = objectData[ 'mesh' ]; + const extensions = modelData[ 'extensions' ]; + const modelXml = modelData[ 'xml' ]; applyExtensions( extensions, meshData, modelXml ); objects[ objectData.id ] = getBuild( meshData, objects, modelData, textureData, objectData, buildGroup ); } else { - var compositeData = objectData[ 'components' ]; + const compositeData = objectData[ 'components' ]; objects[ objectData.id ] = getBuild( compositeData, objects, modelData, textureData, objectData, buildComposite ); } @@ -1235,18 +1235,18 @@ function buildObjects( data3mf ) { - var modelsData = data3mf.model; - var modelRels = data3mf.modelRels; - var objects = {}; - var modelsKeys = Object.keys( modelsData ); - var textureData = {}; // evaluate model relationships to textures + const modelsData = data3mf.model; + const modelRels = data3mf.modelRels; + const objects = {}; + const modelsKeys = Object.keys( modelsData ); + const textureData = {}; // evaluate model relationships to textures if ( modelRels ) { - for ( var i = 0, l = modelRels.length; i < l; i ++ ) { + for ( let i = 0, l = modelRels.length; i < l; i ++ ) { - var modelRel = modelRels[ i ]; - var textureKey = modelRel.target.substring( 1 ); + const modelRel = modelRels[ i ]; + const textureKey = modelRel.target.substring( 1 ); if ( data3mf.texture[ textureKey ] ) { @@ -1259,15 +1259,15 @@ } // start build - for ( var i = 0; i < modelsKeys.length; i ++ ) { + for ( let i = 0; i < modelsKeys.length; i ++ ) { - var modelsKey = modelsKeys[ i ]; - var modelData = modelsData[ modelsKey ]; - var objectIds = Object.keys( modelData[ 'resources' ][ 'object' ] ); + const modelsKey = modelsKeys[ i ]; + const modelData = modelsData[ modelsKey ]; + const objectIds = Object.keys( modelData[ 'resources' ][ 'object' ] ); - for ( var j = 0; j < objectIds.length; j ++ ) { + for ( let j = 0; j < objectIds.length; j ++ ) { - var objectId = objectIds[ j ]; + const objectId = objectIds[ j ]; buildObject( objectId, objects, modelData, textureData ); } @@ -1280,10 +1280,10 @@ function fetch3DModelPart( rels ) { - for ( var i = 0; i < rels.length; i ++ ) { + for ( let i = 0; i < rels.length; i ++ ) { - var rel = rels[ i ]; - var extension = rel.target.split( '.' ).pop(); + const rel = rels[ i ]; + const extension = rel.target.split( '.' ).pop(); if ( extension.toLowerCase() === 'model' ) return rel; } @@ -1292,16 +1292,16 @@ function build( objects, data3mf ) { - var group = new THREE.Group(); - var relationship = fetch3DModelPart( data3mf[ 'rels' ] ); - var buildData = data3mf.model[ relationship[ 'target' ].substring( 1 ) ][ 'build' ]; + const group = new THREE.Group(); + const relationship = fetch3DModelPart( data3mf[ 'rels' ] ); + const buildData = data3mf.model[ relationship[ 'target' ].substring( 1 ) ][ 'build' ]; - for ( var i = 0; i < buildData.length; i ++ ) { + for ( let i = 0; i < buildData.length; i ++ ) { - var buildItem = buildData[ i ]; - var object3D = objects[ buildItem[ 'objectId' ] ]; // apply transform + const buildItem = buildData[ i ]; + const object3D = objects[ buildItem[ 'objectId' ] ]; // apply transform - var transform = buildItem[ 'transform' ]; + const transform = buildItem[ 'transform' ]; if ( transform ) { @@ -1317,17 +1317,19 @@ } - var data3mf = loadDocument( data ); - var objects = buildObjects( data3mf ); + const data3mf = loadDocument( data ); + const objects = buildObjects( data3mf ); return build( objects, data3mf ); - }, - addExtension: function ( extension ) { + } + + addExtension( extension ) { this.availableExtensions.push( extension ); } - } ); + + } THREE.ThreeMFLoader = ThreeMFLoader; diff --git a/examples/js/loaders/AMFLoader.js b/examples/js/loaders/AMFLoader.js index 7b3212bb56717f..366db1ff639d63 100644 --- a/examples/js/loaders/AMFLoader.js +++ b/examples/js/loaders/AMFLoader.js @@ -7,7 +7,7 @@ * More information about the AMF format: http://amf.wikispaces.com * * Usage: - * var loader = new AMFLoader(); + * const loader = new AMFLoader(); * loader.load('/path/to/project.amf', function(objecttree) { * scene.add(objecttree); * }); @@ -18,18 +18,18 @@ * */ - var AMFLoader = function ( manager ) { + class AMFLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); + constructor( manager ) { - }; + super( manager ); - AMFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: AMFLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new THREE.FileLoader( scope.manager ); + const scope = this; + const loader = new THREE.FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( scope.requestHeader ); @@ -58,18 +58,19 @@ }, onProgress, onError ); - }, - parse: function ( data ) { + } + + parse( data ) { function loadDocument( data ) { - var view = new DataView( data ); - var magic = String.fromCharCode( view.getUint8( 0 ), view.getUint8( 1 ) ); + let view = new DataView( data ); + const magic = String.fromCharCode( view.getUint8( 0 ), view.getUint8( 1 ) ); if ( magic === 'PK' ) { - var zip = null; - var file = null; + let zip = null; + let file = null; console.log( 'THREE.AMFLoader: Loading Zip' ); try { @@ -87,7 +88,7 @@ } - for ( var file in zip ) { + for ( file in zip ) { if ( file.toLowerCase().substr( - 4 ) === '.amf' ) { @@ -102,8 +103,8 @@ } - var fileText = THREE.LoaderUtils.decodeText( view ); - var xmlData = new DOMParser().parseFromString( fileText, 'application/xml' ); + const fileText = THREE.LoaderUtils.decodeText( view ); + const xmlData = new DOMParser().parseFromString( fileText, 'application/xml' ); if ( xmlData.documentElement.nodeName.toLowerCase() !== 'amf' ) { @@ -118,8 +119,8 @@ function loadDocumentScale( node ) { - var scale = 1.0; - var unit = 'millimeter'; + let scale = 1.0; + let unit = 'millimeter'; if ( node.documentElement.attributes.unit !== undefined ) { @@ -127,7 +128,7 @@ } - var scaleUnits = { + const scaleUnits = { millimeter: 1.0, inch: 25.4, feet: 304.8, @@ -148,19 +149,19 @@ function loadMaterials( node ) { - var matName = 'AMF Material'; - var matId = node.attributes.id.textContent; - var color = { + let matName = 'AMF Material'; + const matId = node.attributes.id.textContent; + let color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; - var loadedMaterial = null; + let loadedMaterial = null; - for ( var i = 0; i < node.childNodes.length; i ++ ) { + for ( let i = 0; i < node.childNodes.length; i ++ ) { - var matChildEl = node.childNodes[ i ]; + const matChildEl = node.childNodes[ i ]; if ( matChildEl.nodeName === 'metadata' && matChildEl.attributes.type !== undefined ) { @@ -200,16 +201,16 @@ function loadColor( node ) { - var color = { + const color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; - for ( var i = 0; i < node.childNodes.length; i ++ ) { + for ( let i = 0; i < node.childNodes.length; i ++ ) { - var matColor = node.childNodes[ i ]; + const matColor = node.childNodes[ i ]; if ( matColor.nodeName === 'r' ) { @@ -237,12 +238,12 @@ function loadMeshVolume( node ) { - var volume = { + const volume = { name: '', triangles: [], materialid: null }; - var currVolumeNode = node.firstElementChild; + let currVolumeNode = node.firstElementChild; if ( node.attributes.materialid !== undefined ) { @@ -266,9 +267,9 @@ } else if ( currVolumeNode.nodeName === 'triangle' ) { - var v1 = currVolumeNode.getElementsByTagName( 'v1' )[ 0 ].textContent; - var v2 = currVolumeNode.getElementsByTagName( 'v2' )[ 0 ].textContent; - var v3 = currVolumeNode.getElementsByTagName( 'v3' )[ 0 ].textContent; + const v1 = currVolumeNode.getElementsByTagName( 'v1' )[ 0 ].textContent; + const v2 = currVolumeNode.getElementsByTagName( 'v2' )[ 0 ].textContent; + const v3 = currVolumeNode.getElementsByTagName( 'v3' )[ 0 ].textContent; volume.triangles.push( v1, v2, v3 ); } @@ -283,30 +284,30 @@ function loadMeshVertices( node ) { - var vertArray = []; - var normalArray = []; - var currVerticesNode = node.firstElementChild; + const vertArray = []; + const normalArray = []; + let currVerticesNode = node.firstElementChild; while ( currVerticesNode ) { if ( currVerticesNode.nodeName === 'vertex' ) { - var vNode = currVerticesNode.firstElementChild; + let vNode = currVerticesNode.firstElementChild; while ( vNode ) { if ( vNode.nodeName === 'coordinates' ) { - var x = vNode.getElementsByTagName( 'x' )[ 0 ].textContent; - var y = vNode.getElementsByTagName( 'y' )[ 0 ].textContent; - var z = vNode.getElementsByTagName( 'z' )[ 0 ].textContent; + const x = vNode.getElementsByTagName( 'x' )[ 0 ].textContent; + const y = vNode.getElementsByTagName( 'y' )[ 0 ].textContent; + const z = vNode.getElementsByTagName( 'z' )[ 0 ].textContent; vertArray.push( x, y, z ); } else if ( vNode.nodeName === 'normal' ) { - var nx = vNode.getElementsByTagName( 'nx' )[ 0 ].textContent; - var ny = vNode.getElementsByTagName( 'ny' )[ 0 ].textContent; - var nz = vNode.getElementsByTagName( 'nz' )[ 0 ].textContent; + const nx = vNode.getElementsByTagName( 'nx' )[ 0 ].textContent; + const ny = vNode.getElementsByTagName( 'ny' )[ 0 ].textContent; + const nz = vNode.getElementsByTagName( 'nz' )[ 0 ].textContent; normalArray.push( nx, ny, nz ); } @@ -330,13 +331,13 @@ function loadObject( node ) { - var objId = node.attributes.id.textContent; - var loadedObject = { + const objId = node.attributes.id.textContent; + const loadedObject = { name: 'amfobject', meshes: [] }; - var currColor = null; - var currObjNode = node.firstElementChild; + let currColor = null; + let currObjNode = node.firstElementChild; while ( currObjNode ) { @@ -358,8 +359,8 @@ } else if ( currObjNode.nodeName === 'mesh' ) { - var currMeshNode = currObjNode.firstElementChild; - var mesh = { + let currMeshNode = currObjNode.firstElementChild; + const mesh = { vertices: [], normals: [], volumes: [], @@ -370,7 +371,7 @@ if ( currMeshNode.nodeName === 'vertices' ) { - var loadedVertices = loadMeshVertices( currMeshNode ); + const loadedVertices = loadMeshVertices( currMeshNode ); mesh.normals = mesh.normals.concat( loadedVertices.normals ); mesh.vertices = mesh.vertices.concat( loadedVertices.vertices ); @@ -399,18 +400,18 @@ } - var xmlData = loadDocument( data ); - var amfName = ''; - var amfAuthor = ''; - var amfScale = loadDocumentScale( xmlData ); - var amfMaterials = {}; - var amfObjects = {}; - var childNodes = xmlData.documentElement.childNodes; - var i, j; + const xmlData = loadDocument( data ); + let amfName = ''; + let amfAuthor = ''; + const amfScale = loadDocumentScale( xmlData ); + const amfMaterials = {}; + const amfObjects = {}; + const childNodes = xmlData.documentElement.childNodes; + let i, j; for ( i = 0; i < childNodes.length; i ++ ) { - var child = childNodes[ i ]; + const child = childNodes[ i ]; if ( child.nodeName === 'metadata' ) { @@ -430,20 +431,20 @@ } else if ( child.nodeName === 'material' ) { - var loadedMaterial = loadMaterials( child ); + const loadedMaterial = loadMaterials( child ); amfMaterials[ loadedMaterial.id ] = loadedMaterial.material; } else if ( child.nodeName === 'object' ) { - var loadedObject = loadObject( child ); + const loadedObject = loadObject( child ); amfObjects[ loadedObject.id ] = loadedObject.obj; } } - var sceneObject = new THREE.Group(); - var defaultMaterial = new THREE.MeshPhongMaterial( { + const sceneObject = new THREE.Group(); + const defaultMaterial = new THREE.MeshPhongMaterial( { color: 0xaaaaff, flatShading: true } ); @@ -451,19 +452,19 @@ sceneObject.userData.author = amfAuthor; sceneObject.userData.loader = 'AMF'; - for ( var id in amfObjects ) { + for ( const id in amfObjects ) { - var part = amfObjects[ id ]; - var meshes = part.meshes; - var newObject = new THREE.Group(); + const part = amfObjects[ id ]; + const meshes = part.meshes; + const newObject = new THREE.Group(); newObject.name = part.name || ''; for ( i = 0; i < meshes.length; i ++ ) { - var objDefaultMaterial = defaultMaterial; - var mesh = meshes[ i ]; - var vertices = new THREE.Float32BufferAttribute( mesh.vertices, 3 ); - var normals = null; + let objDefaultMaterial = defaultMaterial; + const mesh = meshes[ i ]; + const vertices = new THREE.Float32BufferAttribute( mesh.vertices, 3 ); + let normals = null; if ( mesh.normals.length ) { @@ -473,7 +474,7 @@ if ( mesh.color ) { - var color = mesh.color; + const color = mesh.color; objDefaultMaterial = defaultMaterial.clone(); objDefaultMaterial.color = new THREE.Color( color.r, color.g, color.b ); @@ -486,13 +487,13 @@ } - var volumes = mesh.volumes; + const volumes = mesh.volumes; for ( j = 0; j < volumes.length; j ++ ) { - var volume = volumes[ j ]; - var newGeometry = new THREE.BufferGeometry(); - var material = objDefaultMaterial; + const volume = volumes[ j ]; + const newGeometry = new THREE.BufferGeometry(); + let material = objDefaultMaterial; newGeometry.setIndex( volume.triangles ); newGeometry.setAttribute( 'position', vertices.clone() ); @@ -522,7 +523,8 @@ return sceneObject; } - } ); + + } THREE.AMFLoader = AMFLoader; diff --git a/examples/js/loaders/BVHLoader.js b/examples/js/loaders/BVHLoader.js index 902fe74167b581..3eae1538b863a9 100644 --- a/examples/js/loaders/BVHLoader.js +++ b/examples/js/loaders/BVHLoader.js @@ -7,20 +7,20 @@ * */ - var BVHLoader = function ( manager ) { + class BVHLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); - this.animateBonePositions = true; - this.animateBoneRotations = true; + constructor( manager ) { - }; + super( manager ); + this.animateBonePositions = true; + this.animateBoneRotations = true; - BVHLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: BVHLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new THREE.FileLoader( scope.manager ); + const scope = this; + const loader = new THREE.FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setRequestHeader( scope.requestHeader ); loader.setWithCredentials( scope.withCredentials ); @@ -48,8 +48,9 @@ }, onProgress, onError ); - }, - parse: function ( text ) { + } + + parse( text ) { /* reads a string array (lines) from a BVH file @@ -66,9 +67,9 @@ } - var list = []; // collects flat array of all bones + const list = []; // collects flat array of all bones - var root = readNode( lines, nextLine( lines ), list ); // read motion data + const root = readNode( lines, nextLine( lines ), list ); // read motion data if ( nextLine( lines ) !== 'MOTION' ) { @@ -77,8 +78,8 @@ } // number of frames - var tokens = nextLine( lines ).split( /[\s]+/ ); - var numFrames = parseInt( tokens[ 1 ] ); + let tokens = nextLine( lines ).split( /[\s]+/ ); + const numFrames = parseInt( tokens[ 1 ] ); if ( isNaN( numFrames ) ) { @@ -88,7 +89,7 @@ tokens = nextLine( lines ).split( /[\s]+/ ); - var frameTime = parseFloat( tokens[ 2 ] ); + const frameTime = parseFloat( tokens[ 2 ] ); if ( isNaN( frameTime ) ) { @@ -97,7 +98,7 @@ } // read frame data line by line - for ( var i = 0; i < numFrames; i ++ ) { + for ( let i = 0; i < numFrames; i ++ ) { tokens = nextLine( lines ).split( /[\s]+/ ); readFrameData( tokens, i * frameTime, root ); @@ -123,18 +124,18 @@ // end sites have no motion data if ( bone.type === 'ENDSITE' ) return; // add keyframe - var keyframe = { + const keyframe = { time: frameTime, position: new THREE.Vector3(), rotation: new THREE.Quaternion() }; bone.frames.push( keyframe ); - var quat = new THREE.Quaternion(); - var vx = new THREE.Vector3( 1, 0, 0 ); - var vy = new THREE.Vector3( 0, 1, 0 ); - var vz = new THREE.Vector3( 0, 0, 1 ); // parse values for each channel in node + const quat = new THREE.Quaternion(); + const vx = new THREE.Vector3( 1, 0, 0 ); + const vy = new THREE.Vector3( 0, 1, 0 ); + const vz = new THREE.Vector3( 0, 0, 1 ); // parse values for each channel in node - for ( var i = 0; i < bone.channels.length; i ++ ) { + for ( let i = 0; i < bone.channels.length; i ++ ) { switch ( bone.channels[ i ] ) { @@ -173,7 +174,7 @@ } // parse child nodes - for ( var i = 0; i < bone.children.length; i ++ ) { + for ( let i = 0; i < bone.children.length; i ++ ) { readFrameData( data, frameTime, bone.children[ i ] ); @@ -191,14 +192,14 @@ function readNode( lines, firstline, list ) { - var node = { + const node = { name: '', type: '', frames: [] }; list.push( node ); // parse node type and name - var tokens = firstline.split( /[\s]+/ ); + let tokens = firstline.split( /[\s]+/ ); if ( tokens[ 0 ].toUpperCase() === 'END' && tokens[ 1 ].toUpperCase() === 'SITE' ) { @@ -233,7 +234,7 @@ } - var offset = new THREE.Vector3( parseFloat( tokens[ 1 ] ), parseFloat( tokens[ 2 ] ), parseFloat( tokens[ 3 ] ) ); + const offset = new THREE.Vector3( parseFloat( tokens[ 1 ] ), parseFloat( tokens[ 2 ] ), parseFloat( tokens[ 3 ] ) ); if ( isNaN( offset.x ) || isNaN( offset.y ) || isNaN( offset.z ) ) { @@ -253,7 +254,7 @@ } - var numChannels = parseInt( tokens[ 1 ] ); + const numChannels = parseInt( tokens[ 1 ] ); node.channels = tokens.splice( 2, numChannels ); node.children = []; @@ -262,7 +263,7 @@ while ( true ) { - var line = nextLine( lines ); + const line = nextLine( lines ); if ( line === '}' ) { @@ -287,14 +288,14 @@ function toTHREEBone( source, list ) { - var bone = new THREE.Bone(); + const bone = new THREE.Bone(); list.push( bone ); bone.position.add( source.offset ); bone.name = source.name; if ( source.type !== 'ENDSITE' ) { - for ( var i = 0; i < source.children.length; i ++ ) { + for ( let i = 0; i < source.children.length; i ++ ) { bone.add( toTHREEBone( source.children[ i ], list ) ); @@ -314,20 +315,20 @@ function toTHREEAnimation( bones ) { - var tracks = []; // create a position and quaternion animation track for each node + const tracks = []; // create a position and quaternion animation track for each node - for ( var i = 0; i < bones.length; i ++ ) { + for ( let i = 0; i < bones.length; i ++ ) { - var bone = bones[ i ]; + const bone = bones[ i ]; if ( bone.type === 'ENDSITE' ) continue; // track data - var times = []; - var positions = []; - var rotations = []; + const times = []; + const positions = []; + const rotations = []; - for ( var j = 0; j < bone.frames.length; j ++ ) { + for ( let j = 0; j < bone.frames.length; j ++ ) { - var frame = bone.frames[ j ]; + const frame = bone.frames[ j ]; times.push( frame.time ); // the animation system animates the position property, // so we have to add the joint offset to all values @@ -365,7 +366,7 @@ function nextLine( lines ) { - var line; // skip empty lines + let line; // skip empty lines while ( ( line = lines.shift().trim() ).length === 0 ) {} @@ -373,19 +374,20 @@ } - var scope = this; - var lines = text.split( /[\r\n]+/g ); - var bones = readBvh( lines ); - var threeBones = []; + const scope = this; + const lines = text.split( /[\r\n]+/g ); + const bones = readBvh( lines ); + const threeBones = []; toTHREEBone( bones[ 0 ], threeBones ); - var threeClip = toTHREEAnimation( bones ); + const threeClip = toTHREEAnimation( bones ); return { skeleton: new THREE.Skeleton( threeBones ), clip: threeClip }; } - } ); + + } THREE.BVHLoader = BVHLoader; diff --git a/examples/js/loaders/BasisTextureLoader.js b/examples/js/loaders/BasisTextureLoader.js index 0c8470ab6a9934..f2b5998ea28c04 100644 --- a/examples/js/loaders/BasisTextureLoader.js +++ b/examples/js/loaders/BasisTextureLoader.js @@ -13,36 +13,39 @@ * to the main thread. */ - var BasisTextureLoader = function ( manager ) { - - THREE.Loader.call( this, manager ); - this.transcoderPath = ''; - this.transcoderBinary = null; - this.transcoderPending = null; - this.workerLimit = 4; - this.workerPool = []; - this.workerNextTaskID = 1; - this.workerSourceURL = ''; - this.workerConfig = null; + const _taskCache = new WeakMap(); - }; + class BasisTextureLoader extends THREE.Loader { + + constructor( manager ) { + + super( manager ); + this.transcoderPath = ''; + this.transcoderBinary = null; + this.transcoderPending = null; + this.workerLimit = 4; + this.workerPool = []; + this.workerNextTaskID = 1; + this.workerSourceURL = ''; + this.workerConfig = null; + + } - BasisTextureLoader.taskCache = new WeakMap(); - BasisTextureLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: BasisTextureLoader, - setTranscoderPath: function ( path ) { + setTranscoderPath( path ) { this.transcoderPath = path; return this; - }, - setWorkerLimit: function ( workerLimit ) { + } + + setWorkerLimit( workerLimit ) { this.workerLimit = workerLimit; return this; - }, - detectSupport: function ( renderer ) { + } + + detectSupport( renderer ) { this.workerConfig = { astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ), @@ -54,20 +57,22 @@ }; return this; - }, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var loader = new THREE.FileLoader( this.manager ); + const loader = new THREE.FileLoader( this.manager ); loader.setResponseType( 'arraybuffer' ); loader.setWithCredentials( this.withCredentials ); - var texture = new THREE.CompressedTexture(); + const texture = new THREE.CompressedTexture(); loader.load( url, buffer => { // Check for an existing task using this buffer. A transferred buffer cannot be transferred // again from this thread. - if ( BasisTextureLoader.taskCache.has( buffer ) ) { + if ( _taskCache.has( buffer ) ) { + + const cachedTask = _taskCache.get( buffer ); - var cachedTask = BasisTextureLoader.taskCache.get( buffer ); return cachedTask.promise.then( onLoad ).catch( onError ); } @@ -83,17 +88,18 @@ }, onProgress, onError ); return texture; - }, - + } /** Low-level transcoding API, exposed for use by KTX2Loader. */ - parseInternalAsync: function ( options ) { - var { + + parseInternalAsync( options ) { + + const { levels } = options; - var buffers = new Set(); + const buffers = new Set(); - for ( var i = 0; i < levels.length; i ++ ) { + for ( let i = 0; i < levels.length; i ++ ) { buffers.add( levels[ i ].data.buffer ); @@ -103,27 +109,28 @@ lowLevel: true } ); - }, - + } /** * @param {ArrayBuffer[]} buffers * @param {object?} config * @return {Promise} */ - _createTexture: function ( buffers, config ) { - var worker; - var taskID; - var taskConfig = config || {}; - var taskCost = 0; - for ( var i = 0; i < buffers.length; i ++ ) { + _createTexture( buffers, config = {} ) { + + let worker; + let taskID; + const taskConfig = config; + let taskCost = 0; + + for ( let i = 0; i < buffers.length; i ++ ) { taskCost += buffers[ i ].byteLength; } - var texturePending = this._allocateWorker( taskCost ).then( _worker => { + const texturePending = this._allocateWorker( taskCost ).then( _worker => { worker = _worker; taskID = this.workerNextTaskID ++; @@ -144,13 +151,13 @@ } ).then( message => { - var { + const { mipmaps, width, height, format } = message; - var texture = new THREE.CompressedTexture( mipmaps, width, height, format, THREE.UnsignedByteType ); + const texture = new THREE.CompressedTexture( mipmaps, width, height, format, THREE.UnsignedByteType ); texture.minFilter = mipmaps.length === 1 ? THREE.LinearFilter : THREE.LinearMipmapLinearFilter; texture.magFilter = THREE.LinearFilter; texture.generateMipmaps = false; @@ -171,39 +178,41 @@ } ); // Cache the task result. - BasisTextureLoader.taskCache.set( buffers[ 0 ], { + _taskCache.set( buffers[ 0 ], { promise: texturePending } ); + return texturePending; - }, - _initTranscoder: function () { + } + + _initTranscoder() { if ( ! this.transcoderPending ) { // Load transcoder wrapper. - var jsLoader = new THREE.FileLoader( this.manager ); + const jsLoader = new THREE.FileLoader( this.manager ); jsLoader.setPath( this.transcoderPath ); jsLoader.setWithCredentials( this.withCredentials ); - var jsContent = new Promise( ( resolve, reject ) => { + const jsContent = new Promise( ( resolve, reject ) => { jsLoader.load( 'basis_transcoder.js', resolve, undefined, reject ); } ); // Load transcoder WASM binary. - var binaryLoader = new THREE.FileLoader( this.manager ); + const binaryLoader = new THREE.FileLoader( this.manager ); binaryLoader.setPath( this.transcoderPath ); binaryLoader.setResponseType( 'arraybuffer' ); binaryLoader.setWithCredentials( this.withCredentials ); - var binaryContent = new Promise( ( resolve, reject ) => { + const binaryContent = new Promise( ( resolve, reject ) => { binaryLoader.load( 'basis_transcoder.wasm', resolve, undefined, reject ); } ); this.transcoderPending = Promise.all( [ jsContent, binaryContent ] ).then( ( [ jsContent, binaryContent ] ) => { - var fn = BasisTextureLoader.BasisWorker.toString(); - var body = [ '/* constants */', 'var _EngineFormat = ' + JSON.stringify( BasisTextureLoader.EngineFormat ), 'var _TranscoderFormat = ' + JSON.stringify( BasisTextureLoader.TranscoderFormat ), 'var _BasisFormat = ' + JSON.stringify( BasisTextureLoader.BasisFormat ), '/* basis_transcoder.js */', jsContent, '/* worker */', fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) ) ].join( '\n' ); + const fn = BasisTextureLoader.BasisWorker.toString(); + const body = [ '/* constants */', 'let _EngineFormat = ' + JSON.stringify( BasisTextureLoader.EngineFormat ), 'let _TranscoderFormat = ' + JSON.stringify( BasisTextureLoader.TranscoderFormat ), 'let _BasisFormat = ' + JSON.stringify( BasisTextureLoader.BasisFormat ), '/* basis_transcoder.js */', jsContent, '/* worker */', fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) ) ].join( '\n' ); this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) ); this.transcoderBinary = binaryContent; @@ -213,14 +222,15 @@ return this.transcoderPending; - }, - _allocateWorker: function ( taskCost ) { + } + + _allocateWorker( taskCost ) { return this._initTranscoder().then( () => { if ( this.workerPool.length < this.workerLimit ) { - var worker = new Worker( this.workerSourceURL ); + const worker = new Worker( this.workerSourceURL ); worker._callbacks = {}; worker._taskLoad = 0; worker.postMessage( { @@ -231,7 +241,7 @@ worker.onmessage = function ( e ) { - var message = e.data; + const message = e.data; switch ( message.type ) { @@ -264,16 +274,17 @@ } - var worker = this.workerPool[ this.workerPool.length - 1 ]; + const worker = this.workerPool[ this.workerPool.length - 1 ]; worker._taskLoad += taskCost; return worker; } ); - }, - dispose: function () { + } - for ( var i = 0; i < this.workerPool.length; i ++ ) { + dispose() { + + for ( let i = 0; i < this.workerPool.length; i ++ ) { this.workerPool[ i ].terminate(); @@ -283,9 +294,11 @@ return this; } - } ); + + } /* CONSTANTS */ + BasisTextureLoader.BasisFormat = { ETC1S: 0, UASTC_4x4: 1 @@ -325,18 +338,18 @@ BasisTextureLoader.BasisWorker = function () { - var config; - var transcoderPending; - var BasisModule; - var EngineFormat = _EngineFormat; // eslint-disable-line no-undef + let config; + let transcoderPending; + let BasisModule; + const EngineFormat = _EngineFormat; // eslint-disable-line no-undef - var TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef + const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef - var BasisFormat = _BasisFormat; // eslint-disable-line no-undef + const BasisFormat = _BasisFormat; // eslint-disable-line no-undef onmessage = function ( e ) { - var message = e.data; + const message = e.data; switch ( message.type ) { @@ -350,16 +363,16 @@ try { - var { + const { width, height, hasAlpha, mipmaps, format } = message.taskConfig.lowLevel ? transcodeLowLevel( message.taskConfig ) : transcode( message.buffers[ 0 ] ); - var buffers = []; + const buffers = []; - for ( var i = 0; i < mipmaps.length; ++ i ) { + for ( let i = 0; i < mipmaps.length; ++ i ) { buffers.push( mipmaps[ i ].data.buffer ); @@ -413,24 +426,24 @@ function transcodeLowLevel( taskConfig ) { - var { + const { basisFormat, width, height, hasAlpha } = taskConfig; - var { + const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha ); - var blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat ); + const blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat ); assert( BasisModule.isFormatSupported( transcoderFormat ), 'THREE.BasisTextureLoader: Unsupported format.' ); - var mipmaps = []; + const mipmaps = []; if ( basisFormat === BasisFormat.ETC1S ) { - var transcoder = new BasisModule.LowLevelETC1SImageTranscoder(); - var { + const transcoder = new BasisModule.LowLevelETC1SImageTranscoder(); + const { endpointCount, endpointsData, selectorCount, @@ -440,18 +453,18 @@ try { - var ok; + let ok; ok = transcoder.decodePalettes( endpointCount, endpointsData, selectorCount, selectorsData ); assert( ok, 'THREE.BasisTextureLoader: decodePalettes() failed.' ); ok = transcoder.decodeTables( tablesData ); assert( ok, 'THREE.BasisTextureLoader: decodeTables() failed.' ); - for ( var i = 0; i < taskConfig.levels.length; i ++ ) { + for ( let i = 0; i < taskConfig.levels.length; i ++ ) { - var level = taskConfig.levels[ i ]; - var imageDesc = taskConfig.globalData.imageDescs[ i ]; - var dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height ); - var dst = new Uint8Array( dstByteLength ); + const level = taskConfig.levels[ i ]; + const imageDesc = taskConfig.globalData.imageDescs[ i ]; + const dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height ); + const dst = new Uint8Array( dstByteLength ); ok = transcoder.transcodeImage( transcoderFormat, dst, dstByteLength / blockByteLength, level.data, getWidthInBlocks( transcoderFormat, level.width ), getHeightInBlocks( transcoderFormat, level.height ), level.width, level.height, level.index, imageDesc.rgbSliceByteOffset, imageDesc.rgbSliceByteLength, imageDesc.alphaSliceByteOffset, imageDesc.alphaSliceByteLength, imageDesc.imageFlags, hasAlpha, false, 0, 0 ); assert( ok, 'THREE.BasisTextureLoader: transcodeImage() failed for level ' + level.index + '.' ); mipmaps.push( { @@ -470,12 +483,12 @@ } else { - for ( var i = 0; i < taskConfig.levels.length; i ++ ) { + for ( let i = 0; i < taskConfig.levels.length; i ++ ) { - var level = taskConfig.levels[ i ]; - var dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height ); - var dst = new Uint8Array( dstByteLength ); - var ok = BasisModule.transcodeUASTCImage( transcoderFormat, dst, dstByteLength / blockByteLength, level.data, getWidthInBlocks( transcoderFormat, level.width ), getHeightInBlocks( transcoderFormat, level.height ), level.width, level.height, level.index, 0, level.data.byteLength, 0, hasAlpha, false, 0, 0, - 1, - 1 ); + const level = taskConfig.levels[ i ]; + const dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height ); + const dst = new Uint8Array( dstByteLength ); + const ok = BasisModule.transcodeUASTCImage( transcoderFormat, dst, dstByteLength / blockByteLength, level.data, getWidthInBlocks( transcoderFormat, level.width ), getHeightInBlocks( transcoderFormat, level.height ), level.width, level.height, level.index, 0, level.data.byteLength, 0, hasAlpha, false, 0, 0, - 1, - 1 ); assert( ok, 'THREE.BasisTextureLoader: transcodeUASTCImage() failed for level ' + level.index + '.' ); mipmaps.push( { data: dst, @@ -499,12 +512,12 @@ function transcode( buffer ) { - var basisFile = new BasisModule.BasisFile( new Uint8Array( buffer ) ); - var basisFormat = basisFile.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S; - var width = basisFile.getImageWidth( 0, 0 ); - var height = basisFile.getImageHeight( 0, 0 ); - var levels = basisFile.getNumLevels( 0 ); - var hasAlpha = basisFile.getHasAlpha(); + const basisFile = new BasisModule.BasisFile( new Uint8Array( buffer ) ); + const basisFormat = basisFile.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S; + const width = basisFile.getImageWidth( 0, 0 ); + const height = basisFile.getImageHeight( 0, 0 ); + const levels = basisFile.getNumLevels( 0 ); + const hasAlpha = basisFile.getHasAlpha(); function cleanup() { @@ -513,7 +526,7 @@ } - var { + const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha ); @@ -532,14 +545,14 @@ } - var mipmaps = []; + const mipmaps = []; - for ( var mip = 0; mip < levels; mip ++ ) { + for ( let mip = 0; mip < levels; mip ++ ) { - var mipWidth = basisFile.getImageWidth( 0, mip ); - var mipHeight = basisFile.getImageHeight( 0, mip ); - var dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, transcoderFormat ) ); - var status = basisFile.transcodeImage( dst, 0, mip, transcoderFormat, 0, hasAlpha ); + const mipWidth = basisFile.getImageWidth( 0, mip ); + const mipHeight = basisFile.getImageHeight( 0, mip ); + const dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, transcoderFormat ) ); + const status = basisFile.transcodeImage( dst, 0, mip, transcoderFormat, 0, hasAlpha ); if ( ! status ) { @@ -575,7 +588,7 @@ // chooses RGBA32 only as a last resort and does not expose that option to the caller. - var FORMAT_OPTIONS = [ { + const FORMAT_OPTIONS = [ { if: 'astcSupported', basisFormat: [ BasisFormat.UASTC_4x4 ], transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ], @@ -624,12 +637,12 @@ priorityUASTC: 6, needsPowerOfTwo: true } ]; - var ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) { + const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) { return a.priorityETC1S - b.priorityETC1S; } ); - var UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) { + const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) { return a.priorityUASTC - b.priorityUASTC; @@ -637,13 +650,13 @@ function getTranscoderFormat( basisFormat, width, height, hasAlpha ) { - var transcoderFormat; - var engineFormat; - var options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; + let transcoderFormat; + let engineFormat; + const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; - for ( var i = 0; i < options.length; i ++ ) { + for ( let i = 0; i < options.length; i ++ ) { - var opt = options[ i ]; + const opt = options[ i ]; if ( ! config[ opt.if ] ) continue; if ( ! opt.basisFormat.includes( basisFormat ) ) continue; if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue; @@ -686,7 +699,7 @@ function getTranscodedImageByteLength( transcoderFormat, width, height ) { - var blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat ); + const blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat ); if ( BasisModule.formatIsUncompressed( transcoderFormat ) ) { @@ -698,8 +711,8 @@ // GL requires extra padding for very small textures: // https://www.khronos.org/registry/OpenGL/extensions/IMG/IMG_texture_compression_pvrtc.txt - var paddedWidth = width + 3 & ~ 3; - var paddedHeight = height + 3 & ~ 3; + const paddedWidth = width + 3 & ~ 3; + const paddedHeight = height + 3 & ~ 3; return ( Math.max( 8, paddedWidth ) * Math.max( 8, paddedHeight ) * 4 + 7 ) / 8; } diff --git a/examples/js/loaders/ColladaLoader.js b/examples/js/loaders/ColladaLoader.js index 1f350db462a40f..42422d6dad110d 100644 --- a/examples/js/loaders/ColladaLoader.js +++ b/examples/js/loaders/ColladaLoader.js @@ -1,18 +1,18 @@ ( function () { - var ColladaLoader = function ( manager ) { + class ColladaLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); + constructor( manager ) { - }; + super( manager ); - ColladaLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: ColladaLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var path = scope.path === '' ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path; - var loader = new THREE.FileLoader( scope.manager ); + const scope = this; + const path = scope.path === '' ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path; + const loader = new THREE.FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setRequestHeader( scope.requestHeader ); loader.setWithCredentials( scope.withCredentials ); @@ -40,26 +40,19 @@ }, onProgress, onError ); - }, - options: { - set convertUpAxis( value ) { - - console.warn( 'THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.' ); - - } + } - }, - parse: function ( text, path ) { + parse( text, path ) { function getElementsByTagName( xml, name ) { // Non recursive xml.getElementsByTagName() ... - var array = []; - var childNodes = xml.childNodes; + const array = []; + const childNodes = xml.childNodes; - for ( var i = 0, l = childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = childNodes.length; i < l; i ++ ) { - var child = childNodes[ i ]; + const child = childNodes[ i ]; if ( child.nodeName === name ) { @@ -76,10 +69,10 @@ function parseStrings( text ) { if ( text.length === 0 ) return []; - var parts = text.trim().split( /\s+/ ); - var array = new Array( parts.length ); + const parts = text.trim().split( /\s+/ ); + const array = new Array( parts.length ); - for ( var i = 0, l = parts.length; i < l; i ++ ) { + for ( let i = 0, l = parts.length; i < l; i ++ ) { array[ i ] = parts[ i ]; @@ -92,10 +85,10 @@ function parseFloats( text ) { if ( text.length === 0 ) return []; - var parts = text.trim().split( /\s+/ ); - var array = new Array( parts.length ); + const parts = text.trim().split( /\s+/ ); + const array = new Array( parts.length ); - for ( var i = 0, l = parts.length; i < l; i ++ ) { + for ( let i = 0, l = parts.length; i < l; i ++ ) { array[ i ] = parseFloat( parts[ i ] ); @@ -108,10 +101,10 @@ function parseInts( text ) { if ( text.length === 0 ) return []; - var parts = text.trim().split( /\s+/ ); - var array = new Array( parts.length ); + const parts = text.trim().split( /\s+/ ); + const array = new Array( parts.length ); - for ( var i = 0, l = parts.length; i < l; i ++ ) { + for ( let i = 0, l = parts.length; i < l; i ++ ) { array[ i ] = parseInt( parts[ i ] ); @@ -172,13 +165,13 @@ function parseLibrary( xml, libraryName, nodeName, parser ) { - var library = getElementsByTagName( xml, libraryName )[ 0 ]; + const library = getElementsByTagName( xml, libraryName )[ 0 ]; if ( library !== undefined ) { - var elements = getElementsByTagName( library, nodeName ); + const elements = getElementsByTagName( library, nodeName ); - for ( var i = 0; i < elements.length; i ++ ) { + for ( let i = 0; i < elements.length; i ++ ) { parser( elements[ i ] ); @@ -190,9 +183,9 @@ function buildLibrary( data, builder ) { - for ( var name in data ) { + for ( const name in data ) { - var object = data[ name ]; + const object = data[ name ]; object.build = builder( data[ name ] ); } @@ -211,18 +204,18 @@ function parseAnimation( xml ) { - var data = { + const data = { sources: {}, samplers: {}, channels: {} }; - var hasChildren = false; + let hasChildren = false; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; - var id; + let id; switch ( child.nodeName ) { @@ -265,20 +258,20 @@ function parseAnimationSampler( xml ) { - var data = { + const data = { inputs: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'input': - var id = parseId( child.getAttribute( 'source' ) ); - var semantic = child.getAttribute( 'semantic' ); + const id = parseId( child.getAttribute( 'source' ) ); + const semantic = child.getAttribute( 'semantic' ); data.inputs[ semantic ] = id; break; @@ -292,15 +285,15 @@ function parseAnimationChannel( xml ) { - var data = {}; - var target = xml.getAttribute( 'target' ); // parsing SID Addressing Syntax + const data = {}; + const target = xml.getAttribute( 'target' ); // parsing SID Addressing Syntax - var parts = target.split( '/' ); - var id = parts.shift(); - var sid = parts.shift(); // check selection syntax + let parts = target.split( '/' ); + const id = parts.shift(); + let sid = parts.shift(); // check selection syntax - var arraySyntax = sid.indexOf( '(' ) !== - 1; - var memberSyntax = sid.indexOf( '.' ) !== - 1; + const arraySyntax = sid.indexOf( '(' ) !== - 1; + const memberSyntax = sid.indexOf( '.' ) !== - 1; if ( memberSyntax ) { @@ -312,10 +305,10 @@ } else if ( arraySyntax ) { // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices. - var indices = sid.split( '(' ); + const indices = sid.split( '(' ); sid = indices.shift(); - for ( var i = 0; i < indices.length; i ++ ) { + for ( let i = 0; i < indices.length; i ++ ) { indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) ); @@ -336,22 +329,22 @@ function buildAnimation( data ) { - var tracks = []; - var channels = data.channels; - var samplers = data.samplers; - var sources = data.sources; + const tracks = []; + const channels = data.channels; + const samplers = data.samplers; + const sources = data.sources; - for ( var target in channels ) { + for ( const target in channels ) { if ( channels.hasOwnProperty( target ) ) { - var channel = channels[ target ]; - var sampler = samplers[ channel.sampler ]; - var inputId = sampler.inputs.INPUT; - var outputId = sampler.inputs.OUTPUT; - var inputSource = sources[ inputId ]; - var outputSource = sources[ outputId ]; - var animation = buildAnimationChannel( channel, inputSource, outputSource ); + const channel = channels[ target ]; + const sampler = samplers[ channel.sampler ]; + const inputId = sampler.inputs.INPUT; + const outputId = sampler.inputs.OUTPUT; + const inputSource = sources[ inputId ]; + const outputSource = sources[ outputId ]; + const animation = buildAnimationChannel( channel, inputSource, outputSource ); createKeyframeTracks( animation, tracks ); } @@ -370,13 +363,13 @@ function buildAnimationChannel( channel, inputSource, outputSource ) { - var node = library.nodes[ channel.id ]; - var object3D = getNode( node.id ); - var transform = node.transforms[ channel.sid ]; - var defaultMatrix = node.matrix.clone().transpose(); - var time, stride; - var i, il, j, jl; - var data = {}; // the collada spec allows the animation of data in various ways. + const node = library.nodes[ channel.id ]; + const object3D = getNode( node.id ); + const transform = node.transforms[ channel.sid ]; + const defaultMatrix = node.matrix.clone().transpose(); + let time, stride; + let i, il, j, jl; + const data = {}; // the collada spec allows the animation of data in various ways. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic switch ( transform ) { @@ -390,8 +383,8 @@ if ( channel.arraySyntax === true ) { - var value = outputSource.array[ stride ]; - var index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ]; + const value = outputSource.array[ stride ]; + const index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ]; data[ time ][ index ] = value; } else { @@ -422,8 +415,8 @@ } - var keyframes = prepareAnimationData( data, defaultMatrix ); - var animation = { + const keyframes = prepareAnimationData( data, defaultMatrix ); + const animation = { name: object3D.uuid, keyframes: keyframes }; @@ -433,9 +426,9 @@ function prepareAnimationData( data, defaultMatrix ) { - var keyframes = []; // transfer data into a sortable array + const keyframes = []; // transfer data into a sortable array - for ( var time in data ) { + for ( const time in data ) { keyframes.push( { time: parseFloat( time ), @@ -447,7 +440,7 @@ keyframes.sort( ascending ); // now we clean up all animation data, so we can use them for keyframe tracks - for ( var i = 0; i < 16; i ++ ) { + for ( let i = 0; i < 16; i ++ ) { transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] ); @@ -463,24 +456,24 @@ } - var position = new THREE.Vector3(); - var scale = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); + const position = new THREE.Vector3(); + const scale = new THREE.Vector3(); + const quaternion = new THREE.Quaternion(); function createKeyframeTracks( animation, tracks ) { - var keyframes = animation.keyframes; - var name = animation.name; - var times = []; - var positionData = []; - var quaternionData = []; - var scaleData = []; + const keyframes = animation.keyframes; + const name = animation.name; + const times = []; + const positionData = []; + const quaternionData = []; + const scaleData = []; - for ( var i = 0, l = keyframes.length; i < l; i ++ ) { + for ( let i = 0, l = keyframes.length; i < l; i ++ ) { - var keyframe = keyframes[ i ]; - var time = keyframe.time; - var value = keyframe.value; + const keyframe = keyframes[ i ]; + const time = keyframe.time; + const value = keyframe.value; matrix.fromArray( value ).transpose(); matrix.decompose( position, quaternion, scale ); times.push( time ); @@ -499,9 +492,9 @@ function transformAnimationData( keyframes, property, defaultValue ) { - var keyframe; - var empty = true; - var i, l; // check, if values of a property are missing in our keyframes + let keyframe; + let empty = true; + let i, l; // check, if values of a property are missing in our keyframes for ( i = 0, l = keyframes.length; i < l; i ++ ) { @@ -540,11 +533,11 @@ function createMissingKeyframes( keyframes, property ) { - var prev, next; + let prev, next; - for ( var i = 0, l = keyframes.length; i < l; i ++ ) { + for ( let i = 0, l = keyframes.length; i < l; i ++ ) { - var keyframe = keyframes[ i ]; + const keyframe = keyframes[ i ]; if ( keyframe.value[ property ] === null ) { @@ -577,7 +570,7 @@ while ( i >= 0 ) { - var keyframe = keyframes[ i ]; + const keyframe = keyframes[ i ]; if ( keyframe.value[ property ] !== null ) return keyframe; i --; @@ -591,7 +584,7 @@ while ( i < keyframes.length ) { - var keyframe = keyframes[ i ]; + const keyframe = keyframes[ i ]; if ( keyframe.value[ property ] !== null ) return keyframe; i ++; @@ -617,16 +610,16 @@ function parseAnimationClip( xml ) { - var data = { + const data = { name: xml.getAttribute( 'id' ) || 'default', start: parseFloat( xml.getAttribute( 'start' ) || 0 ), end: parseFloat( xml.getAttribute( 'end' ) || 0 ), animations: [] }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -645,16 +638,16 @@ function buildAnimationClip( data ) { - var tracks = []; - var name = data.name; - var duration = data.end - data.start || - 1; - var animations = data.animations; + const tracks = []; + const name = data.name; + const duration = data.end - data.start || - 1; + const animations = data.animations; - for ( var i = 0, il = animations.length; i < il; i ++ ) { + for ( let i = 0, il = animations.length; i < il; i ++ ) { - var animationTracks = getAnimation( animations[ i ] ); + const animationTracks = getAnimation( animations[ i ] ); - for ( var j = 0, jl = animationTracks.length; j < jl; j ++ ) { + for ( let j = 0, jl = animationTracks.length; j < jl; j ++ ) { tracks.push( animationTracks[ j ] ); @@ -675,11 +668,11 @@ function parseController( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -705,13 +698,13 @@ function parseSkin( xml ) { - var data = { + const data = { sources: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -721,7 +714,7 @@ break; case 'source': - var id = child.getAttribute( 'id' ); + const id = child.getAttribute( 'id' ); data.sources[ id ] = parseSource( child ); break; @@ -743,20 +736,20 @@ function parseJoints( xml ) { - var data = { + const data = { inputs: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'input': - var semantic = child.getAttribute( 'semantic' ); - var id = parseId( child.getAttribute( 'source' ) ); + const semantic = child.getAttribute( 'semantic' ); + const id = parseId( child.getAttribute( 'source' ) ); data.inputs[ semantic ] = id; break; @@ -770,21 +763,21 @@ function parseVertexWeights( xml ) { - var data = { + const data = { inputs: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'input': - var semantic = child.getAttribute( 'semantic' ); - var id = parseId( child.getAttribute( 'source' ) ); - var offset = parseInt( child.getAttribute( 'offset' ) ); + const semantic = child.getAttribute( 'semantic' ); + const id = parseId( child.getAttribute( 'source' ) ); + const offset = parseInt( child.getAttribute( 'offset' ) ); data.inputs[ semantic ] = { id: id, offset: offset @@ -809,10 +802,10 @@ function buildController( data ) { - var build = { + const build = { id: data.id }; - var geometry = library.geometries[ build.id ]; + const geometry = library.geometries[ build.id ]; if ( data.skin !== undefined ) { @@ -829,8 +822,8 @@ function buildSkin( data ) { - var BONE_LIMIT = 4; - var build = { + const BONE_LIMIT = 4; + const build = { joints: [], // this must be an array to preserve the joint order indices: { @@ -842,29 +835,29 @@ stride: BONE_LIMIT } }; - var sources = data.sources; - var vertexWeights = data.vertexWeights; - var vcount = vertexWeights.vcount; - var v = vertexWeights.v; - var jointOffset = vertexWeights.inputs.JOINT.offset; - var weightOffset = vertexWeights.inputs.WEIGHT.offset; - var jointSource = data.sources[ data.joints.inputs.JOINT ]; - var inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ]; - var weights = sources[ vertexWeights.inputs.WEIGHT.id ].array; - var stride = 0; - var i, j, l; // procces skin data for each vertex + const sources = data.sources; + const vertexWeights = data.vertexWeights; + const vcount = vertexWeights.vcount; + const v = vertexWeights.v; + const jointOffset = vertexWeights.inputs.JOINT.offset; + const weightOffset = vertexWeights.inputs.WEIGHT.offset; + const jointSource = data.sources[ data.joints.inputs.JOINT ]; + const inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ]; + const weights = sources[ vertexWeights.inputs.WEIGHT.id ].array; + let stride = 0; + let i, j, l; // procces skin data for each vertex for ( i = 0, l = vcount.length; i < l; i ++ ) { - var jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex + const jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex - var vertexSkinData = []; + const vertexSkinData = []; for ( j = 0; j < jointCount; j ++ ) { - var skinIndex = v[ stride + jointOffset ]; - var weightId = v[ stride + weightOffset ]; - var skinWeight = weights[ weightId ]; + const skinIndex = v[ stride + jointOffset ]; + const weightId = v[ stride + weightOffset ]; + const skinWeight = weights[ weightId ]; vertexSkinData.push( { index: skinIndex, weight: skinWeight @@ -880,7 +873,7 @@ for ( j = 0; j < BONE_LIMIT; j ++ ) { - var d = vertexSkinData[ j ]; + const d = vertexSkinData[ j ]; if ( d !== undefined ) { @@ -912,8 +905,8 @@ for ( i = 0, l = jointSource.array.length; i < l; i ++ ) { - var name = jointSource.array[ i ]; - var boneInverse = new THREE.Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose(); + const name = jointSource.array[ i ]; + const boneInverse = new THREE.Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose(); build.joints.push( { name: name, boneInverse: boneInverse @@ -940,7 +933,7 @@ function parseImage( xml ) { - var data = { + const data = { init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent }; library.images[ xml.getAttribute( 'id' ) ] = data; @@ -956,7 +949,7 @@ function getImage( id ) { - var data = library.images[ id ]; + const data = library.images[ id ]; if ( data !== undefined ) { @@ -972,11 +965,11 @@ function parseEffect( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -995,14 +988,14 @@ function parseEffectProfileCOMMON( xml ) { - var data = { + const data = { surfaces: {}, samplers: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1029,11 +1022,11 @@ function parseEffectNewparam( xml, data ) { - var sid = xml.getAttribute( 'sid' ); + const sid = xml.getAttribute( 'sid' ); - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1054,11 +1047,11 @@ function parseEffectSurface( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1077,11 +1070,11 @@ function parseEffectSampler( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1100,11 +1093,11 @@ function parseEffectTechnique( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1127,11 +1120,11 @@ function parseEffectParameters( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1163,11 +1156,11 @@ function parseEffectParameter( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1197,13 +1190,13 @@ function parseEffectParameterTexture( xml ) { - var data = { + const data = { technique: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1222,9 +1215,9 @@ function parseEffectParameterTextureExtra( xml, data ) { - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1241,9 +1234,9 @@ function parseEffectParameterTextureExtraTechnique( xml, data ) { - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1282,11 +1275,11 @@ function parseEffectExtra( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1305,11 +1298,11 @@ function parseEffectExtraTechnique( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1341,13 +1334,13 @@ function parseMaterial( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ) }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1366,8 +1359,8 @@ function getTextureLoader( image ) { - var loader; - var extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/ + let loader; + let extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/ extension = extension.toLowerCase(); @@ -1388,10 +1381,10 @@ function buildMaterial( data ) { - var effect = getEffect( data.url ); - var technique = effect.profile.technique; - var extra = effect.profile.extra; - var material; + const effect = getEffect( data.url ); + const technique = effect.profile.technique; + const extra = effect.profile.extra; + let material; switch ( technique.type ) { @@ -1414,12 +1407,12 @@ function getTexture( textureObject ) { - var sampler = effect.profile.samplers[ textureObject.id ]; - var image = null; // get image + const sampler = effect.profile.samplers[ textureObject.id ]; + let image = null; // get image if ( sampler !== undefined ) { - var surface = effect.profile.surfaces[ sampler.source ]; + const surface = effect.profile.surfaces[ sampler.source ]; image = getImage( surface.init_from ); } else { @@ -1432,16 +1425,16 @@ if ( image !== null ) { - var loader = getTextureLoader( image ); + const loader = getTextureLoader( image ); if ( loader !== undefined ) { - var texture = loader.load( image ); - var extra = textureObject.extra; + const texture = loader.load( image ); + const extra = textureObject.extra; if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) { - var technique = extra.technique; + const technique = extra.technique; texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping; texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping; texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 ); @@ -1472,11 +1465,11 @@ } - var parameters = technique.parameters; + const parameters = technique.parameters; - for ( var key in parameters ) { + for ( const key in parameters ) { - var parameter = parameters[ key ]; + const parameter = parameters[ key ]; switch ( key ) { @@ -1512,8 +1505,8 @@ } // - var transparent = parameters[ 'transparent' ]; - var transparency = parameters[ 'transparency' ]; // does not exist but + let transparent = parameters[ 'transparent' ]; + let transparency = parameters[ 'transparency' ]; // does not exist but if ( transparency === undefined && transparent ) { @@ -1545,7 +1538,7 @@ } else { - var color = transparent.data.color; + const color = transparent.data.color; switch ( transparent.opaque ) { @@ -1596,13 +1589,13 @@ function parseCamera( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ) }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1621,9 +1614,9 @@ function parseCameraOptics( xml ) { - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; switch ( child.nodeName ) { @@ -1640,11 +1633,11 @@ function parseCameraTechnique( xml ) { - var data = {}; + const data = {}; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; switch ( child.nodeName ) { @@ -1664,11 +1657,11 @@ function parseCameraParameters( xml ) { - var data = {}; + const data = {}; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; switch ( child.nodeName ) { @@ -1692,7 +1685,7 @@ function buildCamera( data ) { - var camera; + let camera; switch ( data.optics.technique ) { @@ -1701,9 +1694,9 @@ break; case 'orthographic': - var ymag = data.optics.parameters.ymag; - var xmag = data.optics.parameters.xmag; - var aspectRatio = data.optics.parameters.aspect_ratio; + let ymag = data.optics.parameters.ymag; + let xmag = data.optics.parameters.xmag; + const aspectRatio = data.optics.parameters.aspect_ratio; xmag = xmag === undefined ? ymag * aspectRatio : xmag; ymag = ymag === undefined ? xmag / aspectRatio : ymag; xmag *= 0.5; @@ -1725,7 +1718,7 @@ function getCamera( id ) { - var data = library.cameras[ id ]; + const data = library.cameras[ id ]; if ( data !== undefined ) { @@ -1741,11 +1734,11 @@ function parseLight( xml ) { - var data = {}; + let data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1764,11 +1757,11 @@ function parseLightTechnique( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1790,17 +1783,17 @@ function parseLightParameters( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'color': - var array = parseFloats( child.textContent ); + const array = parseFloats( child.textContent ); data.color = new THREE.Color().fromArray( array ); break; @@ -1809,7 +1802,7 @@ break; case 'quadratic_attenuation': - var f = parseFloat( child.textContent ); + const f = parseFloat( child.textContent ); data.distance = f ? Math.sqrt( 1 / f ) : 0; break; @@ -1823,7 +1816,7 @@ function buildLight( data ) { - var light; + let light; switch ( data.technique ) { @@ -1853,7 +1846,7 @@ function getLight( id ) { - var data = library.lights[ id ]; + const data = library.lights[ id ]; if ( data !== undefined ) { @@ -1869,21 +1862,21 @@ function parseGeometry( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ), sources: {}, vertices: {}, primitives: [] }; - var mesh = getElementsByTagName( xml, 'mesh' )[ 0 ]; // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep + const mesh = getElementsByTagName( xml, 'mesh' )[ 0 ]; // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep if ( mesh === undefined ) return; - for ( var i = 0; i < mesh.childNodes.length; i ++ ) { + for ( let i = 0; i < mesh.childNodes.length; i ++ ) { - var child = mesh.childNodes[ i ]; + const child = mesh.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; - var id = child.getAttribute( 'id' ); + const id = child.getAttribute( 'id' ); switch ( child.nodeName ) { @@ -1920,14 +1913,14 @@ function parseSource( xml ) { - var data = { + const data = { array: [], stride: 3 }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -1941,7 +1934,7 @@ break; case 'technique_common': - var accessor = getElementsByTagName( child, 'accessor' )[ 0 ]; + const accessor = getElementsByTagName( child, 'accessor' )[ 0 ]; if ( accessor !== undefined ) { @@ -1961,11 +1954,11 @@ function parseGeometryVertices( xml ) { - var data = {}; + const data = {}; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) ); @@ -1977,7 +1970,7 @@ function parseGeometryPrimitive( xml ) { - var primitive = { + const primitive = { type: xml.nodeName, material: xml.getAttribute( 'material' ), count: parseInt( xml.getAttribute( 'count' ) ), @@ -1986,19 +1979,19 @@ hasUV: false }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'input': - var id = parseId( child.getAttribute( 'source' ) ); - var semantic = child.getAttribute( 'semantic' ); - var offset = parseInt( child.getAttribute( 'offset' ) ); - var set = parseInt( child.getAttribute( 'set' ) ); - var inputname = set > 0 ? semantic + set : semantic; + const id = parseId( child.getAttribute( 'source' ) ); + const semantic = child.getAttribute( 'semantic' ); + const offset = parseInt( child.getAttribute( 'offset' ) ); + const set = parseInt( child.getAttribute( 'set' ) ); + const inputname = set > 0 ? semantic + set : semantic; primitive.inputs[ inputname ] = { id: id, offset: offset @@ -2025,11 +2018,11 @@ function groupPrimitives( primitives ) { - var build = {}; + const build = {}; - for ( var i = 0; i < primitives.length; i ++ ) { + for ( let i = 0; i < primitives.length; i ++ ) { - var primitive = primitives[ i ]; + const primitive = primitives[ i ]; if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = []; build[ primitive.type ].push( primitive ); @@ -2041,11 +2034,11 @@ function checkUVCoordinates( primitives ) { - var count = 0; + let count = 0; - for ( var i = 0, l = primitives.length; i < l; i ++ ) { + for ( let i = 0, l = primitives.length; i < l; i ++ ) { - var primitive = primitives[ i ]; + const primitive = primitives[ i ]; if ( primitive.hasUV === true ) { @@ -2065,18 +2058,18 @@ function buildGeometry( data ) { - var build = {}; - var sources = data.sources; - var vertices = data.vertices; - var primitives = data.primitives; + const build = {}; + const sources = data.sources; + const vertices = data.vertices; + const primitives = data.primitives; if ( primitives.length === 0 ) return {}; // our goal is to create one buffer geometry for a single type of primitives // first, we group all primitives by their type - var groupedPrimitives = groupPrimitives( primitives ); + const groupedPrimitives = groupPrimitives( primitives ); - for ( var type in groupedPrimitives ) { + for ( const type in groupedPrimitives ) { - var primitiveType = groupedPrimitives[ type ]; // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines) + const primitiveType = groupedPrimitives[ type ]; // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines) checkUVCoordinates( primitiveType ); // third, create a buffer geometry for each type of primitives @@ -2090,45 +2083,45 @@ function buildGeometryType( primitives, sources, vertices ) { - var build = {}; - var position = { + const build = {}; + const position = { array: [], stride: 0 }; - var normal = { + const normal = { array: [], stride: 0 }; - var uv = { + const uv = { array: [], stride: 0 }; - var uv2 = { + const uv2 = { array: [], stride: 0 }; - var color = { + const color = { array: [], stride: 0 }; - var skinIndex = { + const skinIndex = { array: [], stride: 4 }; - var skinWeight = { + const skinWeight = { array: [], stride: 4 }; - var geometry = new THREE.BufferGeometry(); - var materialKeys = []; - var start = 0; + const geometry = new THREE.BufferGeometry(); + const materialKeys = []; + let start = 0; - for ( var p = 0; p < primitives.length; p ++ ) { + for ( let p = 0; p < primitives.length; p ++ ) { - var primitive = primitives[ p ]; - var inputs = primitive.inputs; // groups + const primitive = primitives[ p ]; + const inputs = primitive.inputs; // groups - var count = 0; + let count = 0; switch ( primitive.type ) { @@ -2142,9 +2135,9 @@ break; case 'polylist': - for ( var g = 0; g < primitive.count; g ++ ) { + for ( let g = 0; g < primitive.count; g ++ ) { - var vc = primitive.vcount[ g ]; + const vc = primitive.vcount[ g ]; switch ( vc ) { @@ -2184,21 +2177,21 @@ } // geometry data - for ( var name in inputs ) { + for ( const name in inputs ) { - var input = inputs[ name ]; + const input = inputs[ name ]; switch ( name ) { case 'VERTEX': - for ( var key in vertices ) { + for ( const key in vertices ) { - var id = vertices[ key ]; + const id = vertices[ key ]; switch ( key ) { case 'POSITION': - var prevLength = position.array.length; + const prevLength = position.array.length; buildGeometryData( primitive, sources[ id ], input.offset, position.array ); position.stride = sources[ id ].stride; @@ -2212,9 +2205,9 @@ if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) { - var count = ( position.array.length - prevLength ) / position.stride; + const count = ( position.array.length - prevLength ) / position.stride; - for ( var i = 0; i < count; i ++ ) { + for ( let i = 0; i < count; i ++ ) { // fill missing uv coordinates uv.array.push( 0, 0 ); @@ -2297,14 +2290,14 @@ function buildGeometryData( primitive, source, offset, array ) { - var indices = primitive.p; - var stride = primitive.stride; - var vcount = primitive.vcount; + const indices = primitive.p; + const stride = primitive.stride; + const vcount = primitive.vcount; function pushVector( i ) { - var index = indices[ i + offset ] * sourceStride; - var length = index + sourceStride; + let index = indices[ i + offset ] * sourceStride; + const length = index + sourceStride; for ( ; index < length; index ++ ) { @@ -2314,23 +2307,23 @@ } - var sourceArray = source.array; - var sourceStride = source.stride; + const sourceArray = source.array; + const sourceStride = source.stride; if ( primitive.vcount !== undefined ) { - var index = 0; + let index = 0; - for ( var i = 0, l = vcount.length; i < l; i ++ ) { + for ( let i = 0, l = vcount.length; i < l; i ++ ) { - var count = vcount[ i ]; + const count = vcount[ i ]; if ( count === 4 ) { - var a = index + stride * 0; - var b = index + stride * 1; - var c = index + stride * 2; - var d = index + stride * 3; + const a = index + stride * 0; + const b = index + stride * 1; + const c = index + stride * 2; + const d = index + stride * 3; pushVector( a ); pushVector( b ); pushVector( d ); @@ -2340,20 +2333,20 @@ } else if ( count === 3 ) { - var a = index + stride * 0; - var b = index + stride * 1; - var c = index + stride * 2; + const a = index + stride * 0; + const b = index + stride * 1; + const c = index + stride * 2; pushVector( a ); pushVector( b ); pushVector( c ); } else if ( count > 4 ) { - for ( var k = 1, kl = count - 2; k <= kl; k ++ ) { + for ( let k = 1, kl = count - 2; k <= kl; k ++ ) { - var a = index + stride * 0; - var b = index + stride * k; - var c = index + stride * ( k + 1 ); + const a = index + stride * 0; + const b = index + stride * k; + const c = index + stride * ( k + 1 ); pushVector( a ); pushVector( b ); pushVector( c ); @@ -2368,7 +2361,7 @@ } else { - for ( var i = 0, l = indices.length; i < l; i += stride ) { + for ( let i = 0, l = indices.length; i < l; i += stride ) { pushVector( i ); @@ -2387,15 +2380,15 @@ function parseKinematicsModel( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ) || '', joints: {}, links: [] }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -2427,9 +2420,9 @@ function parseKinematicsTechniqueCommon( xml, data ) { - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -2450,11 +2443,11 @@ function parseKinematicsJoint( xml ) { - var data; + let data; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -2472,9 +2465,9 @@ } - function parseKinematicsJointParameter( xml, data ) { + function parseKinematicsJointParameter( xml ) { - var data = { + const data = { sid: xml.getAttribute( 'sid' ), name: xml.getAttribute( 'name' ) || '', axis: new THREE.Vector3(), @@ -2488,21 +2481,21 @@ middlePosition: 0 }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'axis': - var array = parseFloats( child.textContent ); + const array = parseFloats( child.textContent ); data.axis.fromArray( array ); break; case 'limits': - var max = child.getElementsByTagName( 'max' )[ 0 ]; - var min = child.getElementsByTagName( 'min' )[ 0 ]; + const max = child.getElementsByTagName( 'max' )[ 0 ]; + const min = child.getElementsByTagName( 'min' )[ 0 ]; data.limits.max = parseFloat( max.textContent ); data.limits.min = parseFloat( min.textContent ); break; @@ -2526,16 +2519,16 @@ function parseKinematicsLink( xml ) { - var data = { + const data = { sid: xml.getAttribute( 'sid' ), name: xml.getAttribute( 'name' ) || '', attachments: [], transforms: [] }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -2560,15 +2553,15 @@ function parseKinematicsAttachment( xml ) { - var data = { + const data = { joint: xml.getAttribute( 'joint' ).split( '/' ).pop(), transforms: [], links: [] }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -2593,10 +2586,10 @@ function parseKinematicsTransform( xml ) { - var data = { + const data = { type: xml.nodeName }; - var array = parseFloats( xml.textContent ); + const array = parseFloats( xml.textContent ); switch ( data.type ) { @@ -2625,14 +2618,14 @@ function parsePhysicsModel( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ) || '', rigidBodies: {} }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -2652,9 +2645,9 @@ function parsePhysicsRigidBody( xml, data ) { - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -2671,9 +2664,9 @@ function parsePhysicsTechniqueCommon( xml, data ) { - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -2695,13 +2688,13 @@ function parseKinematicsScene( xml ) { - var data = { + const data = { bindJointAxis: [] }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { @@ -2720,21 +2713,21 @@ function parseKinematicsBindJointAxis( xml ) { - var data = { + const data = { target: xml.getAttribute( 'target' ).split( '/' ).pop() }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'axis': - var param = child.getElementsByTagName( 'param' )[ 0 ]; + const param = child.getElementsByTagName( 'param' )[ 0 ]; data.axis = param.textContent; - var tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ]; + const tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ]; data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 ); break; @@ -2761,26 +2754,26 @@ function setupKinematics() { - var kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ]; - var kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ]; - var visualSceneId = Object.keys( library.visualScenes )[ 0 ]; + const kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ]; + const kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ]; + const visualSceneId = Object.keys( library.visualScenes )[ 0 ]; if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return; - var kinematicsModel = getKinematicsModel( kinematicsModelId ); - var kinematicsScene = getKinematicsScene( kinematicsSceneId ); - var visualScene = getVisualScene( visualSceneId ); - var bindJointAxis = kinematicsScene.bindJointAxis; - var jointMap = {}; + const kinematicsModel = getKinematicsModel( kinematicsModelId ); + const kinematicsScene = getKinematicsScene( kinematicsSceneId ); + const visualScene = getVisualScene( visualSceneId ); + const bindJointAxis = kinematicsScene.bindJointAxis; + const jointMap = {}; - for ( var i = 0, l = bindJointAxis.length; i < l; i ++ ) { + for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) { - var axis = bindJointAxis[ i ]; // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix' + const axis = bindJointAxis[ i ]; // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix' - var targetElement = collada.querySelector( '[sid="' + axis.target + '"]' ); + const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' ); if ( targetElement ) { // get the parent of the transform element - var parentVisualElement = targetElement.parentElement; // connect the joint of the kinematics model with the element in the visual scene + const parentVisualElement = targetElement.parentElement; // connect the joint of the kinematics model with the element in the visual scene connect( axis.jointIndex, parentVisualElement ); @@ -2790,8 +2783,8 @@ function connect( jointIndex, visualElement ) { - var visualElementName = visualElement.getAttribute( 'name' ); - var joint = kinematicsModel.joints[ jointIndex ]; + const visualElementName = visualElement.getAttribute( 'name' ); + const joint = kinematicsModel.joints[ jointIndex ]; visualScene.traverse( function ( object ) { if ( object.name === visualElementName ) { @@ -2809,12 +2802,12 @@ } - var m0 = new THREE.Matrix4(); + const m0 = new THREE.Matrix4(); kinematics = { joints: kinematicsModel && kinematicsModel.joints, getJointValue: function ( jointIndex ) { - var jointData = jointMap[ jointIndex ]; + const jointData = jointMap[ jointIndex ]; if ( jointData ) { @@ -2829,11 +2822,11 @@ }, setJointValue: function ( jointIndex, value ) { - var jointData = jointMap[ jointIndex ]; + const jointData = jointMap[ jointIndex ]; if ( jointData ) { - var joint = jointData.joint; + const joint = jointData.joint; if ( value > joint.limits.max || value < joint.limits.min ) { @@ -2845,14 +2838,14 @@ } else { - var object = jointData.object; - var axis = joint.axis; - var transforms = jointData.transforms; + const object = jointData.object; + const axis = joint.axis; + const transforms = jointData.transforms; matrix.identity(); // each update, we have to apply all transforms in the correct order - for ( var i = 0; i < transforms.length; i ++ ) { + for ( let i = 0; i < transforms.length; i ++ ) { - var transform = transforms[ i ]; // if there is a connection of the transform node with a joint, apply the joint value + const transform = transforms[ i ]; // if there is a connection of the transform node with a joint, apply the joint value if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) { @@ -2917,19 +2910,20 @@ function buildTransformList( node ) { - var transforms = []; - var xml = collada.querySelector( '[id="' + node.id + '"]' ); + const transforms = []; + const xml = collada.querySelector( '[id="' + node.id + '"]' ); - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; + let array, vector; switch ( child.nodeName ) { case 'matrix': - var array = parseFloats( child.textContent ); - var matrix = new THREE.Matrix4().fromArray( array ).transpose(); + array = parseFloats( child.textContent ); + const matrix = new THREE.Matrix4().fromArray( array ).transpose(); transforms.push( { sid: child.getAttribute( 'sid' ), type: child.nodeName, @@ -2939,8 +2933,8 @@ case 'translate': case 'scale': - var array = parseFloats( child.textContent ); - var vector = new THREE.Vector3().fromArray( array ); + array = parseFloats( child.textContent ); + vector = new THREE.Vector3().fromArray( array ); transforms.push( { sid: child.getAttribute( 'sid' ), type: child.nodeName, @@ -2949,9 +2943,9 @@ break; case 'rotate': - var array = parseFloats( child.textContent ); - var vector = new THREE.Vector3().fromArray( array ); - var angle = THREE.MathUtils.degToRad( array[ 3 ] ); + array = parseFloats( child.textContent ); + vector = new THREE.Vector3().fromArray( array ); + const angle = THREE.MathUtils.degToRad( array[ 3 ] ); transforms.push( { sid: child.getAttribute( 'sid' ), type: child.nodeName, @@ -2971,11 +2965,11 @@ function prepareNodes( xml ) { - var elements = xml.getElementsByTagName( 'node' ); // ensure all node elements have id attributes + const elements = xml.getElementsByTagName( 'node' ); // ensure all node elements have id attributes - for ( var i = 0; i < elements.length; i ++ ) { + for ( let i = 0; i < elements.length; i ++ ) { - var element = elements[ i ]; + const element = elements[ i ]; if ( element.hasAttribute( 'id' ) === false ) { @@ -2987,12 +2981,12 @@ } - var matrix = new THREE.Matrix4(); - var vector = new THREE.Vector3(); + const matrix = new THREE.Matrix4(); + const vector = new THREE.Vector3(); function parseNode( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ) || '', type: xml.getAttribute( 'type' ), id: xml.getAttribute( 'id' ), @@ -3007,10 +3001,11 @@ transforms: {} }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; + let array; switch ( child.nodeName ) { @@ -3040,27 +3035,27 @@ break; case 'matrix': - var array = parseFloats( child.textContent ); + array = parseFloats( child.textContent ); data.matrix.multiply( matrix.fromArray( array ).transpose() ); data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName; break; case 'translate': - var array = parseFloats( child.textContent ); + array = parseFloats( child.textContent ); vector.fromArray( array ); data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) ); data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName; break; case 'rotate': - var array = parseFloats( child.textContent ); - var angle = THREE.MathUtils.degToRad( array[ 3 ] ); + array = parseFloats( child.textContent ); + const angle = THREE.MathUtils.degToRad( array[ 3 ] ); data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) ); data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName; break; case 'scale': - var array = parseFloats( child.textContent ); + array = parseFloats( child.textContent ); data.matrix.scale( vector.fromArray( array ) ); data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName; break; @@ -3091,26 +3086,26 @@ function parseNodeInstance( xml ) { - var data = { + const data = { id: parseId( xml.getAttribute( 'url' ) ), materials: {}, skeletons: [] }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; switch ( child.nodeName ) { case 'bind_material': - var instances = child.getElementsByTagName( 'instance_material' ); + const instances = child.getElementsByTagName( 'instance_material' ); - for ( var j = 0; j < instances.length; j ++ ) { + for ( let j = 0; j < instances.length; j ++ ) { - var instance = instances[ j ]; - var symbol = instance.getAttribute( 'symbol' ); - var target = instance.getAttribute( 'target' ); + const instance = instances[ j ]; + const symbol = instance.getAttribute( 'symbol' ); + const target = instance.getAttribute( 'target' ); data.materials[ symbol ] = parseId( target ); } @@ -3134,15 +3129,15 @@ function buildSkeleton( skeletons, joints ) { - var boneData = []; - var sortedBoneData = []; - var i, j, data; // a skeleton can have multiple root bones. collada expresses this + const boneData = []; + const sortedBoneData = []; + let i, j, data; // a skeleton can have multiple root bones. collada expresses this // situtation with multiple "skeleton" tags per controller instance for ( i = 0; i < skeletons.length; i ++ ) { - var skeleton = skeletons[ i ]; - var root; + const skeleton = skeletons[ i ]; + let root; if ( hasNode( skeleton ) ) { @@ -3152,16 +3147,16 @@ } else if ( hasVisualScene( skeleton ) ) { // handle case where the skeleton refers to the visual scene (#13335) - var visualScene = library.visualScenes[ skeleton ]; - var children = visualScene.children; + const visualScene = library.visualScenes[ skeleton ]; + const children = visualScene.children; - for ( var j = 0; j < children.length; j ++ ) { + for ( let j = 0; j < children.length; j ++ ) { - var child = children[ j ]; + const child = children[ j ]; if ( child.type === 'JOINT' ) { - var root = getNode( child.id ); + const root = getNode( child.id ); buildBoneHierarchy( root, joints, boneData ); } @@ -3210,8 +3205,8 @@ } // setup arrays for skeleton creation - var bones = []; - var boneInverses = []; + const bones = []; + const boneInverses = []; for ( i = 0; i < sortedBoneData.length; i ++ ) { @@ -3232,11 +3227,11 @@ if ( object.isBone === true ) { - var boneInverse; // retrieve the boneInverse from the controller data + let boneInverse; // retrieve the boneInverse from the controller data - for ( var i = 0; i < joints.length; i ++ ) { + for ( let i = 0; i < joints.length; i ++ ) { - var joint = joints[ i ]; + const joint = joints[ i ]; if ( joint.name === object.name ) { @@ -3272,26 +3267,26 @@ function buildNode( data ) { - var objects = []; - var matrix = data.matrix; - var nodes = data.nodes; - var type = data.type; - var instanceCameras = data.instanceCameras; - var instanceControllers = data.instanceControllers; - var instanceLights = data.instanceLights; - var instanceGeometries = data.instanceGeometries; - var instanceNodes = data.instanceNodes; // nodes + const objects = []; + const matrix = data.matrix; + const nodes = data.nodes; + const type = data.type; + const instanceCameras = data.instanceCameras; + const instanceControllers = data.instanceControllers; + const instanceLights = data.instanceLights; + const instanceGeometries = data.instanceGeometries; + const instanceNodes = data.instanceNodes; // nodes - for ( var i = 0, l = nodes.length; i < l; i ++ ) { + for ( let i = 0, l = nodes.length; i < l; i ++ ) { objects.push( getNode( nodes[ i ] ) ); } // instance cameras - for ( var i = 0, l = instanceCameras.length; i < l; i ++ ) { + for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) { - var instanceCamera = getCamera( instanceCameras[ i ] ); + const instanceCamera = getCamera( instanceCameras[ i ] ); if ( instanceCamera !== null ) { @@ -3302,19 +3297,19 @@ } // instance controllers - for ( var i = 0, l = instanceControllers.length; i < l; i ++ ) { + for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) { - var instance = instanceControllers[ i ]; - var controller = getController( instance.id ); - var geometries = getGeometry( controller.id ); - var newObjects = buildObjects( geometries, instance.materials ); - var skeletons = instance.skeletons; - var joints = controller.skin.joints; - var skeleton = buildSkeleton( skeletons, joints ); + const instance = instanceControllers[ i ]; + const controller = getController( instance.id ); + const geometries = getGeometry( controller.id ); + const newObjects = buildObjects( geometries, instance.materials ); + const skeletons = instance.skeletons; + const joints = controller.skin.joints; + const skeleton = buildSkeleton( skeletons, joints ); - for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) { + for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) { - var object = newObjects[ j ]; + const object = newObjects[ j ]; if ( object.isSkinnedMesh ) { @@ -3330,9 +3325,9 @@ } // instance lights - for ( var i = 0, l = instanceLights.length; i < l; i ++ ) { + for ( let i = 0, l = instanceLights.length; i < l; i ++ ) { - var instanceLight = getLight( instanceLights[ i ] ); + const instanceLight = getLight( instanceLights[ i ] ); if ( instanceLight !== null ) { @@ -3343,15 +3338,15 @@ } // instance geometries - for ( var i = 0, l = instanceGeometries.length; i < l; i ++ ) { + for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) { - var instance = instanceGeometries[ i ]; // a single geometry instance in collada can lead to multiple object3Ds. + const instance = instanceGeometries[ i ]; // a single geometry instance in collada can lead to multiple object3Ds. // this is the case when primitives are combined like triangles and lines - var geometries = getGeometry( instance.id ); - var newObjects = buildObjects( geometries, instance.materials ); + const geometries = getGeometry( instance.id ); + const newObjects = buildObjects( geometries, instance.materials ); - for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) { + for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) { objects.push( newObjects[ j ] ); @@ -3360,13 +3355,13 @@ } // instance nodes - for ( var i = 0, l = instanceNodes.length; i < l; i ++ ) { + for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) { objects.push( getNode( instanceNodes[ i ] ).clone() ); } - var object; + let object; if ( nodes.length === 0 && objects.length === 1 ) { @@ -3376,7 +3371,7 @@ object = type === 'JOINT' ? new THREE.Bone() : new THREE.Group(); - for ( var i = 0; i < objects.length; i ++ ) { + for ( let i = 0; i < objects.length; i ++ ) { object.add( objects[ i ] ); @@ -3391,17 +3386,17 @@ } - var fallbackMaterial = new THREE.MeshBasicMaterial( { + const fallbackMaterial = new THREE.MeshBasicMaterial( { color: 0xff00ff } ); function resolveMaterialBinding( keys, instanceMaterials ) { - var materials = []; + const materials = []; - for ( var i = 0, l = keys.length; i < l; i ++ ) { + for ( let i = 0, l = keys.length; i < l; i ++ ) { - var id = instanceMaterials[ keys[ i ] ]; + const id = instanceMaterials[ keys[ i ] ]; if ( id === undefined ) { @@ -3422,12 +3417,12 @@ function buildObjects( geometries, instanceMaterials ) { - var objects = []; + const objects = []; - for ( var type in geometries ) { + for ( const type in geometries ) { - var geometry = geometries[ type ]; - var materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials ); // handle case if no materials are defined + const geometry = geometries[ type ]; + const materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials ); // handle case if no materials are defined if ( materials.length === 0 ) { @@ -3444,11 +3439,11 @@ } // regard skinning - var skinning = geometry.data.attributes.skinIndex !== undefined; + const skinning = geometry.data.attributes.skinIndex !== undefined; if ( skinning ) { - for ( var i = 0, l = materials.length; i < l; i ++ ) { + for ( let i = 0, l = materials.length; i < l; i ++ ) { materials[ i ].skinning = true; @@ -3457,9 +3452,9 @@ } // choose between a single or multi materials (material array) - var material = materials.length === 1 ? materials[ 0 ] : materials; // now create a specific 3D object + const material = materials.length === 1 ? materials[ 0 ] : materials; // now create a specific 3D object - var object; + let object; switch ( type ) { @@ -3510,14 +3505,14 @@ function parseVisualScene( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ), children: [] }; prepareNodes( xml ); - var elements = getElementsByTagName( xml, 'node' ); + const elements = getElementsByTagName( xml, 'node' ); - for ( var i = 0; i < elements.length; i ++ ) { + for ( let i = 0; i < elements.length; i ++ ) { data.children.push( parseNode( elements[ i ] ) ); @@ -3529,13 +3524,13 @@ function buildVisualScene( data ) { - var group = new THREE.Group(); + const group = new THREE.Group(); group.name = data.name; - var children = data.children; + const children = data.children; - for ( var i = 0; i < children.length; i ++ ) { + for ( let i = 0; i < children.length; i ++ ) { - var child = children[ i ]; + const child = children[ i ]; group.add( getNode( child.id ) ); } @@ -3559,27 +3554,27 @@ function parseScene( xml ) { - var instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ]; + const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ]; return getVisualScene( parseId( instance.getAttribute( 'url' ) ) ); } function setupAnimations() { - var clips = library.clips; + const clips = library.clips; if ( isEmpty( clips ) === true ) { if ( isEmpty( library.animations ) === false ) { // if there are animations but no clips, we create a default clip for playback - var tracks = []; + const tracks = []; - for ( var id in library.animations ) { + for ( const id in library.animations ) { - var animationTracks = getAnimation( id ); + const animationTracks = getAnimation( id ); - for ( var i = 0, l = animationTracks.length; i < l; i ++ ) { + for ( let i = 0, l = animationTracks.length; i < l; i ++ ) { tracks.push( animationTracks[ i ] ); @@ -3593,7 +3588,7 @@ } else { - for ( var id in clips ) { + for ( const id in clips ) { animations.push( getAnimationClip( id ) ); @@ -3607,12 +3602,12 @@ function parserErrorToText( parserError ) { - var result = ''; - var stack = [ parserError ]; + let result = ''; + const stack = [ parserError ]; while ( stack.length ) { - var node = stack.shift(); + const node = stack.shift(); if ( node.nodeType === Node.TEXT_NODE ) { @@ -3639,15 +3634,15 @@ } - var xml = new DOMParser().parseFromString( text, 'application/xml' ); - var collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ]; - var parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ]; + const xml = new DOMParser().parseFromString( text, 'application/xml' ); + const collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ]; + const parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ]; if ( parserError !== undefined ) { // Chrome will return parser error with a div in it - var errorElement = getElementsByTagName( parserError, 'div' )[ 0 ]; - var errorText; + const errorElement = getElementsByTagName( parserError, 'div' )[ 0 ]; + let errorText; if ( errorElement ) { @@ -3665,12 +3660,12 @@ } // metadata - var version = collada.getAttribute( 'version' ); + const version = collada.getAttribute( 'version' ); console.log( 'THREE.ColladaLoader: File version', version ); - var asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] ); - var textureLoader = new THREE.TextureLoader( this.manager ); + const asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] ); + const textureLoader = new THREE.TextureLoader( this.manager ); textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin ); - var tgaLoader; + let tgaLoader; if ( THREE.TGALoader ) { @@ -3680,11 +3675,11 @@ } // - var animations = []; - var kinematics = {}; - var count = 0; // + const animations = []; + let kinematics = {}; + let count = 0; // - var library = { + const library = { animations: {}, clips: {}, controllers: {}, @@ -3726,7 +3721,7 @@ buildLibrary( library.visualScenes, buildVisualScene ); setupAnimations(); setupKinematics(); - var scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] ); + const scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] ); scene.animations = animations; if ( asset.upAxis === 'Z_UP' ) { @@ -3750,7 +3745,8 @@ }; } - } ); + + } THREE.ColladaLoader = ColladaLoader; diff --git a/examples/js/loaders/DDSLoader.js b/examples/js/loaders/DDSLoader.js index 1dea03395fe52b..8baa500794ba60 100644 --- a/examples/js/loaders/DDSLoader.js +++ b/examples/js/loaders/DDSLoader.js @@ -1,16 +1,16 @@ ( function () { - var DDSLoader = function ( manager ) { + class DDSLoader extends THREE.CompressedTextureLoader { - THREE.CompressedTextureLoader.call( this, manager ); + constructor( manager ) { - }; + super( manager ); - DDSLoader.prototype = Object.assign( Object.create( THREE.CompressedTextureLoader.prototype ), { - constructor: DDSLoader, - parse: function ( buffer, loadMipmaps ) { + } + + parse( buffer, loadMipmaps ) { - var dds = { + const dds = { mipmaps: [], width: 0, height: 0, @@ -21,31 +21,31 @@ // All values and structures referenced from: // http://msdn.microsoft.com/en-us/library/bb943991.aspx/ - var DDS_MAGIC = 0x20534444; // var DDSD_CAPS = 0x1; - // var DDSD_HEIGHT = 0x2; - // var DDSD_WIDTH = 0x4; - // var DDSD_PITCH = 0x8; - // var DDSD_PIXELFORMAT = 0x1000; - - var DDSD_MIPMAPCOUNT = 0x20000; // var DDSD_LINEARSIZE = 0x80000; - // var DDSD_DEPTH = 0x800000; - // var DDSCAPS_COMPLEX = 0x8; - // var DDSCAPS_MIPMAP = 0x400000; - // var DDSCAPS_TEXTURE = 0x1000; - - var DDSCAPS2_CUBEMAP = 0x200; - var DDSCAPS2_CUBEMAP_POSITIVEX = 0x400; - var DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800; - var DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000; - var DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000; - var DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000; - var DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000; // var DDSCAPS2_VOLUME = 0x200000; - // var DDPF_ALPHAPIXELS = 0x1; - // var DDPF_ALPHA = 0x2; - - var DDPF_FOURCC = 0x4; // var DDPF_RGB = 0x40; - // var DDPF_YUV = 0x200; - // var DDPF_LUMINANCE = 0x20000; + const DDS_MAGIC = 0x20534444; // let DDSD_CAPS = 0x1; + // let DDSD_HEIGHT = 0x2; + // let DDSD_WIDTH = 0x4; + // let DDSD_PITCH = 0x8; + // let DDSD_PIXELFORMAT = 0x1000; + + const DDSD_MIPMAPCOUNT = 0x20000; // let DDSD_LINEARSIZE = 0x80000; + // let DDSD_DEPTH = 0x800000; + // let DDSCAPS_COMPLEX = 0x8; + // let DDSCAPS_MIPMAP = 0x400000; + // let DDSCAPS_TEXTURE = 0x1000; + + const DDSCAPS2_CUBEMAP = 0x200; + const DDSCAPS2_CUBEMAP_POSITIVEX = 0x400; + const DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800; + const DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000; + const DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000; + const DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000; + const DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000; // let DDSCAPS2_VOLUME = 0x200000; + // let DDPF_ALPHAPIXELS = 0x1; + // let DDPF_ALPHA = 0x2; + + const DDPF_FOURCC = 0x4; // let DDPF_RGB = 0x40; + // let DDPF_YUV = 0x200; + // let DDPF_LUMINANCE = 0x20000; function fourCCToInt32( value ) { @@ -61,23 +61,23 @@ function loadARGBMip( buffer, dataOffset, width, height ) { - var dataLength = width * height * 4; - var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength ); - var byteArray = new Uint8Array( dataLength ); - var dst = 0; - var src = 0; + const dataLength = width * height * 4; + const srcBuffer = new Uint8Array( buffer, dataOffset, dataLength ); + const byteArray = new Uint8Array( dataLength ); + let dst = 0; + let src = 0; - for ( var y = 0; y < height; y ++ ) { + for ( let y = 0; y < height; y ++ ) { - for ( var x = 0; x < width; x ++ ) { + for ( let x = 0; x < width; x ++ ) { - var b = srcBuffer[ src ]; + const b = srcBuffer[ src ]; src ++; - var g = srcBuffer[ src ]; + const g = srcBuffer[ src ]; src ++; - var r = srcBuffer[ src ]; + const r = srcBuffer[ src ]; src ++; - var a = srcBuffer[ src ]; + const a = srcBuffer[ src ]; src ++; byteArray[ dst ] = r; dst ++; //r @@ -99,32 +99,32 @@ } - var FOURCC_DXT1 = fourCCToInt32( 'DXT1' ); - var FOURCC_DXT3 = fourCCToInt32( 'DXT3' ); - var FOURCC_DXT5 = fourCCToInt32( 'DXT5' ); - var FOURCC_ETC1 = fourCCToInt32( 'ETC1' ); - var headerLengthInt = 31; // The header length in 32 bit ints + const FOURCC_DXT1 = fourCCToInt32( 'DXT1' ); + const FOURCC_DXT3 = fourCCToInt32( 'DXT3' ); + const FOURCC_DXT5 = fourCCToInt32( 'DXT5' ); + const FOURCC_ETC1 = fourCCToInt32( 'ETC1' ); + const headerLengthInt = 31; // The header length in 32 bit ints // Offsets into the header array - var off_magic = 0; - var off_size = 1; - var off_flags = 2; - var off_height = 3; - var off_width = 4; - var off_mipmapCount = 7; - var off_pfFlags = 20; - var off_pfFourCC = 21; - var off_RGBBitCount = 22; - var off_RBitMask = 23; - var off_GBitMask = 24; - var off_BBitMask = 25; - var off_ABitMask = 26; // var off_caps = 27; - - var off_caps2 = 28; // var off_caps3 = 29; - // var off_caps4 = 30; + const off_magic = 0; + const off_size = 1; + const off_flags = 2; + const off_height = 3; + const off_width = 4; + const off_mipmapCount = 7; + const off_pfFlags = 20; + const off_pfFourCC = 21; + const off_RGBBitCount = 22; + const off_RBitMask = 23; + const off_GBitMask = 24; + const off_BBitMask = 25; + const off_ABitMask = 26; // let off_caps = 27; + + const off_caps2 = 28; // let off_caps3 = 29; + // let off_caps4 = 30; // Parse header - var header = new Int32Array( buffer, 0, headerLengthInt ); + const header = new Int32Array( buffer, 0, headerLengthInt ); if ( header[ off_magic ] !== DDS_MAGIC ) { @@ -140,9 +140,9 @@ } - var blockBytes; - var fourCC = header[ off_pfFourCC ]; - var isRGBAUncompressed = false; + let blockBytes; + const fourCC = header[ off_pfFourCC ]; + let isRGBAUncompressed = false; switch ( fourCC ) { @@ -190,7 +190,7 @@ } - var caps2 = header[ off_caps2 ]; + const caps2 = header[ off_caps2 ]; dds.isCubemap = caps2 & DDSCAPS2_CUBEMAP ? true : false; if ( dds.isCubemap && ( ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEX ) || ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX ) || ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEY ) || ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY ) || ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ ) || ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ ) ) ) { @@ -202,30 +202,32 @@ dds.width = header[ off_width ]; dds.height = header[ off_height ]; - var dataOffset = header[ off_size ] + 4; // Extract mipmaps buffers + let dataOffset = header[ off_size ] + 4; // Extract mipmaps buffers - var faces = dds.isCubemap ? 6 : 1; + const faces = dds.isCubemap ? 6 : 1; - for ( var face = 0; face < faces; face ++ ) { + for ( let face = 0; face < faces; face ++ ) { - var width = dds.width; - var height = dds.height; + let width = dds.width; + let height = dds.height; - for ( var i = 0; i < dds.mipmapCount; i ++ ) { + for ( let i = 0; i < dds.mipmapCount; i ++ ) { + + let byteArray, dataLength; if ( isRGBAUncompressed ) { - var byteArray = loadARGBMip( buffer, dataOffset, width, height ); - var dataLength = byteArray.length; + byteArray = loadARGBMip( buffer, dataOffset, width, height ); + dataLength = byteArray.length; } else { - var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes; - var byteArray = new Uint8Array( buffer, dataOffset, dataLength ); + dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes; + byteArray = new Uint8Array( buffer, dataOffset, dataLength ); } - var mipmap = { + const mipmap = { 'data': byteArray, 'width': width, 'height': height @@ -242,7 +244,8 @@ return dds; } - } ); + + } THREE.DDSLoader = DDSLoader; diff --git a/examples/js/loaders/KMZLoader.js b/examples/js/loaders/KMZLoader.js index 43896622aafb80..047b3da006806b 100644 --- a/examples/js/loaders/KMZLoader.js +++ b/examples/js/loaders/KMZLoader.js @@ -1,17 +1,17 @@ ( function () { - var KMZLoader = function ( manager ) { + class KMZLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); + constructor( manager ) { - }; + super( manager ); - KMZLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: KMZLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new THREE.FileLoader( scope.manager ); + const scope = this; + const loader = new THREE.FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( scope.requestHeader ); @@ -40,12 +40,13 @@ }, onProgress, onError ); - }, - parse: function ( data ) { + } + + parse( data ) { function findFile( url ) { - for ( var path in zip ) { + for ( const path in zip ) { if ( path.substr( - url.length ) === url ) { @@ -57,15 +58,15 @@ } - var manager = new THREE.LoadingManager(); + const manager = new THREE.LoadingManager(); manager.setURLModifier( function ( url ) { - var image = findFile( url ); + const image = findFile( url ); if ( image ) { console.log( 'Loading', url ); - var blob = new Blob( [ image.buffer ], { + const blob = new Blob( [ image.buffer ], { type: 'application/octet-stream' } ); return URL.createObjectURL( blob ); @@ -76,17 +77,17 @@ } ); // - var zip = fflate.unzipSync( new Uint8Array( data ) ); // eslint-disable-line no-undef + const zip = fflate.unzipSync( new Uint8Array( data ) ); // eslint-disable-line no-undef if ( zip[ 'doc.kml' ] ) { - var xml = new DOMParser().parseFromString( fflate.strFromU8( zip[ 'doc.kml' ] ), 'application/xml' ); // eslint-disable-line no-undef + const xml = new DOMParser().parseFromString( fflate.strFromU8( zip[ 'doc.kml' ] ), 'application/xml' ); // eslint-disable-line no-undef - var model = xml.querySelector( 'Placemark Model Link href' ); + const model = xml.querySelector( 'Placemark Model Link href' ); if ( model ) { - var loader = new THREE.ColladaLoader( manager ); + const loader = new THREE.ColladaLoader( manager ); return loader.parse( fflate.strFromU8( zip[ model.textContent ] ) ); // eslint-disable-line no-undef } @@ -95,13 +96,13 @@ console.warn( 'KMZLoader: Missing doc.kml file.' ); - for ( var path in zip ) { + for ( const path in zip ) { - var extension = path.split( '.' ).pop().toLowerCase(); + const extension = path.split( '.' ).pop().toLowerCase(); if ( extension === 'dae' ) { - var loader = new THREE.ColladaLoader( manager ); + const loader = new THREE.ColladaLoader( manager ); return loader.parse( fflate.strFromU8( zip[ path ] ) ); // eslint-disable-line no-undef } @@ -116,7 +117,8 @@ }; } - } ); + + } THREE.KMZLoader = KMZLoader; diff --git a/examples/js/loaders/MD2Loader.js b/examples/js/loaders/MD2Loader.js index 55e9769c591681..436ff386ab0ab8 100644 --- a/examples/js/loaders/MD2Loader.js +++ b/examples/js/loaders/MD2Loader.js @@ -1,17 +1,19 @@ ( function () { - var MD2Loader = function ( manager ) { + const _normalData = [[ - 0.525731, 0.000000, 0.850651 ], [ - 0.442863, 0.238856, 0.864188 ], [ - 0.295242, 0.000000, 0.955423 ], [ - 0.309017, 0.500000, 0.809017 ], [ - 0.162460, 0.262866, 0.951056 ], [ 0.000000, 0.000000, 1.000000 ], [ 0.000000, 0.850651, 0.525731 ], [ - 0.147621, 0.716567, 0.681718 ], [ 0.147621, 0.716567, 0.681718 ], [ 0.000000, 0.525731, 0.850651 ], [ 0.309017, 0.500000, 0.809017 ], [ 0.525731, 0.000000, 0.850651 ], [ 0.295242, 0.000000, 0.955423 ], [ 0.442863, 0.238856, 0.864188 ], [ 0.162460, 0.262866, 0.951056 ], [ - 0.681718, 0.147621, 0.716567 ], [ - 0.809017, 0.309017, 0.500000 ], [ - 0.587785, 0.425325, 0.688191 ], [ - 0.850651, 0.525731, 0.000000 ], [ - 0.864188, 0.442863, 0.238856 ], [ - 0.716567, 0.681718, 0.147621 ], [ - 0.688191, 0.587785, 0.425325 ], [ - 0.500000, 0.809017, 0.309017 ], [ - 0.238856, 0.864188, 0.442863 ], [ - 0.425325, 0.688191, 0.587785 ], [ - 0.716567, 0.681718, - 0.147621 ], [ - 0.500000, 0.809017, - 0.309017 ], [ - 0.525731, 0.850651, 0.000000 ], [ 0.000000, 0.850651, - 0.525731 ], [ - 0.238856, 0.864188, - 0.442863 ], [ 0.000000, 0.955423, - 0.295242 ], [ - 0.262866, 0.951056, - 0.162460 ], [ 0.000000, 1.000000, 0.000000 ], [ 0.000000, 0.955423, 0.295242 ], [ - 0.262866, 0.951056, 0.162460 ], [ 0.238856, 0.864188, 0.442863 ], [ 0.262866, 0.951056, 0.162460 ], [ 0.500000, 0.809017, 0.309017 ], [ 0.238856, 0.864188, - 0.442863 ], [ 0.262866, 0.951056, - 0.162460 ], [ 0.500000, 0.809017, - 0.309017 ], [ 0.850651, 0.525731, 0.000000 ], [ 0.716567, 0.681718, 0.147621 ], [ 0.716567, 0.681718, - 0.147621 ], [ 0.525731, 0.850651, 0.000000 ], [ 0.425325, 0.688191, 0.587785 ], [ 0.864188, 0.442863, 0.238856 ], [ 0.688191, 0.587785, 0.425325 ], [ 0.809017, 0.309017, 0.500000 ], [ 0.681718, 0.147621, 0.716567 ], [ 0.587785, 0.425325, 0.688191 ], [ 0.955423, 0.295242, 0.000000 ], [ 1.000000, 0.000000, 0.000000 ], [ 0.951056, 0.162460, 0.262866 ], [ 0.850651, - 0.525731, 0.000000 ], [ 0.955423, - 0.295242, 0.000000 ], [ 0.864188, - 0.442863, 0.238856 ], [ 0.951056, - 0.162460, 0.262866 ], [ 0.809017, - 0.309017, 0.500000 ], [ 0.681718, - 0.147621, 0.716567 ], [ 0.850651, 0.000000, 0.525731 ], [ 0.864188, 0.442863, - 0.238856 ], [ 0.809017, 0.309017, - 0.500000 ], [ 0.951056, 0.162460, - 0.262866 ], [ 0.525731, 0.000000, - 0.850651 ], [ 0.681718, 0.147621, - 0.716567 ], [ 0.681718, - 0.147621, - 0.716567 ], [ 0.850651, 0.000000, - 0.525731 ], [ 0.809017, - 0.309017, - 0.500000 ], [ 0.864188, - 0.442863, - 0.238856 ], [ 0.951056, - 0.162460, - 0.262866 ], [ 0.147621, 0.716567, - 0.681718 ], [ 0.309017, 0.500000, - 0.809017 ], [ 0.425325, 0.688191, - 0.587785 ], [ 0.442863, 0.238856, - 0.864188 ], [ 0.587785, 0.425325, - 0.688191 ], [ 0.688191, 0.587785, - 0.425325 ], [ - 0.147621, 0.716567, - 0.681718 ], [ - 0.309017, 0.500000, - 0.809017 ], [ 0.000000, 0.525731, - 0.850651 ], [ - 0.525731, 0.000000, - 0.850651 ], [ - 0.442863, 0.238856, - 0.864188 ], [ - 0.295242, 0.000000, - 0.955423 ], [ - 0.162460, 0.262866, - 0.951056 ], [ 0.000000, 0.000000, - 1.000000 ], [ 0.295242, 0.000000, - 0.955423 ], [ 0.162460, 0.262866, - 0.951056 ], [ - 0.442863, - 0.238856, - 0.864188 ], [ - 0.309017, - 0.500000, - 0.809017 ], [ - 0.162460, - 0.262866, - 0.951056 ], [ 0.000000, - 0.850651, - 0.525731 ], [ - 0.147621, - 0.716567, - 0.681718 ], [ 0.147621, - 0.716567, - 0.681718 ], [ 0.000000, - 0.525731, - 0.850651 ], [ 0.309017, - 0.500000, - 0.809017 ], [ 0.442863, - 0.238856, - 0.864188 ], [ 0.162460, - 0.262866, - 0.951056 ], [ 0.238856, - 0.864188, - 0.442863 ], [ 0.500000, - 0.809017, - 0.309017 ], [ 0.425325, - 0.688191, - 0.587785 ], [ 0.716567, - 0.681718, - 0.147621 ], [ 0.688191, - 0.587785, - 0.425325 ], [ 0.587785, - 0.425325, - 0.688191 ], [ 0.000000, - 0.955423, - 0.295242 ], [ 0.000000, - 1.000000, 0.000000 ], [ 0.262866, - 0.951056, - 0.162460 ], [ 0.000000, - 0.850651, 0.525731 ], [ 0.000000, - 0.955423, 0.295242 ], [ 0.238856, - 0.864188, 0.442863 ], [ 0.262866, - 0.951056, 0.162460 ], [ 0.500000, - 0.809017, 0.309017 ], [ 0.716567, - 0.681718, 0.147621 ], [ 0.525731, - 0.850651, 0.000000 ], [ - 0.238856, - 0.864188, - 0.442863 ], [ - 0.500000, - 0.809017, - 0.309017 ], [ - 0.262866, - 0.951056, - 0.162460 ], [ - 0.850651, - 0.525731, 0.000000 ], [ - 0.716567, - 0.681718, - 0.147621 ], [ - 0.716567, - 0.681718, 0.147621 ], [ - 0.525731, - 0.850651, 0.000000 ], [ - 0.500000, - 0.809017, 0.309017 ], [ - 0.238856, - 0.864188, 0.442863 ], [ - 0.262866, - 0.951056, 0.162460 ], [ - 0.864188, - 0.442863, 0.238856 ], [ - 0.809017, - 0.309017, 0.500000 ], [ - 0.688191, - 0.587785, 0.425325 ], [ - 0.681718, - 0.147621, 0.716567 ], [ - 0.442863, - 0.238856, 0.864188 ], [ - 0.587785, - 0.425325, 0.688191 ], [ - 0.309017, - 0.500000, 0.809017 ], [ - 0.147621, - 0.716567, 0.681718 ], [ - 0.425325, - 0.688191, 0.587785 ], [ - 0.162460, - 0.262866, 0.951056 ], [ 0.442863, - 0.238856, 0.864188 ], [ 0.162460, - 0.262866, 0.951056 ], [ 0.309017, - 0.500000, 0.809017 ], [ 0.147621, - 0.716567, 0.681718 ], [ 0.000000, - 0.525731, 0.850651 ], [ 0.425325, - 0.688191, 0.587785 ], [ 0.587785, - 0.425325, 0.688191 ], [ 0.688191, - 0.587785, 0.425325 ], [ - 0.955423, 0.295242, 0.000000 ], [ - 0.951056, 0.162460, 0.262866 ], [ - 1.000000, 0.000000, 0.000000 ], [ - 0.850651, 0.000000, 0.525731 ], [ - 0.955423, - 0.295242, 0.000000 ], [ - 0.951056, - 0.162460, 0.262866 ], [ - 0.864188, 0.442863, - 0.238856 ], [ - 0.951056, 0.162460, - 0.262866 ], [ - 0.809017, 0.309017, - 0.500000 ], [ - 0.864188, - 0.442863, - 0.238856 ], [ - 0.951056, - 0.162460, - 0.262866 ], [ - 0.809017, - 0.309017, - 0.500000 ], [ - 0.681718, 0.147621, - 0.716567 ], [ - 0.681718, - 0.147621, - 0.716567 ], [ - 0.850651, 0.000000, - 0.525731 ], [ - 0.688191, 0.587785, - 0.425325 ], [ - 0.587785, 0.425325, - 0.688191 ], [ - 0.425325, 0.688191, - 0.587785 ], [ - 0.425325, - 0.688191, - 0.587785 ], [ - 0.587785, - 0.425325, - 0.688191 ], [ - 0.688191, - 0.587785, - 0.425325 ]]; - THREE.Loader.call( this, manager ); + class MD2Loader extends THREE.Loader { - }; + constructor( manager ) { - MD2Loader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: MD2Loader, - load: function ( url, onLoad, onProgress, onError ) { + super( manager ); - var scope = this; - var loader = new THREE.FileLoader( scope.manager ); + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + const loader = new THREE.FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( scope.requestHeader ); @@ -40,208 +42,207 @@ }, onProgress, onError ); - }, - parse: function () { + } - var normalData = [[ - 0.525731, 0.000000, 0.850651 ], [ - 0.442863, 0.238856, 0.864188 ], [ - 0.295242, 0.000000, 0.955423 ], [ - 0.309017, 0.500000, 0.809017 ], [ - 0.162460, 0.262866, 0.951056 ], [ 0.000000, 0.000000, 1.000000 ], [ 0.000000, 0.850651, 0.525731 ], [ - 0.147621, 0.716567, 0.681718 ], [ 0.147621, 0.716567, 0.681718 ], [ 0.000000, 0.525731, 0.850651 ], [ 0.309017, 0.500000, 0.809017 ], [ 0.525731, 0.000000, 0.850651 ], [ 0.295242, 0.000000, 0.955423 ], [ 0.442863, 0.238856, 0.864188 ], [ 0.162460, 0.262866, 0.951056 ], [ - 0.681718, 0.147621, 0.716567 ], [ - 0.809017, 0.309017, 0.500000 ], [ - 0.587785, 0.425325, 0.688191 ], [ - 0.850651, 0.525731, 0.000000 ], [ - 0.864188, 0.442863, 0.238856 ], [ - 0.716567, 0.681718, 0.147621 ], [ - 0.688191, 0.587785, 0.425325 ], [ - 0.500000, 0.809017, 0.309017 ], [ - 0.238856, 0.864188, 0.442863 ], [ - 0.425325, 0.688191, 0.587785 ], [ - 0.716567, 0.681718, - 0.147621 ], [ - 0.500000, 0.809017, - 0.309017 ], [ - 0.525731, 0.850651, 0.000000 ], [ 0.000000, 0.850651, - 0.525731 ], [ - 0.238856, 0.864188, - 0.442863 ], [ 0.000000, 0.955423, - 0.295242 ], [ - 0.262866, 0.951056, - 0.162460 ], [ 0.000000, 1.000000, 0.000000 ], [ 0.000000, 0.955423, 0.295242 ], [ - 0.262866, 0.951056, 0.162460 ], [ 0.238856, 0.864188, 0.442863 ], [ 0.262866, 0.951056, 0.162460 ], [ 0.500000, 0.809017, 0.309017 ], [ 0.238856, 0.864188, - 0.442863 ], [ 0.262866, 0.951056, - 0.162460 ], [ 0.500000, 0.809017, - 0.309017 ], [ 0.850651, 0.525731, 0.000000 ], [ 0.716567, 0.681718, 0.147621 ], [ 0.716567, 0.681718, - 0.147621 ], [ 0.525731, 0.850651, 0.000000 ], [ 0.425325, 0.688191, 0.587785 ], [ 0.864188, 0.442863, 0.238856 ], [ 0.688191, 0.587785, 0.425325 ], [ 0.809017, 0.309017, 0.500000 ], [ 0.681718, 0.147621, 0.716567 ], [ 0.587785, 0.425325, 0.688191 ], [ 0.955423, 0.295242, 0.000000 ], [ 1.000000, 0.000000, 0.000000 ], [ 0.951056, 0.162460, 0.262866 ], [ 0.850651, - 0.525731, 0.000000 ], [ 0.955423, - 0.295242, 0.000000 ], [ 0.864188, - 0.442863, 0.238856 ], [ 0.951056, - 0.162460, 0.262866 ], [ 0.809017, - 0.309017, 0.500000 ], [ 0.681718, - 0.147621, 0.716567 ], [ 0.850651, 0.000000, 0.525731 ], [ 0.864188, 0.442863, - 0.238856 ], [ 0.809017, 0.309017, - 0.500000 ], [ 0.951056, 0.162460, - 0.262866 ], [ 0.525731, 0.000000, - 0.850651 ], [ 0.681718, 0.147621, - 0.716567 ], [ 0.681718, - 0.147621, - 0.716567 ], [ 0.850651, 0.000000, - 0.525731 ], [ 0.809017, - 0.309017, - 0.500000 ], [ 0.864188, - 0.442863, - 0.238856 ], [ 0.951056, - 0.162460, - 0.262866 ], [ 0.147621, 0.716567, - 0.681718 ], [ 0.309017, 0.500000, - 0.809017 ], [ 0.425325, 0.688191, - 0.587785 ], [ 0.442863, 0.238856, - 0.864188 ], [ 0.587785, 0.425325, - 0.688191 ], [ 0.688191, 0.587785, - 0.425325 ], [ - 0.147621, 0.716567, - 0.681718 ], [ - 0.309017, 0.500000, - 0.809017 ], [ 0.000000, 0.525731, - 0.850651 ], [ - 0.525731, 0.000000, - 0.850651 ], [ - 0.442863, 0.238856, - 0.864188 ], [ - 0.295242, 0.000000, - 0.955423 ], [ - 0.162460, 0.262866, - 0.951056 ], [ 0.000000, 0.000000, - 1.000000 ], [ 0.295242, 0.000000, - 0.955423 ], [ 0.162460, 0.262866, - 0.951056 ], [ - 0.442863, - 0.238856, - 0.864188 ], [ - 0.309017, - 0.500000, - 0.809017 ], [ - 0.162460, - 0.262866, - 0.951056 ], [ 0.000000, - 0.850651, - 0.525731 ], [ - 0.147621, - 0.716567, - 0.681718 ], [ 0.147621, - 0.716567, - 0.681718 ], [ 0.000000, - 0.525731, - 0.850651 ], [ 0.309017, - 0.500000, - 0.809017 ], [ 0.442863, - 0.238856, - 0.864188 ], [ 0.162460, - 0.262866, - 0.951056 ], [ 0.238856, - 0.864188, - 0.442863 ], [ 0.500000, - 0.809017, - 0.309017 ], [ 0.425325, - 0.688191, - 0.587785 ], [ 0.716567, - 0.681718, - 0.147621 ], [ 0.688191, - 0.587785, - 0.425325 ], [ 0.587785, - 0.425325, - 0.688191 ], [ 0.000000, - 0.955423, - 0.295242 ], [ 0.000000, - 1.000000, 0.000000 ], [ 0.262866, - 0.951056, - 0.162460 ], [ 0.000000, - 0.850651, 0.525731 ], [ 0.000000, - 0.955423, 0.295242 ], [ 0.238856, - 0.864188, 0.442863 ], [ 0.262866, - 0.951056, 0.162460 ], [ 0.500000, - 0.809017, 0.309017 ], [ 0.716567, - 0.681718, 0.147621 ], [ 0.525731, - 0.850651, 0.000000 ], [ - 0.238856, - 0.864188, - 0.442863 ], [ - 0.500000, - 0.809017, - 0.309017 ], [ - 0.262866, - 0.951056, - 0.162460 ], [ - 0.850651, - 0.525731, 0.000000 ], [ - 0.716567, - 0.681718, - 0.147621 ], [ - 0.716567, - 0.681718, 0.147621 ], [ - 0.525731, - 0.850651, 0.000000 ], [ - 0.500000, - 0.809017, 0.309017 ], [ - 0.238856, - 0.864188, 0.442863 ], [ - 0.262866, - 0.951056, 0.162460 ], [ - 0.864188, - 0.442863, 0.238856 ], [ - 0.809017, - 0.309017, 0.500000 ], [ - 0.688191, - 0.587785, 0.425325 ], [ - 0.681718, - 0.147621, 0.716567 ], [ - 0.442863, - 0.238856, 0.864188 ], [ - 0.587785, - 0.425325, 0.688191 ], [ - 0.309017, - 0.500000, 0.809017 ], [ - 0.147621, - 0.716567, 0.681718 ], [ - 0.425325, - 0.688191, 0.587785 ], [ - 0.162460, - 0.262866, 0.951056 ], [ 0.442863, - 0.238856, 0.864188 ], [ 0.162460, - 0.262866, 0.951056 ], [ 0.309017, - 0.500000, 0.809017 ], [ 0.147621, - 0.716567, 0.681718 ], [ 0.000000, - 0.525731, 0.850651 ], [ 0.425325, - 0.688191, 0.587785 ], [ 0.587785, - 0.425325, 0.688191 ], [ 0.688191, - 0.587785, 0.425325 ], [ - 0.955423, 0.295242, 0.000000 ], [ - 0.951056, 0.162460, 0.262866 ], [ - 1.000000, 0.000000, 0.000000 ], [ - 0.850651, 0.000000, 0.525731 ], [ - 0.955423, - 0.295242, 0.000000 ], [ - 0.951056, - 0.162460, 0.262866 ], [ - 0.864188, 0.442863, - 0.238856 ], [ - 0.951056, 0.162460, - 0.262866 ], [ - 0.809017, 0.309017, - 0.500000 ], [ - 0.864188, - 0.442863, - 0.238856 ], [ - 0.951056, - 0.162460, - 0.262866 ], [ - 0.809017, - 0.309017, - 0.500000 ], [ - 0.681718, 0.147621, - 0.716567 ], [ - 0.681718, - 0.147621, - 0.716567 ], [ - 0.850651, 0.000000, - 0.525731 ], [ - 0.688191, 0.587785, - 0.425325 ], [ - 0.587785, 0.425325, - 0.688191 ], [ - 0.425325, 0.688191, - 0.587785 ], [ - 0.425325, - 0.688191, - 0.587785 ], [ - 0.587785, - 0.425325, - 0.688191 ], [ - 0.688191, - 0.587785, - 0.425325 ]]; - return function ( buffer ) { + parse( buffer ) { - var data = new DataView( buffer ); // http://tfc.duke.free.fr/coding/md2-specs-en.html + const data = new DataView( buffer ); // http://tfc.duke.free.fr/coding/md2-specs-en.html - var header = {}; - var headerNames = [ 'ident', 'version', 'skinwidth', 'skinheight', 'framesize', 'num_skins', 'num_vertices', 'num_st', 'num_tris', 'num_glcmds', 'num_frames', 'offset_skins', 'offset_st', 'offset_tris', 'offset_frames', 'offset_glcmds', 'offset_end' ]; + const header = {}; + const headerNames = [ 'ident', 'version', 'skinwidth', 'skinheight', 'framesize', 'num_skins', 'num_vertices', 'num_st', 'num_tris', 'num_glcmds', 'num_frames', 'offset_skins', 'offset_st', 'offset_tris', 'offset_frames', 'offset_glcmds', 'offset_end' ]; - for ( var i = 0; i < headerNames.length; i ++ ) { + for ( let i = 0; i < headerNames.length; i ++ ) { - header[ headerNames[ i ] ] = data.getInt32( i * 4, true ); + header[ headerNames[ i ] ] = data.getInt32( i * 4, true ); - } + } - if ( header.ident !== 844121161 || header.version !== 8 ) { + if ( header.ident !== 844121161 || header.version !== 8 ) { - console.error( 'Not a valid MD2 file' ); - return; + console.error( 'Not a valid MD2 file' ); + return; - } + } - if ( header.offset_end !== data.byteLength ) { + if ( header.offset_end !== data.byteLength ) { - console.error( 'Corrupted MD2 file' ); - return; + console.error( 'Corrupted MD2 file' ); + return; - } // + } // - var geometry = new THREE.BufferGeometry(); // uvs + const geometry = new THREE.BufferGeometry(); // uvs - var uvsTemp = []; - var offset = header.offset_st; + const uvsTemp = []; + let offset = header.offset_st; - for ( var i = 0, l = header.num_st; i < l; i ++ ) { + for ( let i = 0, l = header.num_st; i < l; i ++ ) { - var u = data.getInt16( offset + 0, true ); - var v = data.getInt16( offset + 2, true ); - uvsTemp.push( u / header.skinwidth, 1 - v / header.skinheight ); - offset += 4; + const u = data.getInt16( offset + 0, true ); + const v = data.getInt16( offset + 2, true ); + uvsTemp.push( u / header.skinwidth, 1 - v / header.skinheight ); + offset += 4; - } // triangles + } // triangles - offset = header.offset_tris; - var vertexIndices = []; - var uvIndices = []; + offset = header.offset_tris; + const vertexIndices = []; + const uvIndices = []; - for ( var i = 0, l = header.num_tris; i < l; i ++ ) { + for ( let i = 0, l = header.num_tris; i < l; i ++ ) { - vertexIndices.push( data.getUint16( offset + 0, true ), data.getUint16( offset + 2, true ), data.getUint16( offset + 4, true ) ); - uvIndices.push( data.getUint16( offset + 6, true ), data.getUint16( offset + 8, true ), data.getUint16( offset + 10, true ) ); - offset += 12; + vertexIndices.push( data.getUint16( offset + 0, true ), data.getUint16( offset + 2, true ), data.getUint16( offset + 4, true ) ); + uvIndices.push( data.getUint16( offset + 6, true ), data.getUint16( offset + 8, true ), data.getUint16( offset + 10, true ) ); + offset += 12; - } // frames + } // frames - var translation = new THREE.Vector3(); - var scale = new THREE.Vector3(); - var string = []; - var frames = []; - offset = header.offset_frames; + const translation = new THREE.Vector3(); + const scale = new THREE.Vector3(); + const string = []; + const frames = []; + offset = header.offset_frames; - for ( var i = 0, l = header.num_frames; i < l; i ++ ) { + for ( let i = 0, l = header.num_frames; i < l; i ++ ) { - scale.set( data.getFloat32( offset + 0, true ), data.getFloat32( offset + 4, true ), data.getFloat32( offset + 8, true ) ); - translation.set( data.getFloat32( offset + 12, true ), data.getFloat32( offset + 16, true ), data.getFloat32( offset + 20, true ) ); - offset += 24; + scale.set( data.getFloat32( offset + 0, true ), data.getFloat32( offset + 4, true ), data.getFloat32( offset + 8, true ) ); + translation.set( data.getFloat32( offset + 12, true ), data.getFloat32( offset + 16, true ), data.getFloat32( offset + 20, true ) ); + offset += 24; - for ( var j = 0; j < 16; j ++ ) { + for ( let j = 0; j < 16; j ++ ) { - var character = data.getUint8( offset + j, true ); - if ( character === 0 ) break; - string[ j ] = character; + const character = data.getUint8( offset + j, true ); + if ( character === 0 ) break; + string[ j ] = character; - } + } - var frame = { - name: String.fromCharCode.apply( null, string ), - vertices: [], - normals: [] - }; - offset += 16; + const frame = { + name: String.fromCharCode.apply( null, string ), + vertices: [], + normals: [] + }; + offset += 16; - for ( var j = 0; j < header.num_vertices; j ++ ) { + for ( let j = 0; j < header.num_vertices; j ++ ) { - var x = data.getUint8( offset ++, true ); - var y = data.getUint8( offset ++, true ); - var z = data.getUint8( offset ++, true ); - var n = normalData[ data.getUint8( offset ++, true ) ]; - x = x * scale.x + translation.x; - y = y * scale.y + translation.y; - z = z * scale.z + translation.z; - frame.vertices.push( x, z, y ); // convert to Y-up + let x = data.getUint8( offset ++, true ); + let y = data.getUint8( offset ++, true ); + let z = data.getUint8( offset ++, true ); - frame.normals.push( n[ 0 ], n[ 2 ], n[ 1 ] ); // convert to Y-up + const n = _normalData[ data.getUint8( offset ++, true ) ]; - } + x = x * scale.x + translation.x; + y = y * scale.y + translation.y; + z = z * scale.z + translation.z; + frame.vertices.push( x, z, y ); // convert to Y-up - frames.push( frame ); + frame.normals.push( n[ 0 ], n[ 2 ], n[ 1 ] ); // convert to Y-up - } // static + } + frames.push( frame ); - var positions = []; - var normals = []; - var uvs = []; - var verticesTemp = frames[ 0 ].vertices; - var normalsTemp = frames[ 0 ].normals; + } // static - for ( var i = 0, l = vertexIndices.length; i < l; i ++ ) { - var vertexIndex = vertexIndices[ i ]; - var stride = vertexIndex * 3; // + const positions = []; + const normals = []; + const uvs = []; + const verticesTemp = frames[ 0 ].vertices; + const normalsTemp = frames[ 0 ].normals; - var x = verticesTemp[ stride ]; - var y = verticesTemp[ stride + 1 ]; - var z = verticesTemp[ stride + 2 ]; - positions.push( x, y, z ); // + for ( let i = 0, l = vertexIndices.length; i < l; i ++ ) { - var nx = normalsTemp[ stride ]; - var ny = normalsTemp[ stride + 1 ]; - var nz = normalsTemp[ stride + 2 ]; - normals.push( nx, ny, nz ); // + const vertexIndex = vertexIndices[ i ]; + let stride = vertexIndex * 3; // - var uvIndex = uvIndices[ i ]; - stride = uvIndex * 2; - var u = uvsTemp[ stride ]; - var v = uvsTemp[ stride + 1 ]; - uvs.push( u, v ); + const x = verticesTemp[ stride ]; + const y = verticesTemp[ stride + 1 ]; + const z = verticesTemp[ stride + 2 ]; + positions.push( x, y, z ); // - } + const nx = normalsTemp[ stride ]; + const ny = normalsTemp[ stride + 1 ]; + const nz = normalsTemp[ stride + 2 ]; + normals.push( nx, ny, nz ); // - geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) ); - geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) ); - geometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( uvs, 2 ) ); // animation + const uvIndex = uvIndices[ i ]; + stride = uvIndex * 2; + const u = uvsTemp[ stride ]; + const v = uvsTemp[ stride + 1 ]; + uvs.push( u, v ); - var morphPositions = []; - var morphNormals = []; + } - for ( var i = 0, l = frames.length; i < l; i ++ ) { + geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) ); + geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) ); + geometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( uvs, 2 ) ); // animation - var frame = frames[ i ]; - var attributeName = frame.name; + const morphPositions = []; + const morphNormals = []; - if ( frame.vertices.length > 0 ) { + for ( let i = 0, l = frames.length; i < l; i ++ ) { - var positions = []; + const frame = frames[ i ]; + const attributeName = frame.name; - for ( var j = 0, jl = vertexIndices.length; j < jl; j ++ ) { + if ( frame.vertices.length > 0 ) { - var vertexIndex = vertexIndices[ j ]; - var stride = vertexIndex * 3; - var x = frame.vertices[ stride ]; - var y = frame.vertices[ stride + 1 ]; - var z = frame.vertices[ stride + 2 ]; - positions.push( x, y, z ); + const positions = []; - } + for ( let j = 0, jl = vertexIndices.length; j < jl; j ++ ) { - var positionAttribute = new THREE.Float32BufferAttribute( positions, 3 ); - positionAttribute.name = attributeName; - morphPositions.push( positionAttribute ); + const vertexIndex = vertexIndices[ j ]; + const stride = vertexIndex * 3; + const x = frame.vertices[ stride ]; + const y = frame.vertices[ stride + 1 ]; + const z = frame.vertices[ stride + 2 ]; + positions.push( x, y, z ); } - if ( frame.normals.length > 0 ) { + const positionAttribute = new THREE.Float32BufferAttribute( positions, 3 ); + positionAttribute.name = attributeName; + morphPositions.push( positionAttribute ); - var normals = []; + } - for ( var j = 0, jl = vertexIndices.length; j < jl; j ++ ) { + if ( frame.normals.length > 0 ) { - var vertexIndex = vertexIndices[ j ]; - var stride = vertexIndex * 3; - var nx = frame.normals[ stride ]; - var ny = frame.normals[ stride + 1 ]; - var nz = frame.normals[ stride + 2 ]; - normals.push( nx, ny, nz ); + const normals = []; - } + for ( let j = 0, jl = vertexIndices.length; j < jl; j ++ ) { - var normalAttribute = new THREE.Float32BufferAttribute( normals, 3 ); - normalAttribute.name = attributeName; - morphNormals.push( normalAttribute ); + const vertexIndex = vertexIndices[ j ]; + const stride = vertexIndex * 3; + const nx = frame.normals[ stride ]; + const ny = frame.normals[ stride + 1 ]; + const nz = frame.normals[ stride + 2 ]; + normals.push( nx, ny, nz ); } + const normalAttribute = new THREE.Float32BufferAttribute( normals, 3 ); + normalAttribute.name = attributeName; + morphNormals.push( normalAttribute ); + } - geometry.morphAttributes.position = morphPositions; - geometry.morphAttributes.normal = morphNormals; - geometry.morphTargetsRelative = false; - geometry.animations = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( frames, 10 ); - return geometry; + } + + geometry.morphAttributes.position = morphPositions; + geometry.morphAttributes.normal = morphNormals; + geometry.morphTargetsRelative = false; + geometry.animations = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( frames, 10 ); + return geometry; - }; + } - }() - } ); + } THREE.MD2Loader = MD2Loader; diff --git a/examples/js/loaders/MDDLoader.js b/examples/js/loaders/MDDLoader.js index b05ad0b9120ec1..3f7f9cda5bacfd 100644 --- a/examples/js/loaders/MDDLoader.js +++ b/examples/js/loaders/MDDLoader.js @@ -12,18 +12,18 @@ * vertex data for each frame (sequence of float32) */ - var MDDLoader = function ( manager ) { + class MDDLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); + constructor( manager ) { - }; + super( manager ); - MDDLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: MDDLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new THREE.FileLoader( this.manager ); + const scope = this; + const loader = new THREE.FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.load( url, function ( data ) { @@ -32,18 +32,19 @@ }, onProgress, onError ); - }, - parse: function ( data ) { + } - var view = new DataView( data ); - var totalFrames = view.getUint32( 0 ); - var totalPoints = view.getUint32( 4 ); - var offset = 8; // animation clip + parse( data ) { - var times = new Float32Array( totalFrames ); - var values = new Float32Array( totalFrames * totalFrames ).fill( 0 ); + const view = new DataView( data ); + const totalFrames = view.getUint32( 0 ); + const totalPoints = view.getUint32( 4 ); + let offset = 8; // animation clip - for ( var i = 0; i < totalFrames; i ++ ) { + const times = new Float32Array( totalFrames ); + const values = new Float32Array( totalFrames * totalFrames ).fill( 0 ); + + for ( let i = 0; i < totalFrames; i ++ ) { times[ i ] = view.getFloat32( offset ); offset += 4; @@ -51,18 +52,18 @@ } - var track = new THREE.NumberKeyframeTrack( '.morphTargetInfluences', times, values ); - var clip = new THREE.AnimationClip( 'default', times[ times.length - 1 ], [ track ] ); // morph targets + const track = new THREE.NumberKeyframeTrack( '.morphTargetInfluences', times, values ); + const clip = new THREE.AnimationClip( 'default', times[ times.length - 1 ], [ track ] ); // morph targets - var morphTargets = []; + const morphTargets = []; - for ( var i = 0; i < totalFrames; i ++ ) { + for ( let i = 0; i < totalFrames; i ++ ) { - var morphTarget = new Float32Array( totalPoints * 3 ); + const morphTarget = new Float32Array( totalPoints * 3 ); - for ( var j = 0; j < totalPoints; j ++ ) { + for ( let j = 0; j < totalPoints; j ++ ) { - var stride = j * 3; + const stride = j * 3; morphTarget[ stride + 0 ] = view.getFloat32( offset ); offset += 4; // x @@ -74,7 +75,7 @@ } - var attribute = new THREE.BufferAttribute( morphTarget, 3 ); + const attribute = new THREE.BufferAttribute( morphTarget, 3 ); attribute.name = 'morph_' + i; morphTargets.push( attribute ); @@ -86,7 +87,8 @@ }; } - } ); + + } THREE.MDDLoader = MDDLoader; diff --git a/examples/js/loaders/PCDLoader.js b/examples/js/loaders/PCDLoader.js index c71a7edf26df3e..a89c17f4d90f8b 100644 --- a/examples/js/loaders/PCDLoader.js +++ b/examples/js/loaders/PCDLoader.js @@ -1,18 +1,18 @@ ( function () { - var PCDLoader = function ( manager ) { + class PCDLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); - this.littleEndian = true; + constructor( manager ) { - }; + super( manager ); + this.littleEndian = true; - PCDLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: PCDLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new THREE.FileLoader( scope.manager ); + const scope = this; + const loader = new THREE.FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( scope.requestHeader ); @@ -41,19 +41,20 @@ }, onProgress, onError ); - }, - parse: function ( data, url ) { + } + + parse( data, url ) { // from https://gitlab.com/taketwo/three-pcd-loader/blob/master/decompress-lzf.js function decompressLZF( inData, outLength ) { - var inLength = inData.length; - var outData = new Uint8Array( outLength ); - var inPtr = 0; - var outPtr = 0; - var ctrl; - var len; - var ref; + const inLength = inData.length; + const outData = new Uint8Array( outLength ); + let inPtr = 0; + let outPtr = 0; + let ctrl; + let len; + let ref; do { @@ -105,9 +106,9 @@ function parseHeader( data ) { - var PCDheader = {}; - var result1 = data.search( /[\r\n]DATA\s(\S*)\s/i ); - var result2 = /[\r\n]DATA\s(\S*)\s/i.exec( data.substr( result1 - 1 ) ); + const PCDheader = {}; + const result1 = data.search( /[\r\n]DATA\s(\S*)\s/i ); + const result2 = /[\r\n]DATA\s(\S*)\s/i.exec( data.substr( result1 - 1 ) ); PCDheader.data = result2[ 1 ]; PCDheader.headerLen = result2[ 0 ].length + result1; PCDheader.str = data.substr( 0, PCDheader.headerLen ); // remove comments @@ -155,7 +156,7 @@ PCDheader.count = []; - for ( var i = 0, l = PCDheader.fields.length; i < l; i ++ ) { + for ( let i = 0, l = PCDheader.fields.length; i < l; i ++ ) { PCDheader.count.push( 1 ); @@ -164,9 +165,9 @@ } PCDheader.offset = {}; - var sizeSum = 0; + let sizeSum = 0; - for ( var i = 0, l = PCDheader.fields.length; i < l; i ++ ) { + for ( let i = 0, l = PCDheader.fields.length; i < l; i ++ ) { if ( PCDheader.data === 'ascii' ) { @@ -187,24 +188,24 @@ } - var textData = THREE.LoaderUtils.decodeText( new Uint8Array( data ) ); // parse header (always ascii format) + const textData = THREE.LoaderUtils.decodeText( new Uint8Array( data ) ); // parse header (always ascii format) - var PCDheader = parseHeader( textData ); // parse data + const PCDheader = parseHeader( textData ); // parse data - var position = []; - var normal = []; - var color = []; // ascii + const position = []; + const normal = []; + const color = []; // ascii if ( PCDheader.data === 'ascii' ) { - var offset = PCDheader.offset; - var pcdData = textData.substr( PCDheader.headerLen ); - var lines = pcdData.split( '\n' ); + const offset = PCDheader.offset; + const pcdData = textData.substr( PCDheader.headerLen ); + const lines = pcdData.split( '\n' ); - for ( var i = 0, l = lines.length; i < l; i ++ ) { + for ( let i = 0, l = lines.length; i < l; i ++ ) { if ( lines[ i ] === '' ) continue; - var line = lines[ i ].split( ' ' ); + const line = lines[ i ].split( ' ' ); if ( offset.x !== undefined ) { @@ -216,10 +217,10 @@ if ( offset.rgb !== undefined ) { - var rgb = parseFloat( line[ offset.rgb ] ); - var r = rgb >> 16 & 0x0000ff; - var g = rgb >> 8 & 0x0000ff; - var b = rgb >> 0 & 0x0000ff; + const rgb = parseFloat( line[ offset.rgb ] ); + const r = rgb >> 16 & 0x0000ff; + const g = rgb >> 8 & 0x0000ff; + const b = rgb >> 0 & 0x0000ff; color.push( r / 255, g / 255, b / 255 ); } @@ -242,14 +243,14 @@ if ( PCDheader.data === 'binary_compressed' ) { - var sizes = new Uint32Array( data.slice( PCDheader.headerLen, PCDheader.headerLen + 8 ) ); - var compressedSize = sizes[ 0 ]; - var decompressedSize = sizes[ 1 ]; - var decompressed = decompressLZF( new Uint8Array( data, PCDheader.headerLen + 8, compressedSize ), decompressedSize ); - var dataview = new DataView( decompressed.buffer ); - var offset = PCDheader.offset; + const sizes = new Uint32Array( data.slice( PCDheader.headerLen, PCDheader.headerLen + 8 ) ); + const compressedSize = sizes[ 0 ]; + const decompressedSize = sizes[ 1 ]; + const decompressed = decompressLZF( new Uint8Array( data, PCDheader.headerLen + 8, compressedSize ), decompressedSize ); + const dataview = new DataView( decompressed.buffer ); + const offset = PCDheader.offset; - for ( var i = 0; i < PCDheader.points; i ++ ) { + for ( let i = 0; i < PCDheader.points; i ++ ) { if ( offset.x !== undefined ) { @@ -282,10 +283,10 @@ if ( PCDheader.data === 'binary' ) { - var dataview = new DataView( data, PCDheader.headerLen ); - var offset = PCDheader.offset; + const dataview = new DataView( data, PCDheader.headerLen ); + const offset = PCDheader.offset; - for ( var i = 0, row = 0; i < PCDheader.points; i ++, row += PCDheader.rowSize ) { + for ( let i = 0, row = 0; i < PCDheader.points; i ++, row += PCDheader.rowSize ) { if ( offset.x !== undefined ) { @@ -316,13 +317,13 @@ } // build geometry - var geometry = new THREE.BufferGeometry(); + const geometry = new THREE.BufferGeometry(); if ( position.length > 0 ) geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( position, 3 ) ); if ( normal.length > 0 ) geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normal, 3 ) ); if ( color.length > 0 ) geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( color, 3 ) ); geometry.computeBoundingSphere(); // build material - var material = new THREE.PointsMaterial( { + const material = new THREE.PointsMaterial( { size: 0.005 } ); @@ -337,15 +338,16 @@ } // build point cloud - var mesh = new THREE.Points( geometry, material ); - var name = url.split( '' ).reverse().join( '' ); + const mesh = new THREE.Points( geometry, material ); + let name = url.split( '' ).reverse().join( '' ); name = /([^\/]*)/.exec( name ); name = name[ 1 ].split( '' ).reverse().join( '' ); mesh.name = name; return mesh; } - } ); + + } THREE.PCDLoader = PCDLoader; diff --git a/examples/js/loaders/PDBLoader.js b/examples/js/loaders/PDBLoader.js index 3625334ae50e7f..36786f7c0ef199 100644 --- a/examples/js/loaders/PDBLoader.js +++ b/examples/js/loaders/PDBLoader.js @@ -1,17 +1,17 @@ ( function () { - var PDBLoader = function ( manager ) { + class PDBLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); + constructor( manager ) { - }; + super( manager ); - PDBLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: PDBLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new THREE.FileLoader( scope.manager ); + const scope = this; + const loader = new THREE.FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setRequestHeader( scope.requestHeader ); loader.setWithCredentials( scope.withCredentials ); @@ -39,9 +39,10 @@ }, onProgress, onError ); - }, - // Based on CanvasMol PDB parser - parse: function ( text ) { + } // Based on CanvasMol PDB parser + + + parse( text ) { function trim( text ) { @@ -61,13 +62,13 @@ } - function parseBond( start, length ) { + function parseBond( start, length, satom, i ) { - var eatom = parseInt( lines[ i ].substr( start, length ) ); + const eatom = parseInt( lines[ i ].substr( start, length ) ); if ( eatom ) { - var h = hash( satom, eatom ); + const h = hash( satom, eatom ); if ( _bhash[ h ] === undefined ) { @@ -87,46 +88,44 @@ function buildGeometry() { - var build = { + const build = { geometryAtoms: new THREE.BufferGeometry(), geometryBonds: new THREE.BufferGeometry(), json: { atoms: atoms } }; - var geometryAtoms = build.geometryAtoms; - var geometryBonds = build.geometryBonds; - var i, l; - var x, y, z; - var verticesAtoms = []; - var colorsAtoms = []; - var verticesBonds = []; // atoms - - for ( i = 0, l = atoms.length; i < l; i ++ ) { - - var atom = atoms[ i ]; - x = atom[ 0 ]; - y = atom[ 1 ]; - z = atom[ 2 ]; + const geometryAtoms = build.geometryAtoms; + const geometryBonds = build.geometryBonds; + const verticesAtoms = []; + const colorsAtoms = []; + const verticesBonds = []; // atoms + + for ( let i = 0, l = atoms.length; i < l; i ++ ) { + + const atom = atoms[ i ]; + const x = atom[ 0 ]; + const y = atom[ 1 ]; + const z = atom[ 2 ]; verticesAtoms.push( x, y, z ); - var r = atom[ 3 ][ 0 ] / 255; - var g = atom[ 3 ][ 1 ] / 255; - var b = atom[ 3 ][ 2 ] / 255; + const r = atom[ 3 ][ 0 ] / 255; + const g = atom[ 3 ][ 1 ] / 255; + const b = atom[ 3 ][ 2 ] / 255; colorsAtoms.push( r, g, b ); } // bonds - for ( i = 0, l = _bonds.length; i < l; i ++ ) { + for ( let i = 0, l = _bonds.length; i < l; i ++ ) { - var bond = _bonds[ i ]; - var start = bond[ 0 ]; - var end = bond[ 1 ]; - var startAtom = _atomMap[ start ]; - var endAtom = _atomMap[ end ]; - x = startAtom[ 0 ]; - y = startAtom[ 1 ]; - z = startAtom[ 2 ]; + const bond = _bonds[ i ]; + const start = bond[ 0 ]; + const end = bond[ 1 ]; + const startAtom = _atomMap[ start ]; + const endAtom = _atomMap[ end ]; + let x = startAtom[ 0 ]; + let y = startAtom[ 1 ]; + let z = startAtom[ 2 ]; verticesBonds.push( x, y, z ); x = endAtom[ 0 ]; y = endAtom[ 1 ]; @@ -143,7 +142,7 @@ } - var CPK = { + const CPK = { h: [ 255, 255, 255 ], he: [ 217, 255, 255 ], li: [ 204, 128, 255 ], @@ -263,23 +262,22 @@ uus: [ 235, 0, 38 ], uuo: [ 235, 0, 38 ] }; - var atoms = []; - var _bonds = []; - var _bhash = {}; - var _atomMap = {}; - var x, y, z, index, e; // parse + const atoms = []; + const _bonds = []; + const _bhash = {}; + const _atomMap = {}; // parse - var lines = text.split( '\n' ); + const lines = text.split( '\n' ); - for ( var i = 0, l = lines.length; i < l; i ++ ) { + for ( let i = 0, l = lines.length; i < l; i ++ ) { if ( lines[ i ].substr( 0, 4 ) === 'ATOM' || lines[ i ].substr( 0, 6 ) === 'HETATM' ) { - x = parseFloat( lines[ i ].substr( 30, 7 ) ); - y = parseFloat( lines[ i ].substr( 38, 7 ) ); - z = parseFloat( lines[ i ].substr( 46, 7 ) ); - index = parseInt( lines[ i ].substr( 6, 5 ) ) - 1; - e = trim( lines[ i ].substr( 76, 2 ) ).toLowerCase(); + const x = parseFloat( lines[ i ].substr( 30, 7 ) ); + const y = parseFloat( lines[ i ].substr( 38, 7 ) ); + const z = parseFloat( lines[ i ].substr( 46, 7 ) ); + const index = parseInt( lines[ i ].substr( 6, 5 ) ) - 1; + let e = trim( lines[ i ].substr( 76, 2 ) ).toLowerCase(); if ( e === '' ) { @@ -287,17 +285,17 @@ } - var atomData = [ x, y, z, CPK[ e ], capitalize( e ) ]; + const atomData = [ x, y, z, CPK[ e ], capitalize( e ) ]; atoms.push( atomData ); _atomMap[ index ] = atomData; } else if ( lines[ i ].substr( 0, 6 ) === 'CONECT' ) { - var satom = parseInt( lines[ i ].substr( 6, 5 ) ); - parseBond( 11, 5 ); - parseBond( 16, 5 ); - parseBond( 21, 5 ); - parseBond( 26, 5 ); + const satom = parseInt( lines[ i ].substr( 6, 5 ) ); + parseBond( 11, 5, satom, i ); + parseBond( 16, 5, satom, i ); + parseBond( 21, 5, satom, i ); + parseBond( 26, 5, satom, i ); } @@ -307,7 +305,8 @@ return buildGeometry(); } - } ); + + } THREE.PDBLoader = PDBLoader; diff --git a/examples/js/loaders/PLYLoader.js b/examples/js/loaders/PLYLoader.js index 9bb2171770ce92..a46a2f06901c03 100644 --- a/examples/js/loaders/PLYLoader.js +++ b/examples/js/loaders/PLYLoader.js @@ -7,7 +7,7 @@ * Limitations: ASCII decoding assumes file is UTF-8. * * Usage: - * var loader = new PLYLoader(); + * const loader = new PLYLoader(); * loader.load('./models/ply/ascii/dolphins.ply', function (geometry) { * * scene.add( new THREE.Mesh( geometry ) ); @@ -26,19 +26,19 @@ * */ - var PLYLoader = function ( manager ) { + class PLYLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); - this.propertyNameMapping = {}; + constructor( manager ) { - }; + super( manager ); + this.propertyNameMapping = {}; - PLYLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: PLYLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new THREE.FileLoader( this.manager ); + const scope = this; + const loader = new THREE.FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( this.requestHeader ); @@ -67,20 +67,22 @@ }, onProgress, onError ); - }, - setPropertyNameMapping: function ( mapping ) { + } + + setPropertyNameMapping( mapping ) { this.propertyNameMapping = mapping; - }, - parse: function ( data ) { + } + + parse( data ) { function parseHeader( data ) { - var patternHeader = /ply([\s\S]*)end_header\r?\n/; - var headerText = ''; - var headerLength = 0; - var result = patternHeader.exec( data ); + const patternHeader = /ply([\s\S]*)end_header\r?\n/; + let headerText = ''; + let headerLength = 0; + const result = patternHeader.exec( data ); if ( result !== null ) { @@ -89,19 +91,18 @@ } - var header = { + const header = { comments: [], elements: [], headerLength: headerLength, objInfo: '' }; - var lines = headerText.split( '\n' ); - var currentElement; - var lineType, lineValues; + const lines = headerText.split( '\n' ); + let currentElement; function make_ply_element_property( propertValues, propertyNameMapping ) { - var property = { + const property = { type: propertValues[ 0 ] }; @@ -127,13 +128,13 @@ } - for ( var i = 0; i < lines.length; i ++ ) { + for ( let i = 0; i < lines.length; i ++ ) { - var line = lines[ i ]; + let line = lines[ i ]; line = line.trim(); if ( line === '' ) continue; - lineValues = line.split( /\s+/ ); - lineType = lineValues.shift(); + const lineValues = line.split( /\s+/ ); + const lineType = lineValues.shift(); line = lineValues.join( ' ' ); switch ( lineType ) { @@ -215,17 +216,17 @@ function parseASCIIElement( properties, line ) { - var values = line.split( /\s+/ ); - var element = {}; + const values = line.split( /\s+/ ); + const element = {}; - for ( var i = 0; i < properties.length; i ++ ) { + for ( let i = 0; i < properties.length; i ++ ) { if ( properties[ i ].type === 'list' ) { - var list = []; - var n = parseASCIINumber( values.shift(), properties[ i ].countType ); + const list = []; + const n = parseASCIINumber( values.shift(), properties[ i ].countType ); - for ( var j = 0; j < n; j ++ ) { + for ( let j = 0; j < n; j ++ ) { list.push( parseASCIINumber( values.shift(), properties[ i ].itemType ) ); @@ -248,7 +249,7 @@ function parseASCII( data, header ) { // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format) - var buffer = { + const buffer = { indices: [], vertices: [], normals: [], @@ -256,9 +257,9 @@ faceVertexUvs: [], colors: [] }; - var result; - var patternBody = /end_header\s([\s\S]*)$/; - var body = ''; + let result; + const patternBody = /end_header\s([\s\S]*)$/; + let body = ''; if ( ( result = patternBody.exec( data ) ) !== null ) { @@ -266,13 +267,13 @@ } - var lines = body.split( '\n' ); - var currentElement = 0; - var currentElementCount = 0; + const lines = body.split( '\n' ); + let currentElement = 0; + let currentElementCount = 0; - for ( var i = 0; i < lines.length; i ++ ) { + for ( let i = 0; i < lines.length; i ++ ) { - var line = lines[ i ]; + let line = lines[ i ]; line = line.trim(); if ( line === '' ) { @@ -288,7 +289,7 @@ } - var element = parseASCIIElement( header.elements[ currentElement ].properties, line ); + const element = parseASCIIElement( header.elements[ currentElement ].properties, line ); handleElement( buffer, header.elements[ currentElement ].name, element ); currentElementCount ++; @@ -300,7 +301,7 @@ function postProcess( buffer ) { - var geometry = new THREE.BufferGeometry(); // mandatory buffer data + let geometry = new THREE.BufferGeometry(); // mandatory buffer data if ( buffer.indices.length > 0 ) { @@ -366,9 +367,9 @@ } else if ( elementName === 'face' ) { - var vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338 + const vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338 - var texcoord = element.texcoord; + const texcoord = element.texcoord; if ( vertex_indices.length === 3 ) { @@ -436,20 +437,20 @@ function binaryReadElement( dataview, at, properties, little_endian ) { - var element = {}; - var result, + const element = {}; + let result, read = 0; - for ( var i = 0; i < properties.length; i ++ ) { + for ( let i = 0; i < properties.length; i ++ ) { if ( properties[ i ].type === 'list' ) { - var list = []; + const list = []; result = binaryRead( dataview, at + read, properties[ i ].countType, little_endian ); - var n = result[ 0 ]; + const n = result[ 0 ]; read += result[ 1 ]; - for ( var j = 0; j < n; j ++ ) { + for ( let j = 0; j < n; j ++ ) { result = binaryRead( dataview, at + read, properties[ i ].itemType, little_endian ); list.push( result[ 0 ] ); @@ -475,7 +476,7 @@ function parseBinary( data, header ) { - var buffer = { + const buffer = { indices: [], vertices: [], normals: [], @@ -483,18 +484,18 @@ faceVertexUvs: [], colors: [] }; - var little_endian = header.format === 'binary_little_endian'; - var body = new DataView( data, header.headerLength ); - var result, + const little_endian = header.format === 'binary_little_endian'; + const body = new DataView( data, header.headerLength ); + let result, loc = 0; - for ( var currentElement = 0; currentElement < header.elements.length; currentElement ++ ) { + for ( let currentElement = 0; currentElement < header.elements.length; currentElement ++ ) { - for ( var currentElementCount = 0; currentElementCount < header.elements[ currentElement ].count; currentElementCount ++ ) { + for ( let currentElementCount = 0; currentElementCount < header.elements[ currentElement ].count; currentElementCount ++ ) { result = binaryReadElement( body, loc, header.elements[ currentElement ].properties, little_endian ); loc += result[ 1 ]; - var element = result[ 0 ]; + const element = result[ 0 ]; handleElement( buffer, header.elements[ currentElement ].name, element ); } @@ -506,13 +507,13 @@ } // - var geometry; - var scope = this; + let geometry; + const scope = this; if ( data instanceof ArrayBuffer ) { - var text = THREE.LoaderUtils.decodeText( new Uint8Array( data ) ); - var header = parseHeader( text ); + const text = THREE.LoaderUtils.decodeText( new Uint8Array( data ) ); + const header = parseHeader( text ); geometry = header.format === 'ascii' ? parseASCII( text, header ) : parseBinary( data, header ); } else { @@ -524,7 +525,8 @@ return geometry; } - } ); + + } THREE.PLYLoader = PLYLoader; diff --git a/examples/js/loaders/PVRLoader.js b/examples/js/loaders/PVRLoader.js index b416d0ca22e102..3184cf9916aae8 100644 --- a/examples/js/loaders/PVRLoader.js +++ b/examples/js/loaders/PVRLoader.js @@ -6,19 +6,19 @@ * TODO : implement loadMipmaps option */ - var PVRLoader = function ( manager ) { + class PVRLoader extends THREE.CompressedTextureLoader { - THREE.CompressedTextureLoader.call( this, manager ); + constructor( manager ) { - }; + super( manager ); - PVRLoader.prototype = Object.assign( Object.create( THREE.CompressedTextureLoader.prototype ), { - constructor: PVRLoader, - parse: function ( buffer, loadMipmaps ) { + } + + parse( buffer, loadMipmaps ) { - var headerLengthInt = 13; - var header = new Uint32Array( buffer, 0, headerLengthInt ); - var pvrDatas = { + const headerLengthInt = 13; + const header = new Uint32Array( buffer, 0, headerLengthInt ); + const pvrDatas = { buffer: buffer, header: header, loadMipmaps: loadMipmaps @@ -27,12 +27,12 @@ if ( header[ 0 ] === 0x03525650 ) { // PVR v3 - return PVRLoader._parseV3( pvrDatas ); + return _parseV3( pvrDatas ); } else if ( header[ 11 ] === 0x21525650 ) { // PVR v2 - return PVRLoader._parseV2( pvrDatas ); + return _parseV2( pvrDatas ); } else { @@ -41,13 +41,14 @@ } } - } ); - PVRLoader._parseV3 = function ( pvrDatas ) { + } + + function _parseV3( pvrDatas ) { - var header = pvrDatas.header; - var bpp, format; - var metaLen = header[ 12 ], + const header = pvrDatas.header; + let bpp, format; + const metaLen = header[ 12 ], pixelFormat = header[ 2 ], height = header[ 6 ], width = header[ 7 ], @@ -94,14 +95,14 @@ pvrDatas.numSurfaces = numFaces; pvrDatas.numMipmaps = numMipmaps; pvrDatas.isCubemap = numFaces === 6; - return PVRLoader._extract( pvrDatas ); + return _extract( pvrDatas ); - }; + } - PVRLoader._parseV2 = function ( pvrDatas ) { + function _parseV2( pvrDatas ) { - var header = pvrDatas.header; - var headerLength = header[ 0 ], + const header = pvrDatas.header; + const headerLength = header[ 0 ], height = header[ 1 ], width = header[ 2 ], numMipmaps = header[ 3 ], @@ -114,13 +115,13 @@ bitmaskAlpha = header[ 10 ], // pvrTag = header[ 11 ], numSurfs = header[ 12 ]; - var TYPE_MASK = 0xff; - var PVRTC_2 = 24, + const TYPE_MASK = 0xff; + const PVRTC_2 = 24, PVRTC_4 = 25; - var formatFlags = flags & TYPE_MASK; - var bpp, format; + const formatFlags = flags & TYPE_MASK; + let bpp, format; - var _hasAlpha = bitmaskAlpha > 0; + const _hasAlpha = bitmaskAlpha > 0; if ( formatFlags === PVRTC_4 ) { @@ -148,13 +149,13 @@ // it juste a pvr containing 6 surface (no explicit cubemap type) pvrDatas.isCubemap = numSurfs === 6; - return PVRLoader._extract( pvrDatas ); + return _extract( pvrDatas ); - }; + } - PVRLoader._extract = function ( pvrDatas ) { + function _extract( pvrDatas ) { - var pvr = { + const pvr = { mipmaps: [], width: pvrDatas.width, height: pvrDatas.height, @@ -162,16 +163,16 @@ mipmapCount: pvrDatas.numMipmaps, isCubemap: pvrDatas.isCubemap }; - var buffer = pvrDatas.buffer; - var dataOffset = pvrDatas.dataPtr, - bpp = pvrDatas.bpp, - numSurfs = pvrDatas.numSurfaces, + const buffer = pvrDatas.buffer; + let dataOffset = pvrDatas.dataPtr, dataSize = 0, blockSize = 0, blockWidth = 0, blockHeight = 0, widthBlocks = 0, heightBlocks = 0; + const bpp = pvrDatas.bpp, + numSurfs = pvrDatas.numSurfaces; if ( bpp === 2 ) { @@ -187,11 +188,11 @@ blockSize = blockWidth * blockHeight * bpp / 8; pvr.mipmaps.length = pvrDatas.numMipmaps * numSurfs; - var mipLevel = 0; + let mipLevel = 0; while ( mipLevel < pvrDatas.numMipmaps ) { - var sWidth = pvrDatas.width >> mipLevel, + const sWidth = pvrDatas.width >> mipLevel, sHeight = pvrDatas.height >> mipLevel; widthBlocks = sWidth / blockWidth; heightBlocks = sHeight / blockHeight; // Clamp to minimum number of blocks @@ -200,10 +201,10 @@ if ( heightBlocks < 2 ) heightBlocks = 2; dataSize = widthBlocks * heightBlocks * blockSize; - for ( var surfIndex = 0; surfIndex < numSurfs; surfIndex ++ ) { + for ( let surfIndex = 0; surfIndex < numSurfs; surfIndex ++ ) { - var byteArray = new Uint8Array( buffer, dataOffset, dataSize ); - var mipmap = { + const byteArray = new Uint8Array( buffer, dataOffset, dataSize ); + const mipmap = { data: byteArray, width: sWidth, height: sHeight @@ -219,7 +220,7 @@ return pvr; - }; + } THREE.PVRLoader = PVRLoader; diff --git a/examples/js/loaders/RGBELoader.js b/examples/js/loaders/RGBELoader.js index 66f7d5a09ead05..790a2a5c507f6d 100644 --- a/examples/js/loaders/RGBELoader.js +++ b/examples/js/loaders/RGBELoader.js @@ -2,19 +2,19 @@ // http://en.wikipedia.org/wiki/RGBE_image_format - var RGBELoader = function ( manager ) { + class RGBELoader extends THREE.DataTextureLoader { - THREE.DataTextureLoader.call( this, manager ); - this.type = THREE.UnsignedByteType; + constructor( manager ) { - }; + super( manager ); + this.type = THREE.UnsignedByteType; - RGBELoader.prototype = Object.assign( Object.create( THREE.DataTextureLoader.prototype ), { - constructor: RGBELoader, - // adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html - parse: function ( buffer ) { + } // adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html - var + + parse( buffer ) { + + const /* return codes for rgbe routines */ //RGBE_RETURN_SUCCESS = 0, RGBE_RETURN_FAILURE = - 1, @@ -65,12 +65,12 @@ NEWLINE = '\n', fgets = function ( buffer, lineLimit, consume ) { + const chunkSize = 128; lineLimit = ! lineLimit ? 1024 : lineLimit; - var p = buffer.pos, + let p = buffer.pos, i = - 1, len = 0, s = '', - chunkSize = 128, chunk = String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) ); while ( 0 > ( i = chunk.indexOf( NEWLINE ) ) && len < lineLimit && p < buffer.byteLength ) { @@ -102,10 +102,8 @@ /* minimal header reading. modify if you want to parse more information */ RGBE_ReadHeader = function ( buffer ) { - var line, - match, - // regexes to parse header info fields - magic_token_re = /^#\?(\S+)/, + // regexes to parse header info fields + const magic_token_re = /^#\?(\S+)/, gamma_re = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/, exposure_re = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/, format_re = /^\s*FORMAT=(\S+)\s*$/, @@ -138,6 +136,7 @@ /* image dimensions, width/height */ }; + let line, match; if ( buffer.pos >= buffer.byteLength || ! ( line = fgets( buffer ) ) ) { @@ -218,21 +217,7 @@ }, RGBE_ReadPixels_RLE = function ( buffer, w, h ) { - var data_rgba, - offset, - pos, - count, - byteValue, - scanline_buffer, - ptr, - ptr_end, - i, - l, - off, - isEncodedRun, - scanline_width = w, - num_scanlines = h, - rgbeStart; + const scanline_width = w; if ( // run length encoding is not allowed so read flat scanline_width < 8 || scanline_width > 0x7fff || // this file is not run length encoded @@ -249,7 +234,7 @@ } - data_rgba = new Uint8Array( 4 * w * h ); + const data_rgba = new Uint8Array( 4 * w * h ); if ( ! data_rgba.length ) { @@ -257,11 +242,12 @@ } - offset = 0; - pos = 0; - ptr_end = 4 * scanline_width; - rgbeStart = new Uint8Array( 4 ); - scanline_buffer = new Uint8Array( ptr_end ); // read in each successive scanline + let offset = 0, + pos = 0; + const ptr_end = 4 * scanline_width; + const rgbeStart = new Uint8Array( 4 ); + const scanline_buffer = new Uint8Array( ptr_end ); + let num_scanlines = h; // read in each successive scanline while ( num_scanlines > 0 && pos < buffer.byteLength ) { @@ -284,12 +270,13 @@ // first red, then green, then blue, then exponent - ptr = 0; + let ptr = 0, + count; while ( ptr < ptr_end && pos < buffer.byteLength ) { count = buffer[ pos ++ ]; - isEncodedRun = count > 128; + const isEncodedRun = count > 128; if ( isEncodedRun ) count -= 128; if ( 0 === count || ptr + count > ptr_end ) { @@ -301,9 +288,9 @@ if ( isEncodedRun ) { // a (encoded) run of the same value - byteValue = buffer[ pos ++ ]; + const byteValue = buffer[ pos ++ ]; - for ( i = 0; i < count; i ++ ) { + for ( let i = 0; i < count; i ++ ) { scanline_buffer[ ptr ++ ] = byteValue; @@ -322,11 +309,11 @@ // first red, then green, then blue, then exponent (alpha) - l = scanline_width; //scanline_buffer.byteLength; + const l = scanline_width; //scanline_buffer.byteLength; - for ( i = 0; i < l; i ++ ) { + for ( let i = 0; i < l; i ++ ) { - off = 0; + let off = 0; data_rgba[ offset ] = scanline_buffer[ i + off ]; off += scanline_width; //1; @@ -349,75 +336,78 @@ }; - var RGBEByteToRGBFloat = function ( sourceArray, sourceOffset, destArray, destOffset ) { + const RGBEByteToRGBFloat = function ( sourceArray, sourceOffset, destArray, destOffset ) { - var e = sourceArray[ sourceOffset + 3 ]; - var scale = Math.pow( 2.0, e - 128.0 ) / 255.0; + const e = sourceArray[ sourceOffset + 3 ]; + const scale = Math.pow( 2.0, e - 128.0 ) / 255.0; destArray[ destOffset + 0 ] = sourceArray[ sourceOffset + 0 ] * scale; destArray[ destOffset + 1 ] = sourceArray[ sourceOffset + 1 ] * scale; destArray[ destOffset + 2 ] = sourceArray[ sourceOffset + 2 ] * scale; }; - var RGBEByteToRGBHalf = function ( sourceArray, sourceOffset, destArray, destOffset ) { + const RGBEByteToRGBHalf = function ( sourceArray, sourceOffset, destArray, destOffset ) { - var e = sourceArray[ sourceOffset + 3 ]; - var scale = Math.pow( 2.0, e - 128.0 ) / 255.0; + const e = sourceArray[ sourceOffset + 3 ]; + const scale = Math.pow( 2.0, e - 128.0 ) / 255.0; destArray[ destOffset + 0 ] = THREE.DataUtils.toHalfFloat( sourceArray[ sourceOffset + 0 ] * scale ); destArray[ destOffset + 1 ] = THREE.DataUtils.toHalfFloat( sourceArray[ sourceOffset + 1 ] * scale ); destArray[ destOffset + 2 ] = THREE.DataUtils.toHalfFloat( sourceArray[ sourceOffset + 2 ] * scale ); }; - var byteArray = new Uint8Array( buffer ); + const byteArray = new Uint8Array( buffer ); byteArray.pos = 0; - var rgbe_header_info = RGBE_ReadHeader( byteArray ); + const rgbe_header_info = RGBE_ReadHeader( byteArray ); if ( RGBE_RETURN_FAILURE !== rgbe_header_info ) { - var w = rgbe_header_info.width, + const w = rgbe_header_info.width, h = rgbe_header_info.height, image_rgba_data = RGBE_ReadPixels_RLE( byteArray.subarray( byteArray.pos ), w, h ); if ( RGBE_RETURN_FAILURE !== image_rgba_data ) { + let data, format, type; + let numElements; + switch ( this.type ) { case THREE.UnsignedByteType: - var data = image_rgba_data; - var format = THREE.RGBEFormat; // handled as THREE.RGBAFormat in shaders + data = image_rgba_data; + format = THREE.RGBEFormat; // handled as THREE.RGBAFormat in shaders - var type = THREE.UnsignedByteType; + type = THREE.UnsignedByteType; break; case THREE.FloatType: - var numElements = image_rgba_data.length / 4 * 3; - var floatArray = new Float32Array( numElements ); + numElements = image_rgba_data.length / 4 * 3; + const floatArray = new Float32Array( numElements ); - for ( var j = 0; j < numElements; j ++ ) { + for ( let j = 0; j < numElements; j ++ ) { RGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 3 ); } - var data = floatArray; - var format = THREE.RGBFormat; - var type = THREE.FloatType; + data = floatArray; + format = THREE.RGBFormat; + type = THREE.FloatType; break; case THREE.HalfFloatType: - var numElements = image_rgba_data.length / 4 * 3; - var halfArray = new Uint16Array( numElements ); + numElements = image_rgba_data.length / 4 * 3; + const halfArray = new Uint16Array( numElements ); - for ( var j = 0; j < numElements; j ++ ) { + for ( let j = 0; j < numElements; j ++ ) { RGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 3 ); } - var data = halfArray; - var format = THREE.RGBFormat; - var type = THREE.HalfFloatType; + data = halfArray; + format = THREE.RGBFormat; + type = THREE.HalfFloatType; break; default: @@ -443,14 +433,16 @@ return null; - }, - setDataType: function ( value ) { + } + + setDataType( value ) { this.type = value; return this; - }, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { function onLoadCallback( texture, texData ) { @@ -486,10 +478,11 @@ } - return THREE.DataTextureLoader.prototype.load.call( this, url, onLoadCallback, onProgress, onError ); + return super.load( url, onLoadCallback, onProgress, onError ); } - } ); + + } THREE.RGBELoader = RGBELoader; diff --git a/examples/js/loaders/STLLoader.js b/examples/js/loaders/STLLoader.js index 77886ea3e5a45c..e4059bfcc35283 100644 --- a/examples/js/loaders/STLLoader.js +++ b/examples/js/loaders/STLLoader.js @@ -13,7 +13,7 @@ * ASCII decoding assumes file is UTF-8. * * Usage: - * var loader = new STLLoader(); + * const loader = new STLLoader(); * loader.load( './models/stl/slotted_disk.stl', function ( geometry ) { * scene.add( new THREE.Mesh( geometry ) ); * }); @@ -23,24 +23,24 @@ * if (geometry.hasColors) { * material = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: true }); * } else { .... } - * var mesh = new THREE.Mesh( geometry, material ); + * const mesh = new THREE.Mesh( geometry, material ); * * For ASCII STLs containing multiple solids, each solid is assigned to a different group. * Groups can be used to assign a different color by defining an array of materials with the same length of * geometry.groups and passing it to the Mesh constructor: * - * var mesh = new THREE.Mesh( geometry, material ); + * const mesh = new THREE.Mesh( geometry, material ); * * For example: * - * var materials = []; - * var nGeometryGroups = geometry.groups.length; + * const materials = []; + * const nGeometryGroups = geometry.groups.length; * - * var colorMap = ...; // Some logic to index colors. + * const colorMap = ...; // Some logic to index colors. * - * for (var i = 0; i < nGeometryGroups; i++) { + * for (let i = 0; i < nGeometryGroups; i++) { * - * var material = new THREE.MeshPhongMaterial({ + * const material = new THREE.MeshPhongMaterial({ * color: colorMap[i], * wireframe: false * }); @@ -48,21 +48,21 @@ * } * * materials.push(material); - * var mesh = new THREE.Mesh(geometry, materials); + * const mesh = new THREE.Mesh(geometry, materials); */ - var STLLoader = function ( manager ) { + class STLLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); + constructor( manager ) { - }; + super( manager ); - STLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: STLLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new THREE.FileLoader( this.manager ); + const scope = this; + const loader = new THREE.FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( this.requestHeader ); @@ -91,16 +91,16 @@ }, onProgress, onError ); - }, - parse: function ( data ) { + } + + parse( data ) { function isBinary( data ) { - var expect, face_size, n_faces, reader; - reader = new DataView( data ); - face_size = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8; - n_faces = reader.getUint32( 80, true ); - expect = 80 + 32 / 8 + n_faces * face_size; + const reader = new DataView( data ); + const face_size = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8; + const n_faces = reader.getUint32( 80, true ); + const expect = 80 + 32 / 8 + n_faces * face_size; if ( expect === reader.byteLength ) { @@ -115,9 +115,9 @@ // US-ASCII ordinal values for 's', 'o', 'l', 'i', 'd' - var solid = [ 115, 111, 108, 105, 100 ]; + const solid = [ 115, 111, 108, 105, 100 ]; - for ( var off = 0; off < 5; off ++ ) { + for ( let off = 0; off < 5; off ++ ) { // If "solid" text is matched to the current offset, declare it to be an ASCII STL. if ( matchDataViewAt( solid, reader, off ) ) return false; @@ -132,7 +132,7 @@ function matchDataViewAt( query, reader, offset ) { // Check if each byte in query matches the corresponding byte from the current offset - for ( var i = 0, il = query.length; i < il; i ++ ) { + for ( let i = 0, il = query.length; i < il; i ++ ) { if ( query[ i ] !== reader.getUint8( offset + i, false ) ) return false; @@ -144,17 +144,17 @@ function parseBinary( data ) { - var reader = new DataView( data ); - var faces = reader.getUint32( 80, true ); - var r, + const reader = new DataView( data ); + const faces = reader.getUint32( 80, true ); + let r, g, b, hasColors = false, colors; - var defaultR, defaultG, defaultB, alpha; // process STL header + let defaultR, defaultG, defaultB, alpha; // process STL header // check for default color in header ("COLOR=rgba" sequence). - for ( var index = 0; index < 80 - 10; index ++ ) { + for ( let index = 0; index < 80 - 10; index ++ ) { if ( reader.getUint32( index, false ) == 0x434F4C4F /*COLO*/ @@ -175,22 +175,22 @@ } - var dataOffset = 84; - var faceLength = 12 * 4 + 2; - var geometry = new THREE.BufferGeometry(); - var vertices = new Float32Array( faces * 3 * 3 ); - var normals = new Float32Array( faces * 3 * 3 ); + const dataOffset = 84; + const faceLength = 12 * 4 + 2; + const geometry = new THREE.BufferGeometry(); + const vertices = new Float32Array( faces * 3 * 3 ); + const normals = new Float32Array( faces * 3 * 3 ); - for ( var face = 0; face < faces; face ++ ) { + for ( let face = 0; face < faces; face ++ ) { - var start = dataOffset + face * faceLength; - var normalX = reader.getFloat32( start, true ); - var normalY = reader.getFloat32( start + 4, true ); - var normalZ = reader.getFloat32( start + 8, true ); + const start = dataOffset + face * faceLength; + const normalX = reader.getFloat32( start, true ); + const normalY = reader.getFloat32( start + 4, true ); + const normalZ = reader.getFloat32( start + 8, true ); if ( hasColors ) { - var packedColor = reader.getUint16( start + 48, true ); + const packedColor = reader.getUint16( start + 48, true ); if ( ( packedColor & 0x8000 ) === 0 ) { @@ -209,10 +209,10 @@ } - for ( var i = 1; i <= 3; i ++ ) { + for ( let i = 1; i <= 3; i ++ ) { - var vertexstart = start + i * 12; - var componentIdx = face * 3 * 3 + ( i - 1 ) * 3; + const vertexstart = start + i * 12; + const componentIdx = face * 3 * 3 + ( i - 1 ) * 3; vertices[ componentIdx ] = reader.getFloat32( vertexstart, true ); vertices[ componentIdx + 1 ] = reader.getFloat32( vertexstart + 4, true ); vertices[ componentIdx + 2 ] = reader.getFloat32( vertexstart + 8, true ); @@ -249,31 +249,31 @@ function parseASCII( data ) { - var geometry = new THREE.BufferGeometry(); - var patternSolid = /solid([\s\S]*?)endsolid/g; - var patternFace = /facet([\s\S]*?)endfacet/g; - var faceCounter = 0; - var patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source; - var patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' ); - var patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' ); - var vertices = []; - var normals = []; - var normal = new THREE.Vector3(); - var result; - var groupCount = 0; - var startVertex = 0; - var endVertex = 0; + const geometry = new THREE.BufferGeometry(); + const patternSolid = /solid([\s\S]*?)endsolid/g; + const patternFace = /facet([\s\S]*?)endfacet/g; + let faceCounter = 0; + const patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source; + const patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' ); + const patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' ); + const vertices = []; + const normals = []; + const normal = new THREE.Vector3(); + let result; + let groupCount = 0; + let startVertex = 0; + let endVertex = 0; while ( ( result = patternSolid.exec( data ) ) !== null ) { startVertex = endVertex; - var solid = result[ 0 ]; + const solid = result[ 0 ]; while ( ( result = patternFace.exec( solid ) ) !== null ) { - var vertexCountPerFace = 0; - var normalCountPerFace = 0; - var text = result[ 0 ]; + let vertexCountPerFace = 0; + let normalCountPerFace = 0; + const text = result[ 0 ]; while ( ( result = patternNormal.exec( text ) ) !== null ) { @@ -311,8 +311,8 @@ } - var start = startVertex; - var count = endVertex - startVertex; + const start = startVertex; + const count = endVertex - startVertex; geometry.addGroup( start, count, groupCount ); groupCount ++; @@ -340,9 +340,9 @@ if ( typeof buffer === 'string' ) { - var array_buffer = new Uint8Array( buffer.length ); + const array_buffer = new Uint8Array( buffer.length ); - for ( var i = 0; i < buffer.length; i ++ ) { + for ( let i = 0; i < buffer.length; i ++ ) { array_buffer[ i ] = buffer.charCodeAt( i ) & 0xff; // implicitly assumes little-endian @@ -359,11 +359,12 @@ } // start - var binData = ensureBinary( data ); + const binData = ensureBinary( data ); return isBinary( binData ) ? parseBinary( binData ) : parseASCII( ensureString( data ) ); } - } ); + + } THREE.STLLoader = STLLoader; diff --git a/examples/js/loaders/TDSLoader.js b/examples/js/loaders/TDSLoader.js index 060485cce3c6e5..0809e48294c48c 100644 --- a/examples/js/loaders/TDSLoader.js +++ b/examples/js/loaders/TDSLoader.js @@ -9,20 +9,18 @@ * @constructor */ - var TDSLoader = function ( manager ) { + class TDSLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); - this.debug = false; - this.group = null; - this.position = 0; - this.materials = []; - this.meshes = []; + constructor( manager ) { - }; - - TDSLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: TDSLoader, + super( manager ); + this.debug = false; + this.group = null; + this.position = 0; + this.materials = []; + this.meshes = []; + } /** * Load 3ds file from url. * @@ -32,11 +30,13 @@ * @param {Function} onProgress onProgress callback. * @param {Function} onError onError callback. */ - load: function ( url, onLoad, onProgress, onError ) { - var scope = this; - var path = this.path === '' ? THREE.LoaderUtils.extractUrlBase( url ) : this.path; - var loader = new THREE.FileLoader( this.manager ); + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + const path = this.path === '' ? THREE.LoaderUtils.extractUrlBase( url ) : this.path; + const loader = new THREE.FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( this.requestHeader ); @@ -65,8 +65,7 @@ }, onProgress, onError ); - }, - + } /** * Parse arraybuffer data and load 3ds file. * @@ -75,7 +74,9 @@ * @param {String} path Path for external resources. * @return {Group} THREE.Group loaded from 3ds file. */ - parse: function ( arraybuffer, path ) { + + + parse( arraybuffer, path ) { this.group = new THREE.Group(); this.position = 0; @@ -83,7 +84,7 @@ this.meshes = []; this.readFile( arraybuffer, path ); - for ( var i = 0; i < this.meshes.length; i ++ ) { + for ( let i = 0; i < this.meshes.length; i ++ ) { this.group.add( this.meshes[ i ] ); @@ -91,8 +92,7 @@ return this.group; - }, - + } /** * Decode file content to read 3ds data. * @@ -100,20 +100,22 @@ * @param {ArrayBuffer} arraybuffer Arraybuffer data to be loaded. * @param {String} path Path for external resources. */ - readFile: function ( arraybuffer, path ) { - var data = new DataView( arraybuffer ); - var chunk = this.readChunk( data ); + + readFile( arraybuffer, path ) { + + const data = new DataView( arraybuffer ); + const chunk = this.readChunk( data ); if ( chunk.id === MLIBMAGIC || chunk.id === CMAGIC || chunk.id === M3DMAGIC ) { - var next = this.nextChunk( data, chunk ); + let next = this.nextChunk( data, chunk ); while ( next !== 0 ) { if ( next === M3D_VERSION ) { - var version = this.readDWord( data ); + const version = this.readDWord( data ); this.debugMessage( '3DS file version: ' + version ); } else if ( next === MDATA ) { @@ -135,8 +137,7 @@ this.debugMessage( 'Parsed ' + this.meshes.length + ' meshes' ); - }, - + } /** * Read mesh data chunk. * @@ -144,21 +145,23 @@ * @param {Dataview} data Dataview in use. * @param {String} path Path for external resources. */ - readMeshData: function ( data, path ) { - var chunk = this.readChunk( data ); - var next = this.nextChunk( data, chunk ); + + readMeshData( data, path ) { + + const chunk = this.readChunk( data ); + let next = this.nextChunk( data, chunk ); while ( next !== 0 ) { if ( next === MESH_VERSION ) { - var version = + this.readDWord( data ); + const version = + this.readDWord( data ); this.debugMessage( 'Mesh Version: ' + version ); } else if ( next === MASTER_SCALE ) { - var scale = this.readFloat( data ); + const scale = this.readFloat( data ); this.debugMessage( 'Master scale: ' + scale ); this.group.scale.set( scale, scale, scale ); @@ -184,27 +187,28 @@ } - }, - + } /** * Read named object chunk. * * @method readNamedObject * @param {Dataview} data Dataview in use. */ - readNamedObject: function ( data ) { - var chunk = this.readChunk( data ); - var name = this.readString( data, 64 ); + + readNamedObject( data ) { + + const chunk = this.readChunk( data ); + const name = this.readString( data, 64 ); chunk.cur = this.position; - var next = this.nextChunk( data, chunk ); + let next = this.nextChunk( data, chunk ); while ( next !== 0 ) { if ( next === N_TRI_OBJECT ) { this.resetPosition( data ); - var mesh = this.readMesh( data ); + const mesh = this.readMesh( data ); mesh.name = name; this.meshes.push( mesh ); @@ -220,8 +224,7 @@ this.endChunk( chunk ); - }, - + } /** * Read material data chunk and add it to the material list. * @@ -229,11 +232,13 @@ * @param {Dataview} data Dataview in use. * @param {String} path Path for external resources. */ - readMaterialEntry: function ( data, path ) { - var chunk = this.readChunk( data ); - var next = this.nextChunk( data, chunk ); - var material = new THREE.MeshPhongMaterial(); + + readMaterialEntry( data, path ) { + + const chunk = this.readChunk( data ); + let next = this.nextChunk( data, chunk ); + const material = new THREE.MeshPhongMaterial(); while ( next !== 0 ) { @@ -249,7 +254,7 @@ } else if ( next === MAT_WIRE_SIZE ) { - var value = this.readByte( data ); + const value = this.readByte( data ); material.wireframeLinewidth = value; this.debugMessage( ' Wireframe Thickness: ' + value ); @@ -280,13 +285,13 @@ } else if ( next === MAT_SHININESS ) { - var shininess = this.readPercentage( data ); + const shininess = this.readPercentage( data ); material.shininess = shininess * 100; this.debugMessage( ' Shininess : ' + shininess ); } else if ( next === MAT_TRANSPARENCY ) { - var transparency = this.readPercentage( data ); + const transparency = this.readPercentage( data ); material.opacity = 1 - transparency; this.debugMessage( ' Transparency : ' + transparency ); material.transparent = material.opacity < 1 ? true : false; @@ -328,8 +333,7 @@ this.endChunk( chunk ); this.materials[ material.name ] = material; - }, - + } /** * Read mesh data chunk. * @@ -337,26 +341,27 @@ * @param {Dataview} data Dataview in use. * @return {Mesh} The parsed mesh. */ - readMesh: function ( data ) { - - var chunk = this.readChunk( data ); - var next = this.nextChunk( data, chunk ); - var geometry = new THREE.BufferGeometry(); - var uvs = []; - var material = new THREE.MeshPhongMaterial(); - var mesh = new THREE.Mesh( geometry, material ); + + + readMesh( data ) { + + const chunk = this.readChunk( data ); + let next = this.nextChunk( data, chunk ); + const geometry = new THREE.BufferGeometry(); + const material = new THREE.MeshPhongMaterial(); + const mesh = new THREE.Mesh( geometry, material ); mesh.name = 'mesh'; while ( next !== 0 ) { if ( next === POINT_ARRAY ) { - var points = this.readWord( data ); + const points = this.readWord( data ); this.debugMessage( ' Vertex: ' + points ); //BufferGeometry - var vertices = []; + const vertices = []; - for ( var i = 0; i < points; i ++ ) { + for ( let i = 0; i < points; i ++ ) { vertices.push( this.readFloat( data ) ); vertices.push( this.readFloat( data ) ); @@ -373,12 +378,12 @@ } else if ( next === TEX_VERTS ) { - var texels = this.readWord( data ); + const texels = this.readWord( data ); this.debugMessage( ' UV: ' + texels ); //BufferGeometry - var uvs = []; + const uvs = []; - for ( var i = 0; i < texels; i ++ ) { + for ( let i = 0; i < texels; i ++ ) { uvs.push( this.readFloat( data ) ); uvs.push( this.readFloat( data ) ); @@ -390,15 +395,15 @@ } else if ( next === MESH_MATRIX ) { this.debugMessage( ' Tranformation Matrix (TODO)' ); - var values = []; + const values = []; - for ( var i = 0; i < 12; i ++ ) { + for ( let i = 0; i < 12; i ++ ) { values[ i ] = this.readFloat( data ); } - var matrix = new THREE.Matrix4(); //X Line + const matrix = new THREE.Matrix4(); //X Line matrix.elements[ 0 ] = values[ 0 ]; matrix.elements[ 1 ] = values[ 6 ]; @@ -420,7 +425,7 @@ matrix.elements[ 14 ] = 0; matrix.elements[ 15 ] = 1; matrix.transpose(); - var inverse = new THREE.Matrix4(); + const inverse = new THREE.Matrix4(); inverse.copy( matrix ).invert(); geometry.applyMatrix4( inverse ); matrix.decompose( mesh.position, mesh.quaternion, mesh.scale ); @@ -439,8 +444,7 @@ geometry.computeVertexNormals(); return mesh; - }, - + } /** * Read face array data chunk. * @@ -448,14 +452,16 @@ * @param {Dataview} data Dataview in use. * @param {Mesh} mesh THREE.Mesh to be filled with the data read. */ - readFaceArray: function ( data, mesh ) { - var chunk = this.readChunk( data ); - var faces = this.readWord( data ); + + readFaceArray( data, mesh ) { + + const chunk = this.readChunk( data ); + const faces = this.readWord( data ); this.debugMessage( ' Faces: ' + faces ); - var index = []; + const index = []; - for ( var i = 0; i < faces; ++ i ) { + for ( let i = 0; i < faces; ++ i ) { index.push( this.readWord( data ), this.readWord( data ), this.readWord( data ) ); this.readWord( data ); // visibility @@ -464,24 +470,24 @@ mesh.geometry.setIndex( index ); //The rest of the FACE_ARRAY chunk is subchunks - var materialIndex = 0; - var start = 0; + let materialIndex = 0; + let start = 0; while ( this.position < chunk.end ) { - var subchunk = this.readChunk( data ); + const subchunk = this.readChunk( data ); if ( subchunk.id === MSH_MAT_GROUP ) { this.debugMessage( ' Material THREE.Group' ); this.resetPosition( data ); - var group = this.readMaterialGroup( data ); - var count = group.index.length * 3; // assuming successive indices + const group = this.readMaterialGroup( data ); + const count = group.index.length * 3; // assuming successive indices mesh.geometry.addGroup( start, count, materialIndex ); start += count; materialIndex ++; - var material = this.materials[ group.name ]; + const material = this.materials[ group.name ]; if ( Array.isArray( mesh.material ) === false ) mesh.material = []; if ( material !== undefined ) { @@ -504,8 +510,7 @@ this.endChunk( chunk ); - }, - + } /** * Read texture map data chunk. * @@ -514,19 +519,21 @@ * @param {String} path Path for external resources. * @return {Texture} Texture read from this data chunk. */ - readMap: function ( data, path ) { - var chunk = this.readChunk( data ); - var next = this.nextChunk( data, chunk ); - var texture = {}; - var loader = new THREE.TextureLoader( this.manager ); + + readMap( data, path ) { + + const chunk = this.readChunk( data ); + let next = this.nextChunk( data, chunk ); + let texture = {}; + const loader = new THREE.TextureLoader( this.manager ); loader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin ); while ( next !== 0 ) { if ( next === MAT_MAPNAME ) { - var name = this.readString( data, 128 ); + const name = this.readString( data, 128 ); texture = loader.load( name ); this.debugMessage( ' File: ' + path + name ); @@ -563,8 +570,7 @@ this.endChunk( chunk ); return texture; - }, - + } /** * Read material group data chunk. * @@ -572,16 +578,18 @@ * @param {Dataview} data Dataview in use. * @return {Object} Object with name and index of the object. */ - readMaterialGroup: function ( data ) { + + + readMaterialGroup( data ) { this.readChunk( data ); - var name = this.readString( data, 64 ); - var numFaces = this.readWord( data ); + const name = this.readString( data, 64 ); + const numFaces = this.readWord( data ); this.debugMessage( ' Name: ' + name ); this.debugMessage( ' Faces: ' + numFaces ); - var index = []; + const index = []; - for ( var i = 0; i < numFaces; ++ i ) { + for ( let i = 0; i < numFaces; ++ i ) { index.push( this.readWord( data ) ); @@ -592,8 +600,7 @@ index: index }; - }, - + } /** * Read a color value. * @@ -601,24 +608,26 @@ * @param {DataView} data Dataview. * @return {Color} THREE.Color value read.. */ - readColor: function ( data ) { - var chunk = this.readChunk( data ); - var color = new THREE.Color(); + + readColor( data ) { + + const chunk = this.readChunk( data ); + const color = new THREE.Color(); if ( chunk.id === COLOR_24 || chunk.id === LIN_COLOR_24 ) { - var r = this.readByte( data ); - var g = this.readByte( data ); - var b = this.readByte( data ); + const r = this.readByte( data ); + const g = this.readByte( data ); + const b = this.readByte( data ); color.setRGB( r / 255, g / 255, b / 255 ); this.debugMessage( ' THREE.Color: ' + color.r + ', ' + color.g + ', ' + color.b ); } else if ( chunk.id === COLOR_F || chunk.id === LIN_COLOR_F ) { - var r = this.readFloat( data ); - var g = this.readFloat( data ); - var b = this.readFloat( data ); + const r = this.readFloat( data ); + const g = this.readFloat( data ); + const b = this.readFloat( data ); color.setRGB( r, g, b ); this.debugMessage( ' THREE.Color: ' + color.r + ', ' + color.g + ', ' + color.b ); @@ -631,8 +640,7 @@ this.endChunk( chunk ); return color; - }, - + } /** * Read next chunk of data. * @@ -640,9 +648,11 @@ * @param {DataView} data Dataview. * @return {Object} Chunk of data read. */ - readChunk: function ( data ) { - var chunk = {}; + + readChunk( data ) { + + const chunk = {}; chunk.cur = this.position; chunk.id = this.readWord( data ); chunk.size = this.readDWord( data ); @@ -650,20 +660,20 @@ chunk.cur += 6; return chunk; - }, - + } /** * Set position to the end of the current chunk of data. * * @method endChunk * @param {Object} chunk Data chunk. */ - endChunk: function ( chunk ) { - this.position = chunk.end; - }, + endChunk( chunk ) { + this.position = chunk.end; + + } /** * Move to the next data chunk. * @@ -671,7 +681,9 @@ * @param {DataView} data Dataview. * @param {Object} chunk Data chunk. */ - nextChunk: function ( data, chunk ) { + + + nextChunk( data, chunk ) { if ( chunk.cur >= chunk.end ) { @@ -683,7 +695,7 @@ try { - var next = this.readChunk( data ); + const next = this.readChunk( data ); chunk.cur += next.size; return next.id; @@ -694,19 +706,19 @@ } - }, - + } /** * Reset dataview position. * * @method resetPosition */ - resetPosition: function () { - this.position -= 6; - }, + resetPosition() { + this.position -= 6; + + } /** * Read byte value. * @@ -714,14 +726,15 @@ * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readByte: function ( data ) { - var v = data.getUint8( this.position, true ); + + readByte( data ) { + + const v = data.getUint8( this.position, true ); this.position += 1; return v; - }, - + } /** * Read 32 bit float value. * @@ -729,11 +742,13 @@ * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readFloat: function ( data ) { + + + readFloat( data ) { try { - var v = data.getFloat32( this.position, true ); + const v = data.getFloat32( this.position, true ); this.position += 4; return v; @@ -743,8 +758,7 @@ } - }, - + } /** * Read 32 bit signed integer value. * @@ -752,14 +766,15 @@ * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readInt: function ( data ) { - var v = data.getInt32( this.position, true ); + + readInt( data ) { + + const v = data.getInt32( this.position, true ); this.position += 4; return v; - }, - + } /** * Read 16 bit signed integer value. * @@ -767,14 +782,15 @@ * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readShort: function ( data ) { - var v = data.getInt16( this.position, true ); + + readShort( data ) { + + const v = data.getInt16( this.position, true ); this.position += 2; return v; - }, - + } /** * Read 64 bit unsigned integer value. * @@ -782,14 +798,15 @@ * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readDWord: function ( data ) { - var v = data.getUint32( this.position, true ); + + readDWord( data ) { + + const v = data.getUint32( this.position, true ); this.position += 4; return v; - }, - + } /** * Read 32 bit unsigned integer value. * @@ -797,14 +814,15 @@ * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readWord: function ( data ) { - var v = data.getUint16( this.position, true ); + + readWord( data ) { + + const v = data.getUint16( this.position, true ); this.position += 2; return v; - }, - + } /** * Read string value. * @@ -813,13 +831,15 @@ * @param {Number} maxLength Max size of the string to be read. * @return {String} Data read from the dataview. */ - readString: function ( data, maxLength ) { - var s = ''; - for ( var i = 0; i < maxLength; i ++ ) { + readString( data, maxLength ) { + + let s = ''; + + for ( let i = 0; i < maxLength; i ++ ) { - var c = this.readByte( data ); + const c = this.readByte( data ); if ( ! c ) { @@ -833,8 +853,7 @@ return s; - }, - + } /** * Read percentage value. * @@ -842,10 +861,12 @@ * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readPercentage: function ( data ) { - var chunk = this.readChunk( data ); - var value; + + readPercentage( data ) { + + const chunk = this.readChunk( data ); + let value; switch ( chunk.id ) { @@ -865,8 +886,7 @@ this.endChunk( chunk ); return value; - }, - + } /** * Print debug message to the console. * @@ -875,7 +895,9 @@ * @method debugMessage * @param {Object} message Debug message to print to the console. */ - debugMessage: function ( message ) { + + + debugMessage( message ) { if ( this.debug ) { @@ -884,155 +906,157 @@ } } - } ); // var NULL_CHUNK = 0x0000; - - var M3DMAGIC = 0x4D4D; // var SMAGIC = 0x2D2D; - // var LMAGIC = 0x2D3D; - - var MLIBMAGIC = 0x3DAA; // var MATMAGIC = 0x3DFF; - - var CMAGIC = 0xC23D; - var M3D_VERSION = 0x0002; // var M3D_KFVERSION = 0x0005; - - var COLOR_F = 0x0010; - var COLOR_24 = 0x0011; - var LIN_COLOR_24 = 0x0012; - var LIN_COLOR_F = 0x0013; - var INT_PERCENTAGE = 0x0030; - var FLOAT_PERCENTAGE = 0x0031; - var MDATA = 0x3D3D; - var MESH_VERSION = 0x3D3E; - var MASTER_SCALE = 0x0100; // var LO_SHADOW_BIAS = 0x1400; - // var HI_SHADOW_BIAS = 0x1410; - // var SHADOW_MAP_SIZE = 0x1420; - // var SHADOW_SAMPLES = 0x1430; - // var SHADOW_RANGE = 0x1440; - // var SHADOW_FILTER = 0x1450; - // var RAY_BIAS = 0x1460; - // var O_CONSTS = 0x1500; - // var AMBIENT_LIGHT = 0x2100; - // var BIT_MAP = 0x1100; - // var SOLID_BGND = 0x1200; - // var V_GRADIENT = 0x1300; - // var USE_BIT_MAP = 0x1101; - // var USE_SOLID_BGND = 0x1201; - // var USE_V_GRADIENT = 0x1301; - // var FOG = 0x2200; - // var FOG_BGND = 0x2210; - // var LAYER_FOG = 0x2302; - // var DISTANCE_CUE = 0x2300; - // var DCUE_BGND = 0x2310; - // var USE_FOG = 0x2201; - // var USE_LAYER_FOG = 0x2303; - // var USE_DISTANCE_CUE = 0x2301; - - var MAT_ENTRY = 0xAFFF; - var MAT_NAME = 0xA000; - var MAT_AMBIENT = 0xA010; - var MAT_DIFFUSE = 0xA020; - var MAT_SPECULAR = 0xA030; - var MAT_SHININESS = 0xA040; // var MAT_SHIN2PCT = 0xA041; - - var MAT_TRANSPARENCY = 0xA050; // var MAT_XPFALL = 0xA052; - // var MAT_USE_XPFALL = 0xA240; - // var MAT_REFBLUR = 0xA053; - // var MAT_SHADING = 0xA100; - // var MAT_USE_REFBLUR = 0xA250; - // var MAT_SELF_ILLUM = 0xA084; - - var MAT_TWO_SIDE = 0xA081; // var MAT_DECAL = 0xA082; - - var MAT_ADDITIVE = 0xA083; - var MAT_WIRE = 0xA085; // var MAT_FACEMAP = 0xA088; - // var MAT_TRANSFALLOFF_IN = 0xA08A; - // var MAT_PHONGSOFT = 0xA08C; - // var MAT_WIREABS = 0xA08E; - - var MAT_WIRE_SIZE = 0xA087; - var MAT_TEXMAP = 0xA200; // var MAT_SXP_TEXT_DATA = 0xA320; - // var MAT_TEXMASK = 0xA33E; - // var MAT_SXP_TEXTMASK_DATA = 0xA32A; - // var MAT_TEX2MAP = 0xA33A; - // var MAT_SXP_TEXT2_DATA = 0xA321; - // var MAT_TEX2MASK = 0xA340; - // var MAT_SXP_TEXT2MASK_DATA = 0xA32C; - - var MAT_OPACMAP = 0xA210; // var MAT_SXP_OPAC_DATA = 0xA322; - // var MAT_OPACMASK = 0xA342; - // var MAT_SXP_OPACMASK_DATA = 0xA32E; - - var MAT_BUMPMAP = 0xA230; // var MAT_SXP_BUMP_DATA = 0xA324; - // var MAT_BUMPMASK = 0xA344; - // var MAT_SXP_BUMPMASK_DATA = 0xA330; - - var MAT_SPECMAP = 0xA204; // var MAT_SXP_SPEC_DATA = 0xA325; - // var MAT_SPECMASK = 0xA348; - // var MAT_SXP_SPECMASK_DATA = 0xA332; - // var MAT_SHINMAP = 0xA33C; - // var MAT_SXP_SHIN_DATA = 0xA326; - // var MAT_SHINMASK = 0xA346; - // var MAT_SXP_SHINMASK_DATA = 0xA334; - // var MAT_SELFIMAP = 0xA33D; - // var MAT_SXP_SELFI_DATA = 0xA328; - // var MAT_SELFIMASK = 0xA34A; - // var MAT_SXP_SELFIMASK_DATA = 0xA336; - // var MAT_REFLMAP = 0xA220; - // var MAT_REFLMASK = 0xA34C; - // var MAT_SXP_REFLMASK_DATA = 0xA338; - // var MAT_ACUBIC = 0xA310; - - var MAT_MAPNAME = 0xA300; // var MAT_MAP_TILING = 0xA351; - // var MAT_MAP_TEXBLUR = 0xA353; - - var MAT_MAP_USCALE = 0xA354; - var MAT_MAP_VSCALE = 0xA356; - var MAT_MAP_UOFFSET = 0xA358; - var MAT_MAP_VOFFSET = 0xA35A; // var MAT_MAP_ANG = 0xA35C; - // var MAT_MAP_COL1 = 0xA360; - // var MAT_MAP_COL2 = 0xA362; - // var MAT_MAP_RCOL = 0xA364; - // var MAT_MAP_GCOL = 0xA366; - // var MAT_MAP_BCOL = 0xA368; - - var NAMED_OBJECT = 0x4000; // var N_DIRECT_LIGHT = 0x4600; - // var DL_OFF = 0x4620; - // var DL_OUTER_RANGE = 0x465A; - // var DL_INNER_RANGE = 0x4659; - // var DL_MULTIPLIER = 0x465B; - // var DL_EXCLUDE = 0x4654; - // var DL_ATTENUATE = 0x4625; - // var DL_SPOTLIGHT = 0x4610; - // var DL_SPOT_ROLL = 0x4656; - // var DL_SHADOWED = 0x4630; - // var DL_LOCAL_SHADOW2 = 0x4641; - // var DL_SEE_CONE = 0x4650; - // var DL_SPOT_RECTANGULAR = 0x4651; - // var DL_SPOT_ASPECT = 0x4657; - // var DL_SPOT_PROJECTOR = 0x4653; - // var DL_SPOT_OVERSHOOT = 0x4652; - // var DL_RAY_BIAS = 0x4658; - // var DL_RAYSHAD = 0x4627; - // var N_CAMERA = 0x4700; - // var CAM_SEE_CONE = 0x4710; - // var CAM_RANGES = 0x4720; - // var OBJ_HIDDEN = 0x4010; - // var OBJ_VIS_LOFTER = 0x4011; - // var OBJ_DOESNT_CAST = 0x4012; - // var OBJ_DONT_RECVSHADOW = 0x4017; - // var OBJ_MATTE = 0x4013; - // var OBJ_FAST = 0x4014; - // var OBJ_PROCEDURAL = 0x4015; - // var OBJ_FROZEN = 0x4016; - - var N_TRI_OBJECT = 0x4100; - var POINT_ARRAY = 0x4110; // var POINT_FLAG_ARRAY = 0x4111; - - var FACE_ARRAY = 0x4120; - var MSH_MAT_GROUP = 0x4130; // var SMOOTH_GROUP = 0x4150; - // var MSH_BOXMAP = 0x4190; - - var TEX_VERTS = 0x4140; - var MESH_MATRIX = 0x4160; // var MESH_COLOR = 0x4165; + + } // const NULL_CHUNK = 0x0000; + + + const M3DMAGIC = 0x4D4D; // const SMAGIC = 0x2D2D; + // const LMAGIC = 0x2D3D; + + const MLIBMAGIC = 0x3DAA; // const MATMAGIC = 0x3DFF; + + const CMAGIC = 0xC23D; + const M3D_VERSION = 0x0002; // const M3D_KFVERSION = 0x0005; + + const COLOR_F = 0x0010; + const COLOR_24 = 0x0011; + const LIN_COLOR_24 = 0x0012; + const LIN_COLOR_F = 0x0013; + const INT_PERCENTAGE = 0x0030; + const FLOAT_PERCENTAGE = 0x0031; + const MDATA = 0x3D3D; + const MESH_VERSION = 0x3D3E; + const MASTER_SCALE = 0x0100; // const LO_SHADOW_BIAS = 0x1400; + // const HI_SHADOW_BIAS = 0x1410; + // const SHADOW_MAP_SIZE = 0x1420; + // const SHADOW_SAMPLES = 0x1430; + // const SHADOW_RANGE = 0x1440; + // const SHADOW_FILTER = 0x1450; + // const RAY_BIAS = 0x1460; + // const O_CONSTS = 0x1500; + // const AMBIENT_LIGHT = 0x2100; + // const BIT_MAP = 0x1100; + // const SOLID_BGND = 0x1200; + // const V_GRADIENT = 0x1300; + // const USE_BIT_MAP = 0x1101; + // const USE_SOLID_BGND = 0x1201; + // const USE_V_GRADIENT = 0x1301; + // const FOG = 0x2200; + // const FOG_BGND = 0x2210; + // const LAYER_FOG = 0x2302; + // const DISTANCE_CUE = 0x2300; + // const DCUE_BGND = 0x2310; + // const USE_FOG = 0x2201; + // const USE_LAYER_FOG = 0x2303; + // const USE_DISTANCE_CUE = 0x2301; + + const MAT_ENTRY = 0xAFFF; + const MAT_NAME = 0xA000; + const MAT_AMBIENT = 0xA010; + const MAT_DIFFUSE = 0xA020; + const MAT_SPECULAR = 0xA030; + const MAT_SHININESS = 0xA040; // const MAT_SHIN2PCT = 0xA041; + + const MAT_TRANSPARENCY = 0xA050; // const MAT_XPFALL = 0xA052; + // const MAT_USE_XPFALL = 0xA240; + // const MAT_REFBLUR = 0xA053; + // const MAT_SHADING = 0xA100; + // const MAT_USE_REFBLUR = 0xA250; + // const MAT_SELF_ILLUM = 0xA084; + + const MAT_TWO_SIDE = 0xA081; // const MAT_DECAL = 0xA082; + + const MAT_ADDITIVE = 0xA083; + const MAT_WIRE = 0xA085; // const MAT_FACEMAP = 0xA088; + // const MAT_TRANSFALLOFF_IN = 0xA08A; + // const MAT_PHONGSOFT = 0xA08C; + // const MAT_WIREABS = 0xA08E; + + const MAT_WIRE_SIZE = 0xA087; + const MAT_TEXMAP = 0xA200; // const MAT_SXP_TEXT_DATA = 0xA320; + // const MAT_TEXMASK = 0xA33E; + // const MAT_SXP_TEXTMASK_DATA = 0xA32A; + // const MAT_TEX2MAP = 0xA33A; + // const MAT_SXP_TEXT2_DATA = 0xA321; + // const MAT_TEX2MASK = 0xA340; + // const MAT_SXP_TEXT2MASK_DATA = 0xA32C; + + const MAT_OPACMAP = 0xA210; // const MAT_SXP_OPAC_DATA = 0xA322; + // const MAT_OPACMASK = 0xA342; + // const MAT_SXP_OPACMASK_DATA = 0xA32E; + + const MAT_BUMPMAP = 0xA230; // const MAT_SXP_BUMP_DATA = 0xA324; + // const MAT_BUMPMASK = 0xA344; + // const MAT_SXP_BUMPMASK_DATA = 0xA330; + + const MAT_SPECMAP = 0xA204; // const MAT_SXP_SPEC_DATA = 0xA325; + // const MAT_SPECMASK = 0xA348; + // const MAT_SXP_SPECMASK_DATA = 0xA332; + // const MAT_SHINMAP = 0xA33C; + // const MAT_SXP_SHIN_DATA = 0xA326; + // const MAT_SHINMASK = 0xA346; + // const MAT_SXP_SHINMASK_DATA = 0xA334; + // const MAT_SELFIMAP = 0xA33D; + // const MAT_SXP_SELFI_DATA = 0xA328; + // const MAT_SELFIMASK = 0xA34A; + // const MAT_SXP_SELFIMASK_DATA = 0xA336; + // const MAT_REFLMAP = 0xA220; + // const MAT_REFLMASK = 0xA34C; + // const MAT_SXP_REFLMASK_DATA = 0xA338; + // const MAT_ACUBIC = 0xA310; + + const MAT_MAPNAME = 0xA300; // const MAT_MAP_TILING = 0xA351; + // const MAT_MAP_TEXBLUR = 0xA353; + + const MAT_MAP_USCALE = 0xA354; + const MAT_MAP_VSCALE = 0xA356; + const MAT_MAP_UOFFSET = 0xA358; + const MAT_MAP_VOFFSET = 0xA35A; // const MAT_MAP_ANG = 0xA35C; + // const MAT_MAP_COL1 = 0xA360; + // const MAT_MAP_COL2 = 0xA362; + // const MAT_MAP_RCOL = 0xA364; + // const MAT_MAP_GCOL = 0xA366; + // const MAT_MAP_BCOL = 0xA368; + + const NAMED_OBJECT = 0x4000; // const N_DIRECT_LIGHT = 0x4600; + // const DL_OFF = 0x4620; + // const DL_OUTER_RANGE = 0x465A; + // const DL_INNER_RANGE = 0x4659; + // const DL_MULTIPLIER = 0x465B; + // const DL_EXCLUDE = 0x4654; + // const DL_ATTENUATE = 0x4625; + // const DL_SPOTLIGHT = 0x4610; + // const DL_SPOT_ROLL = 0x4656; + // const DL_SHADOWED = 0x4630; + // const DL_LOCAL_SHADOW2 = 0x4641; + // const DL_SEE_CONE = 0x4650; + // const DL_SPOT_RECTANGULAR = 0x4651; + // const DL_SPOT_ASPECT = 0x4657; + // const DL_SPOT_PROJECTOR = 0x4653; + // const DL_SPOT_OVERSHOOT = 0x4652; + // const DL_RAY_BIAS = 0x4658; + // const DL_RAYSHAD = 0x4627; + // const N_CAMERA = 0x4700; + // const CAM_SEE_CONE = 0x4710; + // const CAM_RANGES = 0x4720; + // const OBJ_HIDDEN = 0x4010; + // const OBJ_VIS_LOFTER = 0x4011; + // const OBJ_DOESNT_CAST = 0x4012; + // const OBJ_DONT_RECVSHADOW = 0x4017; + // const OBJ_MATTE = 0x4013; + // const OBJ_FAST = 0x4014; + // const OBJ_PROCEDURAL = 0x4015; + // const OBJ_FROZEN = 0x4016; + + const N_TRI_OBJECT = 0x4100; + const POINT_ARRAY = 0x4110; // const POINT_FLAG_ARRAY = 0x4111; + + const FACE_ARRAY = 0x4120; + const MSH_MAT_GROUP = 0x4130; // const SMOOTH_GROUP = 0x4150; + // const MSH_BOXMAP = 0x4190; + + const TEX_VERTS = 0x4140; + const MESH_MATRIX = 0x4160; // const MESH_COLOR = 0x4165; THREE.TDSLoader = TDSLoader; diff --git a/examples/js/loaders/TGALoader.js b/examples/js/loaders/TGALoader.js index 38b92d80ddc31c..978630e4b1c475 100644 --- a/examples/js/loaders/TGALoader.js +++ b/examples/js/loaders/TGALoader.js @@ -1,14 +1,14 @@ ( function () { - var TGALoader = function ( manager ) { + class TGALoader extends THREE.DataTextureLoader { - THREE.DataTextureLoader.call( this, manager ); + constructor( manager ) { - }; + super( manager ); - TGALoader.prototype = Object.assign( Object.create( THREE.DataTextureLoader.prototype ), { - constructor: TGALoader, - parse: function ( buffer ) { + } + + parse( buffer ) { // reference from vthibault, https://github.com/vthibault/roBrowser/blob/master/src/Loaders/Targa.js function tgaCheckHeader( header ) { @@ -68,9 +68,9 @@ function tgaParse( use_rle, use_pal, header, offset, data ) { - var pixel_data, pixel_size, pixel_total, palettes; - pixel_size = header.pixel_size >> 3; - pixel_total = header.width * header.height * pixel_size; // read palettes + let pixel_data, palettes; + const pixel_size = header.pixel_size >> 3; + const pixel_total = header.width * header.height * pixel_size; // read palettes if ( use_pal ) { @@ -82,9 +82,9 @@ if ( use_rle ) { pixel_data = new Uint8Array( pixel_total ); - var c, count, i; - var shift = 0; - var pixels = new Uint8Array( pixel_size ); + let c, count, i; + let shift = 0; + const pixels = new Uint8Array( pixel_size ); while ( shift < pixel_total ) { @@ -142,12 +142,12 @@ function tgaGetImageData8bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image, palettes ) { - var colormap = palettes; - var color, + const colormap = palettes; + let color, i = 0, x, y; - var width = header.width; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -169,11 +169,11 @@ function tgaGetImageData16bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { - var color, + let color, i = 0, x, y; - var width = header.width; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -196,10 +196,10 @@ function tgaGetImageData24bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { - var i = 0, + let i = 0, x, y; - var width = header.width; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -220,10 +220,10 @@ function tgaGetImageData32bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { - var i = 0, + let i = 0, x, y; - var width = header.width; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -244,11 +244,11 @@ function tgaGetImageDataGrey8bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { - var color, + let color, i = 0, x, y; - var width = header.width; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -270,10 +270,10 @@ function tgaGetImageDataGrey16bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { - var i = 0, + let i = 0, x, y; - var width = header.width; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -294,7 +294,7 @@ function getTgaRGBA( data, width, height, image, palette ) { - var x_start, y_start, x_step, y_step, x_end, y_end; + let x_start, y_start, x_step, y_step, x_end, y_end; switch ( ( header.flags & TGA_ORIGIN_MASK ) >> TGA_ORIGIN_SHIFT ) { @@ -382,7 +382,7 @@ } } // Load image data according to specific method - // var func = 'tgaGetImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits'; + // let func = 'tgaGetImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits'; // func(data, y_start, y_step, y_end, x_start, x_step, x_end, width, image, palette ); @@ -391,7 +391,7 @@ } // TGA constants - var TGA_TYPE_NO_DATA = 0, + const TGA_TYPE_NO_DATA = 0, TGA_TYPE_INDEXED = 1, TGA_TYPE_RGB = 2, TGA_TYPE_GREY = 3, @@ -405,8 +405,8 @@ TGA_ORIGIN_UL = 0x02, TGA_ORIGIN_UR = 0x03; if ( buffer.length < 19 ) console.error( 'THREE.TGALoader: Not enough data to contain header.' ); - var content = new Uint8Array( buffer ), - offset = 0, + let offset = 0; + const content = new Uint8Array( buffer ), header = { id_length: content[ offset ++ ], colormap_type: content[ offset ++ ], @@ -432,7 +432,7 @@ offset += header.id_length; // get targa information about RLE compression and palette - var use_rle = false, + let use_rle = false, use_pal = false, use_grey = false; @@ -466,8 +466,8 @@ } // - var imageData = new Uint8Array( header.width * header.height * 4 ); - var result = tgaParse( use_rle, use_pal, header, offset, content ); + const imageData = new Uint8Array( header.width * header.height * 4 ); + const result = tgaParse( use_rle, use_pal, header, offset, content ); getTgaRGBA( imageData, header.width, header.height, result.pixel_data, result.palettes ); return { data: imageData, @@ -479,7 +479,8 @@ }; } - } ); + + } THREE.TGALoader = TGALoader; diff --git a/examples/js/loaders/TTFLoader.js b/examples/js/loaders/TTFLoader.js index 0b9357e169498a..18f4f1d2a0858d 100644 --- a/examples/js/loaders/TTFLoader.js +++ b/examples/js/loaders/TTFLoader.js @@ -6,19 +6,19 @@ * to create THREE.Font objects. */ - var TTFLoader = function ( manager ) { + class TTFLoader extends THREE.Loader { - THREE.Loader.call( this, manager ); - this.reversed = false; + constructor( manager ) { - }; + super( manager ); + this.reversed = false; - TTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: TTFLoader, - load: function ( url, onLoad, onProgress, onError ) { + } + + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new THREE.FileLoader( this.manager ); + const scope = this; + const loader = new THREE.FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( this.requestHeader ); @@ -47,25 +47,26 @@ }, onProgress, onError ); - }, - parse: function ( arraybuffer ) { + } + + parse( arraybuffer ) { function convert( font, reversed ) { - var round = Math.round; - var glyphs = {}; - var scale = 100000 / ( ( font.unitsPerEm || 2048 ) * 72 ); - var glyphIndexMap = font.encoding.cmap.glyphIndexMap; - var unicodes = Object.keys( glyphIndexMap ); + const round = Math.round; + const glyphs = {}; + const scale = 100000 / ( ( font.unitsPerEm || 2048 ) * 72 ); + const glyphIndexMap = font.encoding.cmap.glyphIndexMap; + const unicodes = Object.keys( glyphIndexMap ); - for ( var i = 0; i < unicodes.length; i ++ ) { + for ( let i = 0; i < unicodes.length; i ++ ) { - var unicode = unicodes[ i ]; - var glyph = font.glyphs.glyphs[ glyphIndexMap[ unicode ] ]; + const unicode = unicodes[ i ]; + const glyph = font.glyphs.glyphs[ glyphIndexMap[ unicode ] ]; if ( unicode !== undefined ) { - var token = { + const token = { ha: round( glyph.advanceWidth * scale ), x_min: round( glyph.xMin * scale ), x_max: round( glyph.xMax * scale ), @@ -134,8 +135,8 @@ function reverseCommands( commands ) { - var paths = []; - var path; + const paths = []; + let path; commands.forEach( function ( c ) { if ( c.type.toLowerCase() === 'm' ) { @@ -150,20 +151,20 @@ } } ); - var reversed = []; + const reversed = []; paths.forEach( function ( p ) { - var result = { + const result = { type: 'm', x: p[ p.length - 1 ].x, y: p[ p.length - 1 ].y }; reversed.push( result ); - for ( var i = p.length - 1; i > 0; i -- ) { + for ( let i = p.length - 1; i > 0; i -- ) { - var command = p[ i ]; - var result = { + const command = p[ i ]; + const result = { type: command.type }; @@ -202,7 +203,8 @@ return convert( opentype.parse( arraybuffer ), this.reversed ); // eslint-disable-line no-undef } - } ); + + } THREE.TTFLoader = TTFLoader; diff --git a/examples/js/loaders/VRMLLoader.js b/examples/js/loaders/VRMLLoader.js index c1ac85777ca41b..2bc52be5f45f7d 100644 --- a/examples/js/loaders/VRMLLoader.js +++ b/examples/js/loaders/VRMLLoader.js @@ -1,518 +1,513 @@ ( function () { - var VRMLLoader = function () { + class VRMLLoader extends THREE.Loader { - // dependency check - if ( typeof chevrotain === 'undefined' ) { + constructor( manager ) { - // eslint-disable-line no-undef - throw Error( 'THREE.VRMLLoader: External library chevrotain.min.js required.' ); + super( manager ); // dependency check - } // class definitions + if ( typeof chevrotain === 'undefined' ) { + // eslint-disable-line no-undef + throw Error( 'THREE.VRMLLoader: External library chevrotain.min.js required.' ); - function VRMLLoader( manager ) { - - THREE.Loader.call( this, manager ); + } } - VRMLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: VRMLLoader, - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - var path = scope.path === '' ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path; - var loader = new THREE.FileLoader( scope.manager ); - loader.setPath( scope.path ); - loader.setRequestHeader( scope.requestHeader ); - loader.setWithCredentials( scope.withCredentials ); - loader.load( url, function ( text ) { - - try { + load( url, onLoad, onProgress, onError ) { - onLoad( scope.parse( text, path ) ); + const scope = this; + const path = scope.path === '' ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path; + const loader = new THREE.FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { - } catch ( e ) { + try { - if ( onError ) { + onLoad( scope.parse( text, path ) ); - onError( e ); + } catch ( e ) { - } else { + if ( onError ) { - console.error( e ); + onError( e ); - } + } else { - scope.manager.itemError( url ); + console.error( e ); } - }, onProgress, onError ); + scope.manager.itemError( url ); - }, - parse: function ( data, path ) { + } - var nodeMap = {}; + }, onProgress, onError ); - function generateVRMLTree( data ) { + } - // create lexer, parser and visitor - var tokenData = createTokens(); - var lexer = new VRMLLexer( tokenData.tokens ); - var parser = new VRMLParser( tokenData.tokenVocabulary ); - var visitor = createVisitor( parser.getBaseCstVisitorConstructor() ); // lexing + parse( data, path ) { - var lexingResult = lexer.lex( data ); - parser.input = lexingResult.tokens; // parsing + const nodeMap = {}; - var cstOutput = parser.vrml(); + function generateVRMLTree( data ) { - if ( parser.errors.length > 0 ) { + // create lexer, parser and visitor + const tokenData = createTokens(); + const lexer = new VRMLLexer( tokenData.tokens ); + const parser = new VRMLParser( tokenData.tokenVocabulary ); + const visitor = createVisitor( parser.getBaseCstVisitorConstructor() ); // lexing - console.error( parser.errors ); - throw Error( 'THREE.VRMLLoader: Parsing errors detected.' ); + const lexingResult = lexer.lex( data ); + parser.input = lexingResult.tokens; // parsing - } // actions + const cstOutput = parser.vrml(); + if ( parser.errors.length > 0 ) { - var ast = visitor.visit( cstOutput ); - return ast; + console.error( parser.errors ); + throw Error( 'THREE.VRMLLoader: Parsing errors detected.' ); - } + } // actions - function createTokens() { - var createToken = chevrotain.createToken; // eslint-disable-line no-undef - // from http://gun.teipir.gr/VRML-amgem/spec/part1/concepts.html#SyntaxBasics + const ast = visitor.visit( cstOutput ); + return ast; - var RouteIdentifier = createToken( { - name: 'RouteIdentifier', - pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*[\.][^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/ - } ); - var Identifier = createToken( { - name: 'Identifier', - pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/, - longer_alt: RouteIdentifier - } ); // from http://gun.teipir.gr/VRML-amgem/spec/part1/nodesRef.html - - var nodeTypes = [ 'Anchor', 'Billboard', 'Collision', 'Group', 'Transform', // grouping nodes - 'Inline', 'LOD', 'Switch', // special groups - 'AudioClip', 'DirectionalLight', 'PointLight', 'Script', 'Shape', 'Sound', 'SpotLight', 'WorldInfo', // common nodes - 'CylinderSensor', 'PlaneSensor', 'ProximitySensor', 'SphereSensor', 'TimeSensor', 'TouchSensor', 'VisibilitySensor', // sensors - 'Box', 'Cone', 'Cylinder', 'ElevationGrid', 'Extrusion', 'IndexedFaceSet', 'IndexedLineSet', 'PointSet', 'Sphere', // geometries - 'Color', 'Coordinate', 'Normal', 'TextureCoordinate', // geometric properties - 'Appearance', 'FontStyle', 'ImageTexture', 'Material', 'MovieTexture', 'PixelTexture', 'TextureTransform', // appearance - 'ColorInterpolator', 'CoordinateInterpolator', 'NormalInterpolator', 'OrientationInterpolator', 'PositionInterpolator', 'ScalarInterpolator', // interpolators - 'Background', 'Fog', 'NavigationInfo', 'Viewpoint', // bindable nodes - 'Text' // Text must be placed at the end of the regex so there are no matches for TextureTransform and TextureCoordinate - ]; // - - var Version = createToken( { - name: 'Version', - pattern: /#VRML.*/, - longer_alt: Identifier - } ); - var NodeName = createToken( { - name: 'NodeName', - pattern: new RegExp( nodeTypes.join( '|' ) ), - longer_alt: Identifier - } ); - var DEF = createToken( { - name: 'DEF', - pattern: /DEF/, - longer_alt: Identifier - } ); - var USE = createToken( { - name: 'USE', - pattern: /USE/, - longer_alt: Identifier - } ); - var ROUTE = createToken( { - name: 'ROUTE', - pattern: /ROUTE/, - longer_alt: Identifier - } ); - var TO = createToken( { - name: 'TO', - pattern: /TO/, - longer_alt: Identifier - } ); // - - var StringLiteral = createToken( { - name: 'StringLiteral', - pattern: /"(:?[^\\"\n\r]+|\\(:?[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*"/ - } ); - var HexLiteral = createToken( { - name: 'HexLiteral', - pattern: /0[xX][0-9a-fA-F]+/ - } ); - var NumberLiteral = createToken( { - name: 'NumberLiteral', - pattern: /[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/ - } ); - var TrueLiteral = createToken( { - name: 'TrueLiteral', - pattern: /TRUE/ - } ); - var FalseLiteral = createToken( { - name: 'FalseLiteral', - pattern: /FALSE/ - } ); - var NullLiteral = createToken( { - name: 'NullLiteral', - pattern: /NULL/ - } ); - var LSquare = createToken( { - name: 'LSquare', - pattern: /\[/ - } ); - var RSquare = createToken( { - name: 'RSquare', - pattern: /]/ - } ); - var LCurly = createToken( { - name: 'LCurly', - pattern: /{/ - } ); - var RCurly = createToken( { - name: 'RCurly', - pattern: /}/ - } ); - var Comment = createToken( { - name: 'Comment', - pattern: /#.*/, - group: chevrotain.Lexer.SKIPPED // eslint-disable-line no-undef + } - } ); // commas, blanks, tabs, newlines and carriage returns are whitespace characters wherever they appear outside of string fields + function createTokens() { - var WhiteSpace = createToken( { - name: 'WhiteSpace', - pattern: /[ ,\s]/, - group: chevrotain.Lexer.SKIPPED // eslint-disable-line no-undef + const createToken = chevrotain.createToken; // eslint-disable-line no-undef + // from http://gun.teipir.gr/VRML-amgem/spec/part1/concepts.html#SyntaxBasics - } ); - var tokens = [ WhiteSpace, // keywords appear before the Identifier - NodeName, DEF, USE, ROUTE, TO, TrueLiteral, FalseLiteral, NullLiteral, // the Identifier must appear after the keywords because all keywords are valid identifiers - Version, Identifier, RouteIdentifier, StringLiteral, HexLiteral, NumberLiteral, LSquare, RSquare, LCurly, RCurly, Comment ]; - var tokenVocabulary = {}; + const RouteIdentifier = createToken( { + name: 'RouteIdentifier', + pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*[\.][^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/ + } ); + const Identifier = createToken( { + name: 'Identifier', + pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/, + longer_alt: RouteIdentifier + } ); // from http://gun.teipir.gr/VRML-amgem/spec/part1/nodesRef.html + + const nodeTypes = [ 'Anchor', 'Billboard', 'Collision', 'Group', 'Transform', // grouping nodes + 'Inline', 'LOD', 'Switch', // special groups + 'AudioClip', 'DirectionalLight', 'PointLight', 'Script', 'Shape', 'Sound', 'SpotLight', 'WorldInfo', // common nodes + 'CylinderSensor', 'PlaneSensor', 'ProximitySensor', 'SphereSensor', 'TimeSensor', 'TouchSensor', 'VisibilitySensor', // sensors + 'Box', 'Cone', 'Cylinder', 'ElevationGrid', 'Extrusion', 'IndexedFaceSet', 'IndexedLineSet', 'PointSet', 'Sphere', // geometries + 'Color', 'Coordinate', 'Normal', 'TextureCoordinate', // geometric properties + 'Appearance', 'FontStyle', 'ImageTexture', 'Material', 'MovieTexture', 'PixelTexture', 'TextureTransform', // appearance + 'ColorInterpolator', 'CoordinateInterpolator', 'NormalInterpolator', 'OrientationInterpolator', 'PositionInterpolator', 'ScalarInterpolator', // interpolators + 'Background', 'Fog', 'NavigationInfo', 'Viewpoint', // bindable nodes + 'Text' // Text must be placed at the end of the regex so there are no matches for TextureTransform and TextureCoordinate + ]; // + + const Version = createToken( { + name: 'Version', + pattern: /#VRML.*/, + longer_alt: Identifier + } ); + const NodeName = createToken( { + name: 'NodeName', + pattern: new RegExp( nodeTypes.join( '|' ) ), + longer_alt: Identifier + } ); + const DEF = createToken( { + name: 'DEF', + pattern: /DEF/, + longer_alt: Identifier + } ); + const USE = createToken( { + name: 'USE', + pattern: /USE/, + longer_alt: Identifier + } ); + const ROUTE = createToken( { + name: 'ROUTE', + pattern: /ROUTE/, + longer_alt: Identifier + } ); + const TO = createToken( { + name: 'TO', + pattern: /TO/, + longer_alt: Identifier + } ); // + + const StringLiteral = createToken( { + name: 'StringLiteral', + pattern: /"(:?[^\\"\n\r]+|\\(:?[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*"/ + } ); + const HexLiteral = createToken( { + name: 'HexLiteral', + pattern: /0[xX][0-9a-fA-F]+/ + } ); + const NumberLiteral = createToken( { + name: 'NumberLiteral', + pattern: /[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/ + } ); + const TrueLiteral = createToken( { + name: 'TrueLiteral', + pattern: /TRUE/ + } ); + const FalseLiteral = createToken( { + name: 'FalseLiteral', + pattern: /FALSE/ + } ); + const NullLiteral = createToken( { + name: 'NullLiteral', + pattern: /NULL/ + } ); + const LSquare = createToken( { + name: 'LSquare', + pattern: /\[/ + } ); + const RSquare = createToken( { + name: 'RSquare', + pattern: /]/ + } ); + const LCurly = createToken( { + name: 'LCurly', + pattern: /{/ + } ); + const RCurly = createToken( { + name: 'RCurly', + pattern: /}/ + } ); + const Comment = createToken( { + name: 'Comment', + pattern: /#.*/, + group: chevrotain.Lexer.SKIPPED // eslint-disable-line no-undef - for ( var i = 0, l = tokens.length; i < l; i ++ ) { + } ); // commas, blanks, tabs, newlines and carriage returns are whitespace characters wherever they appear outside of string fields - var token = tokens[ i ]; - tokenVocabulary[ token.name ] = token; + const WhiteSpace = createToken( { + name: 'WhiteSpace', + pattern: /[ ,\s]/, + group: chevrotain.Lexer.SKIPPED // eslint-disable-line no-undef - } + } ); + const tokens = [ WhiteSpace, // keywords appear before the Identifier + NodeName, DEF, USE, ROUTE, TO, TrueLiteral, FalseLiteral, NullLiteral, // the Identifier must appear after the keywords because all keywords are valid identifiers + Version, Identifier, RouteIdentifier, StringLiteral, HexLiteral, NumberLiteral, LSquare, RSquare, LCurly, RCurly, Comment ]; + const tokenVocabulary = {}; - return { - tokens: tokens, - tokenVocabulary: tokenVocabulary - }; + for ( let i = 0, l = tokens.length; i < l; i ++ ) { + + const token = tokens[ i ]; + tokenVocabulary[ token.name ] = token; } - function createVisitor( BaseVRMLVisitor ) { + return { + tokens: tokens, + tokenVocabulary: tokenVocabulary + }; - // the visitor is created dynmaically based on the given base class - function VRMLToASTVisitor() { + } - BaseVRMLVisitor.call( this ); - this.validateVisitor(); + function createVisitor( BaseVRMLVisitor ) { - } + // the visitor is created dynmaically based on the given base class + function VRMLToASTVisitor() { - VRMLToASTVisitor.prototype = Object.assign( Object.create( BaseVRMLVisitor.prototype ), { - constructor: VRMLToASTVisitor, - vrml: function ( ctx ) { + BaseVRMLVisitor.call( this ); + this.validateVisitor(); - var data = { - version: this.visit( ctx.version ), - nodes: [], - routes: [] - }; + } - for ( var i = 0, l = ctx.node.length; i < l; i ++ ) { + VRMLToASTVisitor.prototype = Object.assign( Object.create( BaseVRMLVisitor.prototype ), { + constructor: VRMLToASTVisitor, + vrml: function ( ctx ) { - var node = ctx.node[ i ]; - data.nodes.push( this.visit( node ) ); + const data = { + version: this.visit( ctx.version ), + nodes: [], + routes: [] + }; - } + for ( let i = 0, l = ctx.node.length; i < l; i ++ ) { - if ( ctx.route ) { + const node = ctx.node[ i ]; + data.nodes.push( this.visit( node ) ); - for ( var i = 0, l = ctx.route.length; i < l; i ++ ) { + } - var route = ctx.route[ i ]; - data.routes.push( this.visit( route ) ); + if ( ctx.route ) { - } + for ( let i = 0, l = ctx.route.length; i < l; i ++ ) { + + const route = ctx.route[ i ]; + data.routes.push( this.visit( route ) ); } - return data; + } - }, - version: function ( ctx ) { + return data; - return ctx.Version[ 0 ].image; + }, + version: function ( ctx ) { - }, - node: function ( ctx ) { + return ctx.Version[ 0 ].image; - var data = { - name: ctx.NodeName[ 0 ].image, - fields: [] - }; + }, + node: function ( ctx ) { - if ( ctx.field ) { + const data = { + name: ctx.NodeName[ 0 ].image, + fields: [] + }; - for ( var i = 0, l = ctx.field.length; i < l; i ++ ) { + if ( ctx.field ) { - var field = ctx.field[ i ]; - data.fields.push( this.visit( field ) ); + for ( let i = 0, l = ctx.field.length; i < l; i ++ ) { - } + const field = ctx.field[ i ]; + data.fields.push( this.visit( field ) ); - } // DEF + } + } // DEF - if ( ctx.def ) { - data.DEF = this.visit( ctx.def[ 0 ] ); + if ( ctx.def ) { - } + data.DEF = this.visit( ctx.def[ 0 ] ); - return data; + } - }, - field: function ( ctx ) { + return data; - var data = { - name: ctx.Identifier[ 0 ].image, - type: null, - values: null - }; - var result; // SFValue + }, + field: function ( ctx ) { - if ( ctx.singleFieldValue ) { + const data = { + name: ctx.Identifier[ 0 ].image, + type: null, + values: null + }; + let result; // SFValue - result = this.visit( ctx.singleFieldValue[ 0 ] ); + if ( ctx.singleFieldValue ) { - } // MFValue + result = this.visit( ctx.singleFieldValue[ 0 ] ); + } // MFValue - if ( ctx.multiFieldValue ) { - result = this.visit( ctx.multiFieldValue[ 0 ] ); + if ( ctx.multiFieldValue ) { - } + result = this.visit( ctx.multiFieldValue[ 0 ] ); - data.type = result.type; - data.values = result.values; - return data; + } - }, - def: function ( ctx ) { + data.type = result.type; + data.values = result.values; + return data; - return ( ctx.Identifier || ctx.NodeName )[ 0 ].image; + }, + def: function ( ctx ) { - }, - use: function ( ctx ) { + return ( ctx.Identifier || ctx.NodeName )[ 0 ].image; - return { - USE: ( ctx.Identifier || ctx.NodeName )[ 0 ].image - }; + }, + use: function ( ctx ) { - }, - singleFieldValue: function ( ctx ) { + return { + USE: ( ctx.Identifier || ctx.NodeName )[ 0 ].image + }; - return processField( this, ctx ); + }, + singleFieldValue: function ( ctx ) { - }, - multiFieldValue: function ( ctx ) { + return processField( this, ctx ); - return processField( this, ctx ); + }, + multiFieldValue: function ( ctx ) { - }, - route: function ( ctx ) { + return processField( this, ctx ); - var data = { - FROM: ctx.RouteIdentifier[ 0 ].image, - TO: ctx.RouteIdentifier[ 1 ].image - }; - return data; + }, + route: function ( ctx ) { - } - } ); + const data = { + FROM: ctx.RouteIdentifier[ 0 ].image, + TO: ctx.RouteIdentifier[ 1 ].image + }; + return data; - function processField( scope, ctx ) { + } + } ); - var field = { - type: null, - values: [] - }; + function processField( scope, ctx ) { - if ( ctx.node ) { + const field = { + type: null, + values: [] + }; - field.type = 'node'; + if ( ctx.node ) { - for ( var i = 0, l = ctx.node.length; i < l; i ++ ) { + field.type = 'node'; - var node = ctx.node[ i ]; - field.values.push( scope.visit( node ) ); + for ( let i = 0, l = ctx.node.length; i < l; i ++ ) { - } + const node = ctx.node[ i ]; + field.values.push( scope.visit( node ) ); } - if ( ctx.use ) { + } - field.type = 'use'; + if ( ctx.use ) { - for ( var i = 0, l = ctx.use.length; i < l; i ++ ) { + field.type = 'use'; - var use = ctx.use[ i ]; - field.values.push( scope.visit( use ) ); + for ( let i = 0, l = ctx.use.length; i < l; i ++ ) { - } + const use = ctx.use[ i ]; + field.values.push( scope.visit( use ) ); } - if ( ctx.StringLiteral ) { + } - field.type = 'string'; + if ( ctx.StringLiteral ) { - for ( var i = 0, l = ctx.StringLiteral.length; i < l; i ++ ) { + field.type = 'string'; - var stringLiteral = ctx.StringLiteral[ i ]; - field.values.push( stringLiteral.image.replace( /'|"/g, '' ) ); + for ( let i = 0, l = ctx.StringLiteral.length; i < l; i ++ ) { - } + const stringLiteral = ctx.StringLiteral[ i ]; + field.values.push( stringLiteral.image.replace( /'|"/g, '' ) ); } - if ( ctx.NumberLiteral ) { + } - field.type = 'number'; + if ( ctx.NumberLiteral ) { - for ( var i = 0, l = ctx.NumberLiteral.length; i < l; i ++ ) { + field.type = 'number'; - var numberLiteral = ctx.NumberLiteral[ i ]; - field.values.push( parseFloat( numberLiteral.image ) ); + for ( let i = 0, l = ctx.NumberLiteral.length; i < l; i ++ ) { - } + const numberLiteral = ctx.NumberLiteral[ i ]; + field.values.push( parseFloat( numberLiteral.image ) ); } - if ( ctx.HexLiteral ) { + } - field.type = 'hex'; + if ( ctx.HexLiteral ) { - for ( var i = 0, l = ctx.HexLiteral.length; i < l; i ++ ) { + field.type = 'hex'; - var hexLiteral = ctx.HexLiteral[ i ]; - field.values.push( hexLiteral.image ); + for ( let i = 0, l = ctx.HexLiteral.length; i < l; i ++ ) { - } + const hexLiteral = ctx.HexLiteral[ i ]; + field.values.push( hexLiteral.image ); } - if ( ctx.TrueLiteral ) { + } - field.type = 'boolean'; + if ( ctx.TrueLiteral ) { - for ( var i = 0, l = ctx.TrueLiteral.length; i < l; i ++ ) { + field.type = 'boolean'; - var trueLiteral = ctx.TrueLiteral[ i ]; - if ( trueLiteral.image === 'TRUE' ) field.values.push( true ); + for ( let i = 0, l = ctx.TrueLiteral.length; i < l; i ++ ) { - } + const trueLiteral = ctx.TrueLiteral[ i ]; + if ( trueLiteral.image === 'TRUE' ) field.values.push( true ); } - if ( ctx.FalseLiteral ) { + } - field.type = 'boolean'; + if ( ctx.FalseLiteral ) { - for ( var i = 0, l = ctx.FalseLiteral.length; i < l; i ++ ) { + field.type = 'boolean'; - var falseLiteral = ctx.FalseLiteral[ i ]; - if ( falseLiteral.image === 'FALSE' ) field.values.push( false ); + for ( let i = 0, l = ctx.FalseLiteral.length; i < l; i ++ ) { - } + const falseLiteral = ctx.FalseLiteral[ i ]; + if ( falseLiteral.image === 'FALSE' ) field.values.push( false ); } - if ( ctx.NullLiteral ) { - - field.type = 'null'; - ctx.NullLiteral.forEach( function () { + } - field.values.push( null ); + if ( ctx.NullLiteral ) { - } ); + field.type = 'null'; + ctx.NullLiteral.forEach( function () { - } + field.values.push( null ); - return field; + } ); } - return new VRMLToASTVisitor(); + return field; } - function parseTree( tree ) { + return new VRMLToASTVisitor(); - // console.log( JSON.stringify( tree, null, 2 ) ); - var nodes = tree.nodes; - var scene = new THREE.Scene(); // first iteration: build nodemap based on DEF statements + } - for ( var i = 0, l = nodes.length; i < l; i ++ ) { + function parseTree( tree ) { - var node = nodes[ i ]; - buildNodeMap( node ); + // console.log( JSON.stringify( tree, null, 2 ) ); + const nodes = tree.nodes; + const scene = new THREE.Scene(); // first iteration: build nodemap based on DEF statements - } // second iteration: build nodes + for ( let i = 0, l = nodes.length; i < l; i ++ ) { + const node = nodes[ i ]; + buildNodeMap( node ); - for ( var i = 0, l = nodes.length; i < l; i ++ ) { + } // second iteration: build nodes - var node = nodes[ i ]; - var object = getNode( node ); - if ( object instanceof THREE.Object3D ) scene.add( object ); - if ( node.name === 'WorldInfo' ) scene.userData.worldInfo = object; - } + for ( let i = 0, l = nodes.length; i < l; i ++ ) { - return scene; + const node = nodes[ i ]; + const object = getNode( node ); + if ( object instanceof THREE.Object3D ) scene.add( object ); + if ( node.name === 'WorldInfo' ) scene.userData.worldInfo = object; } - function buildNodeMap( node ) { + return scene; - if ( node.DEF ) { + } - nodeMap[ node.DEF ] = node; + function buildNodeMap( node ) { - } + if ( node.DEF ) { + + nodeMap[ node.DEF ] = node; - var fields = node.fields; + } - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const fields = node.fields; - var field = fields[ i ]; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - if ( field.type === 'node' ) { + const field = fields[ i ]; - var fieldValues = field.values; + if ( field.type === 'node' ) { - for ( var j = 0, jl = fieldValues.length; j < jl; j ++ ) { + const fieldValues = field.values; - buildNodeMap( fieldValues[ j ] ); + for ( let j = 0, jl = fieldValues.length; j < jl; j ++ ) { - } + buildNodeMap( fieldValues[ j ] ); } @@ -520,1971 +515,1971 @@ } - function getNode( node ) { + } - // handle case where a node refers to a different one - if ( node.USE ) { + function getNode( node ) { - return resolveUSE( node.USE ); + // handle case where a node refers to a different one + if ( node.USE ) { - } + return resolveUSE( node.USE ); - if ( node.build !== undefined ) return node.build; - node.build = buildNode( node ); - return node.build; + } - } // node builder + if ( node.build !== undefined ) return node.build; + node.build = buildNode( node ); + return node.build; + } // node builder - function buildNode( node ) { - var nodeName = node.name; - var build; + function buildNode( node ) { + + const nodeName = node.name; + let build; + + switch ( nodeName ) { + + case 'Group': + case 'Transform': + case 'Collision': + build = buildGroupingNode( node ); + break; + + case 'Background': + build = buildBackgroundNode( node ); + break; + + case 'Shape': + build = buildShapeNode( node ); + break; + + case 'Appearance': + build = buildAppearanceNode( node ); + break; + + case 'Material': + build = buildMaterialNode( node ); + break; + + case 'ImageTexture': + build = buildImageTextureNode( node ); + break; + + case 'PixelTexture': + build = buildPixelTextureNode( node ); + break; + + case 'TextureTransform': + build = buildTextureTransformNode( node ); + break; + + case 'IndexedFaceSet': + build = buildIndexedFaceSetNode( node ); + break; + + case 'IndexedLineSet': + build = buildIndexedLineSetNode( node ); + break; + + case 'PointSet': + build = buildPointSetNode( node ); + break; + + case 'Box': + build = buildBoxNode( node ); + break; + + case 'Cone': + build = buildConeNode( node ); + break; + + case 'Cylinder': + build = buildCylinderNode( node ); + break; + + case 'Sphere': + build = buildSphereNode( node ); + break; + + case 'ElevationGrid': + build = buildElevationGridNode( node ); + break; + + case 'Extrusion': + build = buildExtrusionNode( node ); + break; + + case 'Color': + case 'Coordinate': + case 'Normal': + case 'TextureCoordinate': + build = buildGeometricNode( node ); + break; + + case 'WorldInfo': + build = buildWorldInfoNode( node ); + break; + + case 'Anchor': + case 'Billboard': + case 'Inline': + case 'LOD': + case 'Switch': + case 'AudioClip': + case 'DirectionalLight': + case 'PointLight': + case 'Script': + case 'Sound': + case 'SpotLight': + case 'CylinderSensor': + case 'PlaneSensor': + case 'ProximitySensor': + case 'SphereSensor': + case 'TimeSensor': + case 'TouchSensor': + case 'VisibilitySensor': + case 'Text': + case 'FontStyle': + case 'MovieTexture': + case 'ColorInterpolator': + case 'CoordinateInterpolator': + case 'NormalInterpolator': + case 'OrientationInterpolator': + case 'PositionInterpolator': + case 'ScalarInterpolator': + case 'Fog': + case 'NavigationInfo': + case 'Viewpoint': + // node not supported yet + break; + + default: + console.warn( 'THREE.VRMLLoader: Unknown node:', nodeName ); + break; + + } - switch ( nodeName ) { + if ( build !== undefined && node.DEF !== undefined && build.hasOwnProperty( 'name' ) === true ) { - case 'Group': - case 'Transform': - case 'Collision': - build = buildGroupingNode( node ); - break; + build.name = node.DEF; - case 'Background': - build = buildBackgroundNode( node ); - break; + } - case 'Shape': - build = buildShapeNode( node ); - break; + return build; - case 'Appearance': - build = buildAppearanceNode( node ); - break; + } - case 'Material': - build = buildMaterialNode( node ); - break; + function buildGroupingNode( node ) { - case 'ImageTexture': - build = buildImageTextureNode( node ); - break; + const object = new THREE.Group(); // - case 'PixelTexture': - build = buildPixelTextureNode( node ); - break; + const fields = node.fields; - case 'TextureTransform': - build = buildTextureTransformNode( node ); - break; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'IndexedFaceSet': - build = buildIndexedFaceSetNode( node ); - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'IndexedLineSet': - build = buildIndexedLineSetNode( node ); - break; + switch ( fieldName ) { - case 'PointSet': - build = buildPointSetNode( node ); + case 'bboxCenter': + // field not supported break; - case 'Box': - build = buildBoxNode( node ); + case 'bboxSize': + // field not supported break; - case 'Cone': - build = buildConeNode( node ); + case 'center': + // field not supported break; - case 'Cylinder': - build = buildCylinderNode( node ); + case 'children': + parseFieldChildren( fieldValues, object ); break; - case 'Sphere': - build = buildSphereNode( node ); + case 'collide': + // field not supported break; - case 'ElevationGrid': - build = buildElevationGridNode( node ); + case 'rotation': + const axis = new THREE.Vector3( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); + const angle = fieldValues[ 3 ]; + object.quaternion.setFromAxisAngle( axis, angle ); break; - case 'Extrusion': - build = buildExtrusionNode( node ); + case 'scale': + object.scale.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; - case 'Color': - case 'Coordinate': - case 'Normal': - case 'TextureCoordinate': - build = buildGeometricNode( node ); + case 'scaleOrientation': + // field not supported break; - case 'WorldInfo': - build = buildWorldInfoNode( node ); + case 'translation': + object.position.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; - case 'Anchor': - case 'Billboard': - case 'Inline': - case 'LOD': - case 'Switch': - case 'AudioClip': - case 'DirectionalLight': - case 'PointLight': - case 'Script': - case 'Sound': - case 'SpotLight': - case 'CylinderSensor': - case 'PlaneSensor': - case 'ProximitySensor': - case 'SphereSensor': - case 'TimeSensor': - case 'TouchSensor': - case 'VisibilitySensor': - case 'Text': - case 'FontStyle': - case 'MovieTexture': - case 'ColorInterpolator': - case 'CoordinateInterpolator': - case 'NormalInterpolator': - case 'OrientationInterpolator': - case 'PositionInterpolator': - case 'ScalarInterpolator': - case 'Fog': - case 'NavigationInfo': - case 'Viewpoint': - // node not supported yet + case 'proxy': + // field not supported break; default: - console.warn( 'THREE.VRMLLoader: Unknown node:', nodeName ); + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } - if ( build !== undefined && node.DEF !== undefined && build.hasOwnProperty( 'name' ) === true ) { - - build.name = node.DEF; - - } - - return build; - } - function buildGroupingNode( node ) { + return object; - var object = new THREE.Group(); // + } - var fields = node.fields; + function buildBackgroundNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const group = new THREE.Group(); + let groundAngle, groundColor; + let skyAngle, skyColor; + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'bboxCenter': - // field not supported - break; + switch ( fieldName ) { - case 'bboxSize': - // field not supported - break; + case 'groundAngle': + groundAngle = fieldValues; + break; - case 'center': - // field not supported - break; + case 'groundColor': + groundColor = fieldValues; + break; - case 'children': - parseFieldChildren( fieldValues, object ); - break; + case 'backUrl': + // field not supported + break; - case 'collide': - // field not supported - break; + case 'bottomUrl': + // field not supported + break; - case 'rotation': - var axis = new THREE.Vector3( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - var angle = fieldValues[ 3 ]; - object.quaternion.setFromAxisAngle( axis, angle ); - break; + case 'frontUrl': + // field not supported + break; - case 'scale': - object.scale.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - break; + case 'leftUrl': + // field not supported + break; - case 'scaleOrientation': - // field not supported - break; + case 'rightUrl': + // field not supported + break; - case 'translation': - object.position.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - break; + case 'topUrl': + // field not supported + break; - case 'proxy': - // field not supported - break; + case 'skyAngle': + skyAngle = fieldValues; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'skyColor': + skyColor = fieldValues; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - return object; - } - function buildBackgroundNode( node ) { - - var group = new THREE.Group(); - var groundAngle, groundColor; - var skyAngle, skyColor; - var fields = node.fields; + const radius = 10000; // sky - for ( var i = 0, l = fields.length; i < l; i ++ ) { + if ( skyColor ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; - - switch ( fieldName ) { - - case 'groundAngle': - groundAngle = fieldValues; - break; - - case 'groundColor': - groundColor = fieldValues; - break; - - case 'backUrl': - // field not supported - break; - - case 'bottomUrl': - // field not supported - break; + const skyGeometry = new THREE.SphereGeometry( radius, 32, 16 ); + const skyMaterial = new THREE.MeshBasicMaterial( { + fog: false, + side: THREE.BackSide, + depthWrite: false, + depthTest: false + } ); - case 'frontUrl': - // field not supported - break; + if ( skyColor.length > 3 ) { - case 'leftUrl': - // field not supported - break; + paintFaces( skyGeometry, radius, skyAngle, toColorArray( skyColor ), true ); + skyMaterial.vertexColors = true; - case 'rightUrl': - // field not supported - break; + } else { - case 'topUrl': - // field not supported - break; + skyMaterial.color.setRGB( skyColor[ 0 ], skyColor[ 1 ], skyColor[ 2 ] ); - case 'skyAngle': - skyAngle = fieldValues; - break; - - case 'skyColor': - skyColor = fieldValues; - break; + } - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + const sky = new THREE.Mesh( skyGeometry, skyMaterial ); + group.add( sky ); - } + } // ground - } - var radius = 10000; // sky + if ( groundColor ) { - if ( skyColor ) { + if ( groundColor.length > 0 ) { - var skyGeometry = new THREE.SphereGeometry( radius, 32, 16 ); - var skyMaterial = new THREE.MeshBasicMaterial( { + const groundGeometry = new THREE.SphereGeometry( radius, 32, 16, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI ); + const groundMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, + vertexColors: true, depthWrite: false, depthTest: false } ); + paintFaces( groundGeometry, radius, groundAngle, toColorArray( groundColor ), false ); + const ground = new THREE.Mesh( groundGeometry, groundMaterial ); + group.add( ground ); - if ( skyColor.length > 3 ) { - - paintFaces( skyGeometry, radius, skyAngle, toColorArray( skyColor ), true ); - skyMaterial.vertexColors = true; - - } else { - - skyMaterial.color.setRGB( skyColor[ 0 ], skyColor[ 1 ], skyColor[ 2 ] ); - - } - - var sky = new THREE.Mesh( skyGeometry, skyMaterial ); - group.add( sky ); - - } // ground - - - if ( groundColor ) { - - if ( groundColor.length > 0 ) { - - var groundGeometry = new THREE.SphereGeometry( radius, 32, 16, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI ); - var groundMaterial = new THREE.MeshBasicMaterial( { - fog: false, - side: THREE.BackSide, - vertexColors: true, - depthWrite: false, - depthTest: false - } ); - paintFaces( groundGeometry, radius, groundAngle, toColorArray( groundColor ), false ); - var ground = new THREE.Mesh( groundGeometry, groundMaterial ); - group.add( ground ); - - } + } - } // render background group first + } // render background group first - group.renderOrder = - Infinity; - return group; + group.renderOrder = - Infinity; + return group; - } + } - function buildShapeNode( node ) { + function buildShapeNode( node ) { - var fields = node.fields; // if the appearance field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0) + const fields = node.fields; // if the appearance field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0) - var material = new THREE.MeshBasicMaterial( { - color: 0x000000 - } ); - var geometry; + let material = new THREE.MeshBasicMaterial( { + color: 0x000000 + } ); + let geometry; - for ( var i = 0, l = fields.length; i < l; i ++ ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - switch ( fieldName ) { + switch ( fieldName ) { - case 'appearance': - if ( fieldValues[ 0 ] !== null ) { + case 'appearance': + if ( fieldValues[ 0 ] !== null ) { - material = getNode( fieldValues[ 0 ] ); + material = getNode( fieldValues[ 0 ] ); - } + } - break; + break; - case 'geometry': - if ( fieldValues[ 0 ] !== null ) { + case 'geometry': + if ( fieldValues[ 0 ] !== null ) { - geometry = getNode( fieldValues[ 0 ] ); + geometry = getNode( fieldValues[ 0 ] ); - } - - break; + } - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - } // build 3D object + } + } // build 3D object - var object; - if ( geometry && geometry.attributes.position ) { + let object; - var type = geometry._type; + if ( geometry && geometry.attributes.position ) { - if ( type === 'points' ) { + const type = geometry._type; - // points - var pointsMaterial = new THREE.PointsMaterial( { - color: 0xffffff - } ); + if ( type === 'points' ) { - if ( geometry.attributes.color !== undefined ) { + // points + const pointsMaterial = new THREE.PointsMaterial( { + color: 0xffffff + } ); - pointsMaterial.vertexColors = true; + if ( geometry.attributes.color !== undefined ) { - } else { + pointsMaterial.vertexColors = true; - // if the color field is NULL and there is a material defined for the appearance affecting this PointSet, then use the emissiveColor of the material to draw the points - if ( material.isMeshPhongMaterial ) { + } else { - pointsMaterial.color.copy( material.emissive ); + // if the color field is NULL and there is a material defined for the appearance affecting this PointSet, then use the emissiveColor of the material to draw the points + if ( material.isMeshPhongMaterial ) { - } + pointsMaterial.color.copy( material.emissive ); } - object = new THREE.Points( geometry, pointsMaterial ); + } - } else if ( type === 'line' ) { + object = new THREE.Points( geometry, pointsMaterial ); - // lines - var lineMaterial = new THREE.LineBasicMaterial( { - color: 0xffffff - } ); + } else if ( type === 'line' ) { - if ( geometry.attributes.color !== undefined ) { + // lines + const lineMaterial = new THREE.LineBasicMaterial( { + color: 0xffffff + } ); - lineMaterial.vertexColors = true; + if ( geometry.attributes.color !== undefined ) { - } else { + lineMaterial.vertexColors = true; - // if the color field is NULL and there is a material defined for the appearance affecting this IndexedLineSet, then use the emissiveColor of the material to draw the lines - if ( material.isMeshPhongMaterial ) { + } else { - lineMaterial.color.copy( material.emissive ); + // if the color field is NULL and there is a material defined for the appearance affecting this IndexedLineSet, then use the emissiveColor of the material to draw the lines + if ( material.isMeshPhongMaterial ) { - } + lineMaterial.color.copy( material.emissive ); } - object = new THREE.LineSegments( geometry, lineMaterial ); + } - } else { + object = new THREE.LineSegments( geometry, lineMaterial ); - // consider meshes - // check "solid" hint (it's placed in the geometry but affects the material) - if ( geometry._solid !== undefined ) { + } else { - material.side = geometry._solid ? THREE.FrontSide : THREE.DoubleSide; + // consider meshes + // check "solid" hint (it's placed in the geometry but affects the material) + if ( geometry._solid !== undefined ) { - } // check for vertex colors + material.side = geometry._solid ? THREE.FrontSide : THREE.DoubleSide; + } // check for vertex colors - if ( geometry.attributes.color !== undefined ) { - material.vertexColors = true; + if ( geometry.attributes.color !== undefined ) { - } - - object = new THREE.Mesh( geometry, material ); + material.vertexColors = true; } - } else { - - object = new THREE.Object3D(); // if the geometry field is NULL or no vertices are defined the object is not drawn - - object.visible = false; + object = new THREE.Mesh( geometry, material ); } - return object; + } else { - } - - function buildAppearanceNode( node ) { + object = new THREE.Object3D(); // if the geometry field is NULL or no vertices are defined the object is not drawn - var material = new THREE.MeshPhongMaterial(); - var transformData; - var fields = node.fields; + object.visible = false; - for ( var i = 0, l = fields.length; i < l; i ++ ) { + } - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + return object; - switch ( fieldName ) { + } - case 'material': - if ( fieldValues[ 0 ] !== null ) { + function buildAppearanceNode( node ) { - var materialData = getNode( fieldValues[ 0 ] ); - if ( materialData.diffuseColor ) material.color.copy( materialData.diffuseColor ); - if ( materialData.emissiveColor ) material.emissive.copy( materialData.emissiveColor ); - if ( materialData.shininess ) material.shininess = materialData.shininess; - if ( materialData.specularColor ) material.specular.copy( materialData.specularColor ); - if ( materialData.transparency ) material.opacity = 1 - materialData.transparency; - if ( materialData.transparency > 0 ) material.transparent = true; + let material = new THREE.MeshPhongMaterial(); + let transformData; + const fields = node.fields; - } else { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - // if the material field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0) - material = new THREE.MeshBasicMaterial( { - color: 0x000000 - } ); + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - } + switch ( fieldName ) { - break; + case 'material': + if ( fieldValues[ 0 ] !== null ) { - case 'texture': - var textureNode = fieldValues[ 0 ]; + const materialData = getNode( fieldValues[ 0 ] ); + if ( materialData.diffuseColor ) material.color.copy( materialData.diffuseColor ); + if ( materialData.emissiveColor ) material.emissive.copy( materialData.emissiveColor ); + if ( materialData.shininess ) material.shininess = materialData.shininess; + if ( materialData.specularColor ) material.specular.copy( materialData.specularColor ); + if ( materialData.transparency ) material.opacity = 1 - materialData.transparency; + if ( materialData.transparency > 0 ) material.transparent = true; - if ( textureNode !== null ) { + } else { - if ( textureNode.name === 'ImageTexture' || textureNode.name === 'PixelTexture' ) { + // if the material field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0) + material = new THREE.MeshBasicMaterial( { + color: 0x000000 + } ); - material.map = getNode( textureNode ); + } - } else { // MovieTexture not supported yet - } + break; - } + case 'texture': + const textureNode = fieldValues[ 0 ]; - break; + if ( textureNode !== null ) { - case 'textureTransform': - if ( fieldValues[ 0 ] !== null ) { + if ( textureNode.name === 'ImageTexture' || textureNode.name === 'PixelTexture' ) { - transformData = getNode( fieldValues[ 0 ] ); + material.map = getNode( textureNode ); + } else { // MovieTexture not supported yet } - break; - - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + } - } + break; - } // only apply texture transform data if a texture was defined + case 'textureTransform': + if ( fieldValues[ 0 ] !== null ) { + transformData = getNode( fieldValues[ 0 ] ); - if ( material.map ) { + } - // respect VRML lighting model - if ( material.map.__type ) { + break; - switch ( material.map.__type ) { + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - case TEXTURE_TYPE.INTENSITY_ALPHA: - material.opacity = 1; // ignore transparency + } - break; + } // only apply texture transform data if a texture was defined - case TEXTURE_TYPE.RGB: - material.color.set( 0xffffff ); // ignore material color - break; + if ( material.map ) { - case TEXTURE_TYPE.RGBA: - material.color.set( 0xffffff ); // ignore material color + // respect VRML lighting model + if ( material.map.__type ) { - material.opacity = 1; // ignore transparency + switch ( material.map.__type ) { - break; + case TEXTURE_TYPE.INTENSITY_ALPHA: + material.opacity = 1; // ignore transparency - default: + break; - } + case TEXTURE_TYPE.RGB: + material.color.set( 0xffffff ); // ignore material color - delete material.map.__type; + break; - } // apply texture transform + case TEXTURE_TYPE.RGBA: + material.color.set( 0xffffff ); // ignore material color + material.opacity = 1; // ignore transparency - if ( transformData ) { + break; - material.map.center.copy( transformData.center ); - material.map.rotation = transformData.rotation; - material.map.repeat.copy( transformData.scale ); - material.map.offset.copy( transformData.translation ); + default: } - } - - return material; - - } - - function buildMaterialNode( node ) { + delete material.map.__type; - var materialData = {}; - var fields = node.fields; + } // apply texture transform - for ( var i = 0, l = fields.length; i < l; i ++ ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + if ( transformData ) { - switch ( fieldName ) { + material.map.center.copy( transformData.center ); + material.map.rotation = transformData.rotation; + material.map.repeat.copy( transformData.scale ); + material.map.offset.copy( transformData.translation ); - case 'ambientIntensity': - // field not supported - break; - - case 'diffuseColor': - materialData.diffuseColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - break; + } - case 'emissiveColor': - materialData.emissiveColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - break; + } - case 'shininess': - materialData.shininess = fieldValues[ 0 ]; - break; + return material; - case 'specularColor': - materialData.emissiveColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - break; + } - case 'transparency': - materialData.transparency = fieldValues[ 0 ]; - break; + function buildMaterialNode( node ) { - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + const materialData = {}; + const fields = node.fields; - } - - } + for ( let i = 0, l = fields.length; i < l; i ++ ) { - return materialData; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - } + switch ( fieldName ) { - function parseHexColor( hex, textureType, color ) { + case 'ambientIntensity': + // field not supported + break; - switch ( textureType ) { + case 'diffuseColor': + materialData.diffuseColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); + break; - case TEXTURE_TYPE.INTENSITY: - // Intensity texture: A one-component image specifies one-byte hexadecimal or integer values representing the intensity of the image - var value = parseInt( hex ); - color.r = value; - color.g = value; - color.b = value; + case 'emissiveColor': + materialData.emissiveColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; - case TEXTURE_TYPE.INTENSITY_ALPHA: - // Intensity+Alpha texture: A two-component image specifies the intensity in the first (high) byte and the alpha opacity in the second (low) byte. - var value = parseInt( '0x' + hex.substring( 2, 4 ) ); - color.r = value; - color.g = value; - color.b = value; - color.a = parseInt( '0x' + hex.substring( 4, 6 ) ); + case 'shininess': + materialData.shininess = fieldValues[ 0 ]; break; - case TEXTURE_TYPE.RGB: - // RGB texture: Pixels in a three-component image specify the red component in the first (high) byte, followed by the green and blue components - color.r = parseInt( '0x' + hex.substring( 2, 4 ) ); - color.g = parseInt( '0x' + hex.substring( 4, 6 ) ); - color.b = parseInt( '0x' + hex.substring( 6, 8 ) ); + case 'specularColor': + materialData.emissiveColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; - case TEXTURE_TYPE.RGBA: - // RGBA texture: Four-component images specify the alpha opacity byte after red/green/blue - color.r = parseInt( '0x' + hex.substring( 2, 4 ) ); - color.g = parseInt( '0x' + hex.substring( 4, 6 ) ); - color.b = parseInt( '0x' + hex.substring( 6, 8 ) ); - color.a = parseInt( '0x' + hex.substring( 8, 10 ) ); + case 'transparency': + materialData.transparency = fieldValues[ 0 ]; break; default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } } - function getTextureType( num_components ) { + return materialData; - var type; - - switch ( num_components ) { + } - case 1: - type = TEXTURE_TYPE.INTENSITY; - break; + function parseHexColor( hex, textureType, color ) { + + let value; + + switch ( textureType ) { + + case TEXTURE_TYPE.INTENSITY: + // Intensity texture: A one-component image specifies one-byte hexadecimal or integer values representing the intensity of the image + value = parseInt( hex ); + color.r = value; + color.g = value; + color.b = value; + break; + + case TEXTURE_TYPE.INTENSITY_ALPHA: + // Intensity+Alpha texture: A two-component image specifies the intensity in the first (high) byte and the alpha opacity in the second (low) byte. + value = parseInt( '0x' + hex.substring( 2, 4 ) ); + color.r = value; + color.g = value; + color.b = value; + color.a = parseInt( '0x' + hex.substring( 4, 6 ) ); + break; + + case TEXTURE_TYPE.RGB: + // RGB texture: Pixels in a three-component image specify the red component in the first (high) byte, followed by the green and blue components + color.r = parseInt( '0x' + hex.substring( 2, 4 ) ); + color.g = parseInt( '0x' + hex.substring( 4, 6 ) ); + color.b = parseInt( '0x' + hex.substring( 6, 8 ) ); + break; + + case TEXTURE_TYPE.RGBA: + // RGBA texture: Four-component images specify the alpha opacity byte after red/green/blue + color.r = parseInt( '0x' + hex.substring( 2, 4 ) ); + color.g = parseInt( '0x' + hex.substring( 4, 6 ) ); + color.b = parseInt( '0x' + hex.substring( 6, 8 ) ); + color.a = parseInt( '0x' + hex.substring( 8, 10 ) ); + break; + + default: - case 2: - type = TEXTURE_TYPE.INTENSITY_ALPHA; - break; + } - case 3: - type = TEXTURE_TYPE.RGB; - break; + } - case 4: - type = TEXTURE_TYPE.RGBA; - break; + function getTextureType( num_components ) { - default: + let type; - } + switch ( num_components ) { - return type; + case 1: + type = TEXTURE_TYPE.INTENSITY; + break; - } + case 2: + type = TEXTURE_TYPE.INTENSITY_ALPHA; + break; - function buildPixelTextureNode( node ) { + case 3: + type = TEXTURE_TYPE.RGB; + break; - var texture; - var wrapS = THREE.RepeatWrapping; - var wrapT = THREE.RepeatWrapping; - var fields = node.fields; + case 4: + type = TEXTURE_TYPE.RGBA; + break; - for ( var i = 0, l = fields.length; i < l; i ++ ) { + default: - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + } - switch ( fieldName ) { + return type; - case 'image': - var width = fieldValues[ 0 ]; - var height = fieldValues[ 1 ]; - var num_components = fieldValues[ 2 ]; - var useAlpha = num_components === 2 || num_components === 4; - var textureType = getTextureType( num_components ); - var size = ( useAlpha === true ? 4 : 3 ) * ( width * height ); - var data = new Uint8Array( size ); - var color = { - r: 0, - g: 0, - b: 0, - a: 0 - }; + } - for ( var j = 3, k = 0, jl = fieldValues.length; j < jl; j ++, k ++ ) { + function buildPixelTextureNode( node ) { + + let texture; + let wrapS = THREE.RepeatWrapping; + let wrapT = THREE.RepeatWrapping; + const fields = node.fields; + + for ( let i = 0, l = fields.length; i < l; i ++ ) { + + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; + + switch ( fieldName ) { + + case 'image': + const width = fieldValues[ 0 ]; + const height = fieldValues[ 1 ]; + const num_components = fieldValues[ 2 ]; + const useAlpha = num_components === 2 || num_components === 4; + const textureType = getTextureType( num_components ); + const size = ( useAlpha === true ? 4 : 3 ) * ( width * height ); + const data = new Uint8Array( size ); + const color = { + r: 0, + g: 0, + b: 0, + a: 0 + }; - parseHexColor( fieldValues[ j ], textureType, color ); + for ( let j = 3, k = 0, jl = fieldValues.length; j < jl; j ++, k ++ ) { - if ( useAlpha === true ) { + parseHexColor( fieldValues[ j ], textureType, color ); - var stride = k * 4; - data[ stride + 0 ] = color.r; - data[ stride + 1 ] = color.g; - data[ stride + 2 ] = color.b; - data[ stride + 3 ] = color.a; + if ( useAlpha === true ) { - } else { + const stride = k * 4; + data[ stride + 0 ] = color.r; + data[ stride + 1 ] = color.g; + data[ stride + 2 ] = color.b; + data[ stride + 3 ] = color.a; - var stride = k * 3; - data[ stride + 0 ] = color.r; - data[ stride + 1 ] = color.g; - data[ stride + 2 ] = color.b; + } else { - } + const stride = k * 3; + data[ stride + 0 ] = color.r; + data[ stride + 1 ] = color.g; + data[ stride + 2 ] = color.b; } - texture = new THREE.DataTexture( data, width, height, useAlpha === true ? THREE.RGBAFormat : THREE.RGBFormat ); - texture.__type = textureType; // needed for material modifications + } - break; + texture = new THREE.DataTexture( data, width, height, useAlpha === true ? THREE.RGBAFormat : THREE.RGBFormat ); + texture.__type = textureType; // needed for material modifications - case 'repeatS': - if ( fieldValues[ 0 ] === false ) wrapS = THREE.ClampToEdgeWrapping; - break; + break; - case 'repeatT': - if ( fieldValues[ 0 ] === false ) wrapT = THREE.ClampToEdgeWrapping; - break; + case 'repeatS': + if ( fieldValues[ 0 ] === false ) wrapS = THREE.ClampToEdgeWrapping; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'repeatT': + if ( fieldValues[ 0 ] === false ) wrapT = THREE.ClampToEdgeWrapping; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - if ( texture ) { - - texture.wrapS = wrapS; - texture.wrapT = wrapT; + } - } + if ( texture ) { - return texture; + texture.wrapS = wrapS; + texture.wrapT = wrapT; } - function buildImageTextureNode( node ) { + return texture; - var texture; - var wrapS = THREE.RepeatWrapping; - var wrapT = THREE.RepeatWrapping; - var fields = node.fields; + } - for ( var i = 0, l = fields.length; i < l; i ++ ) { + function buildImageTextureNode( node ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + let texture; + let wrapS = THREE.RepeatWrapping; + let wrapT = THREE.RepeatWrapping; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'url': - var url = fieldValues[ 0 ]; - if ( url ) texture = textureLoader.load( url ); - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'repeatS': - if ( fieldValues[ 0 ] === false ) wrapS = THREE.ClampToEdgeWrapping; - break; + switch ( fieldName ) { - case 'repeatT': - if ( fieldValues[ 0 ] === false ) wrapT = THREE.ClampToEdgeWrapping; - break; + case 'url': + const url = fieldValues[ 0 ]; + if ( url ) texture = textureLoader.load( url ); + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'repeatS': + if ( fieldValues[ 0 ] === false ) wrapS = THREE.ClampToEdgeWrapping; + break; - } + case 'repeatT': + if ( fieldValues[ 0 ] === false ) wrapT = THREE.ClampToEdgeWrapping; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - if ( texture ) { + } - texture.wrapS = wrapS; - texture.wrapT = wrapT; + } - } + if ( texture ) { - return texture; + texture.wrapS = wrapS; + texture.wrapT = wrapT; } - function buildTextureTransformNode( node ) { + return texture; - var transformData = { - center: new THREE.Vector2(), - rotation: new THREE.Vector2(), - scale: new THREE.Vector2(), - translation: new THREE.Vector2() - }; - var fields = node.fields; + } - for ( var i = 0, l = fields.length; i < l; i ++ ) { + function buildTextureTransformNode( node ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const transformData = { + center: new THREE.Vector2(), + rotation: new THREE.Vector2(), + scale: new THREE.Vector2(), + translation: new THREE.Vector2() + }; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'center': - transformData.center.set( fieldValues[ 0 ], fieldValues[ 1 ] ); - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'rotation': - transformData.rotation = fieldValues[ 0 ]; - break; + switch ( fieldName ) { - case 'scale': - transformData.scale.set( fieldValues[ 0 ], fieldValues[ 1 ] ); - break; + case 'center': + transformData.center.set( fieldValues[ 0 ], fieldValues[ 1 ] ); + break; - case 'translation': - transformData.translation.set( fieldValues[ 0 ], fieldValues[ 1 ] ); - break; + case 'rotation': + transformData.rotation = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'scale': + transformData.scale.set( fieldValues[ 0 ], fieldValues[ 1 ] ); + break; - } + case 'translation': + transformData.translation.set( fieldValues[ 0 ], fieldValues[ 1 ] ); + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - return transformData; + } } - function buildGeometricNode( node ) { + return transformData; - return node.fields[ 0 ].values; + } - } + function buildGeometricNode( node ) { - function buildWorldInfoNode( node ) { + return node.fields[ 0 ].values; - var worldInfo = {}; - var fields = node.fields; + } - for ( var i = 0, l = fields.length; i < l; i ++ ) { + function buildWorldInfoNode( node ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const worldInfo = {}; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'title': - worldInfo.title = fieldValues[ 0 ]; - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'info': - worldInfo.info = fieldValues; - break; + switch ( fieldName ) { - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'title': + worldInfo.title = fieldValues[ 0 ]; + break; - } + case 'info': + worldInfo.info = fieldValues; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - return worldInfo; + } } - function buildIndexedFaceSetNode( node ) { + return worldInfo; - var color, coord, normal, texCoord; - var ccw = true, - solid = true, - creaseAngle = 0; - var colorIndex, coordIndex, normalIndex, texCoordIndex; - var colorPerVertex = true, - normalPerVertex = true; - var fields = node.fields; + } - for ( var i = 0, l = fields.length; i < l; i ++ ) { + function buildIndexedFaceSetNode( node ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + let color, coord, normal, texCoord; + let ccw = true, + solid = true, + creaseAngle = 0; + let colorIndex, coordIndex, normalIndex, texCoordIndex; + let colorPerVertex = true, + normalPerVertex = true; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'color': - var colorNode = fieldValues[ 0 ]; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - if ( colorNode !== null ) { + switch ( fieldName ) { - color = getNode( colorNode ); + case 'color': + const colorNode = fieldValues[ 0 ]; - } + if ( colorNode !== null ) { - break; + color = getNode( colorNode ); - case 'coord': - var coordNode = fieldValues[ 0 ]; + } - if ( coordNode !== null ) { + break; - coord = getNode( coordNode ); + case 'coord': + const coordNode = fieldValues[ 0 ]; - } + if ( coordNode !== null ) { - break; + coord = getNode( coordNode ); - case 'normal': - var normalNode = fieldValues[ 0 ]; + } - if ( normalNode !== null ) { + break; - normal = getNode( normalNode ); + case 'normal': + const normalNode = fieldValues[ 0 ]; - } + if ( normalNode !== null ) { - break; + normal = getNode( normalNode ); - case 'texCoord': - var texCoordNode = fieldValues[ 0 ]; + } - if ( texCoordNode !== null ) { + break; - texCoord = getNode( texCoordNode ); + case 'texCoord': + const texCoordNode = fieldValues[ 0 ]; - } + if ( texCoordNode !== null ) { - break; + texCoord = getNode( texCoordNode ); - case 'ccw': - ccw = fieldValues[ 0 ]; - break; + } - case 'colorIndex': - colorIndex = fieldValues; - break; + break; - case 'colorPerVertex': - colorPerVertex = fieldValues[ 0 ]; - break; + case 'ccw': + ccw = fieldValues[ 0 ]; + break; - case 'convex': - // field not supported - break; + case 'colorIndex': + colorIndex = fieldValues; + break; - case 'coordIndex': - coordIndex = fieldValues; - break; + case 'colorPerVertex': + colorPerVertex = fieldValues[ 0 ]; + break; - case 'creaseAngle': - creaseAngle = fieldValues[ 0 ]; - break; + case 'convex': + // field not supported + break; - case 'normalIndex': - normalIndex = fieldValues; - break; + case 'coordIndex': + coordIndex = fieldValues; + break; - case 'normalPerVertex': - normalPerVertex = fieldValues[ 0 ]; - break; + case 'creaseAngle': + creaseAngle = fieldValues[ 0 ]; + break; - case 'solid': - solid = fieldValues[ 0 ]; - break; + case 'normalIndex': + normalIndex = fieldValues; + break; - case 'texCoordIndex': - texCoordIndex = fieldValues; - break; + case 'normalPerVertex': + normalPerVertex = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'solid': + solid = fieldValues[ 0 ]; + break; - } + case 'texCoordIndex': + texCoordIndex = fieldValues; + break; + + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - if ( coordIndex === undefined ) { + } - console.warn( 'THREE.VRMLLoader: Missing coordIndex.' ); - return new THREE.BufferGeometry(); // handle VRML files with incomplete geometry definition + if ( coordIndex === undefined ) { - } + console.warn( 'THREE.VRMLLoader: Missing coordIndex.' ); + return new THREE.BufferGeometry(); // handle VRML files with incomplete geometry definition - var triangulatedCoordIndex = triangulateFaceIndex( coordIndex, ccw ); - var positionAttribute; - var colorAttribute; - var normalAttribute; - var uvAttribute; + } - if ( color ) { + const triangulatedCoordIndex = triangulateFaceIndex( coordIndex, ccw ); + let colorAttribute; + let normalAttribute; + let uvAttribute; - if ( colorPerVertex === true ) { + if ( color ) { - if ( colorIndex && colorIndex.length > 0 ) { + if ( colorPerVertex === true ) { - // if the colorIndex field is not empty, then it is used to choose colors for each vertex of the IndexedFaceSet. - var triangulatedColorIndex = triangulateFaceIndex( colorIndex, ccw ); - colorAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedColorIndex, color, 3 ); + if ( colorIndex && colorIndex.length > 0 ) { - } else { + // if the colorIndex field is not empty, then it is used to choose colors for each vertex of the IndexedFaceSet. + const triangulatedColorIndex = triangulateFaceIndex( colorIndex, ccw ); + colorAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedColorIndex, color, 3 ); - // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the THREE.Color node - colorAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( color, 3 ) ); + } else { - } + // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the THREE.Color node + colorAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( color, 3 ) ); - } else { + } - if ( colorIndex && colorIndex.length > 0 ) { + } else { - // if the colorIndex field is not empty, then they are used to choose one color for each face of the IndexedFaceSet - var flattenFaceColors = flattenData( color, colorIndex ); - var triangulatedFaceColors = triangulateFaceData( flattenFaceColors, coordIndex ); - colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors ); + if ( colorIndex && colorIndex.length > 0 ) { - } else { + // if the colorIndex field is not empty, then they are used to choose one color for each face of the IndexedFaceSet + const flattenFaceColors = flattenData( color, colorIndex ); + const triangulatedFaceColors = triangulateFaceData( flattenFaceColors, coordIndex ); + colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors ); - // if the colorIndex field is empty, then the color are applied to each face of the IndexedFaceSet in order - var triangulatedFaceColors = triangulateFaceData( color, coordIndex ); - colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors ); + } else { - } + // if the colorIndex field is empty, then the color are applied to each face of the IndexedFaceSet in order + const triangulatedFaceColors = triangulateFaceData( color, coordIndex ); + colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors ); } } - if ( normal ) { + } - if ( normalPerVertex === true ) { + if ( normal ) { - // consider vertex normals - if ( normalIndex && normalIndex.length > 0 ) { + if ( normalPerVertex === true ) { - // if the normalIndex field is not empty, then it is used to choose normals for each vertex of the IndexedFaceSet. - var triangulatedNormalIndex = triangulateFaceIndex( normalIndex, ccw ); - normalAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedNormalIndex, normal, 3 ); + // consider vertex normals + if ( normalIndex && normalIndex.length > 0 ) { - } else { + // if the normalIndex field is not empty, then it is used to choose normals for each vertex of the IndexedFaceSet. + const triangulatedNormalIndex = triangulateFaceIndex( normalIndex, ccw ); + normalAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedNormalIndex, normal, 3 ); - // if the normalIndex field is empty, then the coordIndex field is used to choose normals from the Normal node - normalAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( normal, 3 ) ); + } else { - } + // if the normalIndex field is empty, then the coordIndex field is used to choose normals from the Normal node + normalAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( normal, 3 ) ); - } else { + } - // consider face normals - if ( normalIndex && normalIndex.length > 0 ) { + } else { - // if the normalIndex field is not empty, then they are used to choose one normal for each face of the IndexedFaceSet - var flattenFaceNormals = flattenData( normal, normalIndex ); - var triangulatedFaceNormals = triangulateFaceData( flattenFaceNormals, coordIndex ); - normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals ); + // consider face normals + if ( normalIndex && normalIndex.length > 0 ) { - } else { + // if the normalIndex field is not empty, then they are used to choose one normal for each face of the IndexedFaceSet + const flattenFaceNormals = flattenData( normal, normalIndex ); + const triangulatedFaceNormals = triangulateFaceData( flattenFaceNormals, coordIndex ); + normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals ); - // if the normalIndex field is empty, then the normals are applied to each face of the IndexedFaceSet in order - var triangulatedFaceNormals = triangulateFaceData( normal, coordIndex ); - normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals ); + } else { - } + // if the normalIndex field is empty, then the normals are applied to each face of the IndexedFaceSet in order + const triangulatedFaceNormals = triangulateFaceData( normal, coordIndex ); + normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals ); } - } else { + } - // if the normal field is NULL, then the loader should automatically generate normals, using creaseAngle to determine if and how normals are smoothed across shared vertices - normalAttribute = computeNormalAttribute( triangulatedCoordIndex, coord, creaseAngle ); + } else { - } + // if the normal field is NULL, then the loader should automatically generate normals, using creaseAngle to determine if and how normals are smoothed across shared vertices + normalAttribute = computeNormalAttribute( triangulatedCoordIndex, coord, creaseAngle ); - if ( texCoord ) { + } - // texture coordinates are always defined on vertex level - if ( texCoordIndex && texCoordIndex.length > 0 ) { + if ( texCoord ) { - // if the texCoordIndex field is not empty, then it is used to choose texture coordinates for each vertex of the IndexedFaceSet. - var triangulatedTexCoordIndex = triangulateFaceIndex( texCoordIndex, ccw ); - uvAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedTexCoordIndex, texCoord, 2 ); + // texture coordinates are always defined on vertex level + if ( texCoordIndex && texCoordIndex.length > 0 ) { - } else { + // if the texCoordIndex field is not empty, then it is used to choose texture coordinates for each vertex of the IndexedFaceSet. + const triangulatedTexCoordIndex = triangulateFaceIndex( texCoordIndex, ccw ); + uvAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedTexCoordIndex, texCoord, 2 ); - // if the texCoordIndex field is empty, then the coordIndex array is used to choose texture coordinates from the TextureCoordinate node - uvAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( texCoord, 2 ) ); + } else { - } + // if the texCoordIndex field is empty, then the coordIndex array is used to choose texture coordinates from the TextureCoordinate node + uvAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( texCoord, 2 ) ); } - var geometry = new THREE.BufferGeometry(); - positionAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( coord, 3 ) ); - geometry.setAttribute( 'position', positionAttribute ); - geometry.setAttribute( 'normal', normalAttribute ); // optional attributes + } - if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); - if ( uvAttribute ) geometry.setAttribute( 'uv', uvAttribute ); // "solid" influences the material so let's store it for later use + const geometry = new THREE.BufferGeometry(); + const positionAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( coord, 3 ) ); + geometry.setAttribute( 'position', positionAttribute ); + geometry.setAttribute( 'normal', normalAttribute ); // optional attributes - geometry._solid = solid; - geometry._type = 'mesh'; - return geometry; + if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); + if ( uvAttribute ) geometry.setAttribute( 'uv', uvAttribute ); // "solid" influences the material so let's store it for later use - } + geometry._solid = solid; + geometry._type = 'mesh'; + return geometry; - function buildIndexedLineSetNode( node ) { + } - var color, coord; - var colorIndex, coordIndex; - var colorPerVertex = true; - var fields = node.fields; + function buildIndexedLineSetNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + let color, coord; + let colorIndex, coordIndex; + let colorPerVertex = true; + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'color': - var colorNode = fieldValues[ 0 ]; + switch ( fieldName ) { - if ( colorNode !== null ) { + case 'color': + const colorNode = fieldValues[ 0 ]; - color = getNode( colorNode ); + if ( colorNode !== null ) { - } + color = getNode( colorNode ); - break; + } - case 'coord': - var coordNode = fieldValues[ 0 ]; + break; - if ( coordNode !== null ) { + case 'coord': + const coordNode = fieldValues[ 0 ]; - coord = getNode( coordNode ); + if ( coordNode !== null ) { - } + coord = getNode( coordNode ); - break; + } - case 'colorIndex': - colorIndex = fieldValues; - break; + break; - case 'colorPerVertex': - colorPerVertex = fieldValues[ 0 ]; - break; + case 'colorIndex': + colorIndex = fieldValues; + break; - case 'coordIndex': - coordIndex = fieldValues; - break; + case 'colorPerVertex': + colorPerVertex = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'coordIndex': + coordIndex = fieldValues; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - } // build lines + } + } // build lines - var colorAttribute; - var expandedLineIndex = expandLineIndex( coordIndex ); // create an index for three.js's linesegment primitive - if ( color ) { + let colorAttribute; + const expandedLineIndex = expandLineIndex( coordIndex ); // create an index for three.js's linesegment primitive - if ( colorPerVertex === true ) { + if ( color ) { - if ( colorIndex.length > 0 ) { + if ( colorPerVertex === true ) { - // if the colorIndex field is not empty, then one color is used for each polyline of the IndexedLineSet. - var expandedColorIndex = expandLineIndex( colorIndex ); // compute colors for each line segment (rendering primitve) + if ( colorIndex.length > 0 ) { - colorAttribute = computeAttributeFromIndexedData( expandedLineIndex, expandedColorIndex, color, 3 ); // compute data on vertex level + // if the colorIndex field is not empty, then one color is used for each polyline of the IndexedLineSet. + const expandedColorIndex = expandLineIndex( colorIndex ); // compute colors for each line segment (rendering primitve) - } else { + colorAttribute = computeAttributeFromIndexedData( expandedLineIndex, expandedColorIndex, color, 3 ); // compute data on vertex level - // if the colorIndex field is empty, then the colors are applied to each polyline of the IndexedLineSet in order. - colorAttribute = toNonIndexedAttribute( expandedLineIndex, new THREE.Float32BufferAttribute( color, 3 ) ); + } else { - } + // if the colorIndex field is empty, then the colors are applied to each polyline of the IndexedLineSet in order. + colorAttribute = toNonIndexedAttribute( expandedLineIndex, new THREE.Float32BufferAttribute( color, 3 ) ); - } else { + } - if ( colorIndex.length > 0 ) { + } else { - // if the colorIndex field is not empty, then colors are applied to each vertex of the IndexedLineSet - var flattenLineColors = flattenData( color, colorIndex ); // compute colors for each VRML primitve + if ( colorIndex.length > 0 ) { - var expandedLineColors = expandLineData( flattenLineColors, coordIndex ); // compute colors for each line segment (rendering primitve) + // if the colorIndex field is not empty, then colors are applied to each vertex of the IndexedLineSet + const flattenLineColors = flattenData( color, colorIndex ); // compute colors for each VRML primitve - colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level + const expandedLineColors = expandLineData( flattenLineColors, coordIndex ); // compute colors for each line segment (rendering primitve) - } else { + colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level - // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the THREE.Color node - var expandedLineColors = expandLineData( color, coordIndex ); // compute colors for each line segment (rendering primitve) + } else { - colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level + // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the THREE.Color node + const expandedLineColors = expandLineData( color, coordIndex ); // compute colors for each line segment (rendering primitve) - } + colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level } - } // + } + } // - var geometry = new THREE.BufferGeometry(); - var positionAttribute = toNonIndexedAttribute( expandedLineIndex, new THREE.Float32BufferAttribute( coord, 3 ) ); - geometry.setAttribute( 'position', positionAttribute ); - if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); - geometry._type = 'line'; - return geometry; - } + const geometry = new THREE.BufferGeometry(); + const positionAttribute = toNonIndexedAttribute( expandedLineIndex, new THREE.Float32BufferAttribute( coord, 3 ) ); + geometry.setAttribute( 'position', positionAttribute ); + if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); + geometry._type = 'line'; + return geometry; - function buildPointSetNode( node ) { + } - var geometry; - var color, coord; - var fields = node.fields; + function buildPointSetNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + let color, coord; + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'color': - var colorNode = fieldValues[ 0 ]; + switch ( fieldName ) { - if ( colorNode !== null ) { + case 'color': + const colorNode = fieldValues[ 0 ]; - color = getNode( colorNode ); + if ( colorNode !== null ) { - } + color = getNode( colorNode ); - break; + } - case 'coord': - var coordNode = fieldValues[ 0 ]; + break; - if ( coordNode !== null ) { + case 'coord': + const coordNode = fieldValues[ 0 ]; - coord = getNode( coordNode ); + if ( coordNode !== null ) { - } + coord = getNode( coordNode ); - break; + } - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - var geometry = new THREE.BufferGeometry(); - geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( coord, 3 ) ); - if ( color ) geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( color, 3 ) ); - geometry._type = 'points'; - return geometry; - } - function buildBoxNode( node ) { + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( coord, 3 ) ); + if ( color ) geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( color, 3 ) ); + geometry._type = 'points'; + return geometry; - var size = new THREE.Vector3( 2, 2, 2 ); - var fields = node.fields; + } - for ( var i = 0, l = fields.length; i < l; i ++ ) { + function buildBoxNode( node ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const size = new THREE.Vector3( 2, 2, 2 ); + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'size': - size.x = fieldValues[ 0 ]; - size.y = fieldValues[ 1 ]; - size.z = fieldValues[ 2 ]; - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + switch ( fieldName ) { - } + case 'size': + size.x = fieldValues[ 0 ]; + size.y = fieldValues[ 1 ]; + size.z = fieldValues[ 2 ]; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - var geometry = new THREE.BoxGeometry( size.x, size.y, size.z ); - return geometry; + } } - function buildConeNode( node ) { + const geometry = new THREE.BoxGeometry( size.x, size.y, size.z ); + return geometry; + + } - var radius = 1, - height = 2, - openEnded = false; - var fields = node.fields; + function buildConeNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + let radius = 1, + height = 2, + openEnded = false; + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'bottom': - openEnded = ! fieldValues[ 0 ]; - break; + switch ( fieldName ) { - case 'bottomRadius': - radius = fieldValues[ 0 ]; - break; + case 'bottom': + openEnded = ! fieldValues[ 0 ]; + break; - case 'height': - height = fieldValues[ 0 ]; - break; + case 'bottomRadius': + radius = fieldValues[ 0 ]; + break; - case 'side': - // field not supported - break; + case 'height': + height = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'side': + // field not supported + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - var geometry = new THREE.ConeGeometry( radius, height, 16, 1, openEnded ); - return geometry; - } - function buildCylinderNode( node ) { + const geometry = new THREE.ConeGeometry( radius, height, 16, 1, openEnded ); + return geometry; - var radius = 1, - height = 2; - var fields = node.fields; + } - for ( var i = 0, l = fields.length; i < l; i ++ ) { + function buildCylinderNode( node ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + let radius = 1, + height = 2; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'bottom': - // field not supported - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'radius': - radius = fieldValues[ 0 ]; - break; + switch ( fieldName ) { - case 'height': - height = fieldValues[ 0 ]; - break; + case 'bottom': + // field not supported + break; - case 'side': - // field not supported - break; + case 'radius': + radius = fieldValues[ 0 ]; + break; - case 'top': - // field not supported - break; + case 'height': + height = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'side': + // field not supported + break; - } + case 'top': + // field not supported + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - var geometry = new THREE.CylinderGeometry( radius, radius, height, 16, 1 ); - return geometry; + } } - function buildSphereNode( node ) { + const geometry = new THREE.CylinderGeometry( radius, radius, height, 16, 1 ); + return geometry; - var radius = 1; - var fields = node.fields; + } - for ( var i = 0, l = fields.length; i < l; i ++ ) { + function buildSphereNode( node ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + let radius = 1; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'radius': - radius = fieldValues[ 0 ]; - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + switch ( fieldName ) { - } + case 'radius': + radius = fieldValues[ 0 ]; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - var geometry = new THREE.SphereGeometry( radius, 16, 16 ); - return geometry; + } } - function buildElevationGridNode( node ) { + const geometry = new THREE.SphereGeometry( radius, 16, 16 ); + return geometry; - var color; - var normal; - var texCoord; - var height; - var colorPerVertex = true; - var normalPerVertex = true; - var solid = true; - var ccw = true; - var creaseAngle = 0; - var xDimension = 2; - var zDimension = 2; - var xSpacing = 1; - var zSpacing = 1; - var fields = node.fields; + } - for ( var i = 0, l = fields.length; i < l; i ++ ) { + function buildElevationGridNode( node ) { - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + let color; + let normal; + let texCoord; + let height; + let colorPerVertex = true; + let normalPerVertex = true; + let solid = true; + let ccw = true; + let creaseAngle = 0; + let xDimension = 2; + let zDimension = 2; + let xSpacing = 1; + let zSpacing = 1; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'color': - var colorNode = fieldValues[ 0 ]; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - if ( colorNode !== null ) { + switch ( fieldName ) { - color = getNode( colorNode ); + case 'color': + const colorNode = fieldValues[ 0 ]; - } + if ( colorNode !== null ) { - break; + color = getNode( colorNode ); - case 'normal': - var normalNode = fieldValues[ 0 ]; + } - if ( normalNode !== null ) { + break; - normal = getNode( normalNode ); + case 'normal': + const normalNode = fieldValues[ 0 ]; - } + if ( normalNode !== null ) { - break; + normal = getNode( normalNode ); - case 'texCoord': - var texCoordNode = fieldValues[ 0 ]; + } - if ( texCoordNode !== null ) { + break; - texCoord = getNode( texCoordNode ); + case 'texCoord': + const texCoordNode = fieldValues[ 0 ]; - } + if ( texCoordNode !== null ) { - break; + texCoord = getNode( texCoordNode ); - case 'height': - height = fieldValues; - break; + } - case 'ccw': - ccw = fieldValues[ 0 ]; - break; + break; - case 'colorPerVertex': - colorPerVertex = fieldValues[ 0 ]; - break; + case 'height': + height = fieldValues; + break; - case 'creaseAngle': - creaseAngle = fieldValues[ 0 ]; - break; + case 'ccw': + ccw = fieldValues[ 0 ]; + break; - case 'normalPerVertex': - normalPerVertex = fieldValues[ 0 ]; - break; + case 'colorPerVertex': + colorPerVertex = fieldValues[ 0 ]; + break; - case 'solid': - solid = fieldValues[ 0 ]; - break; + case 'creaseAngle': + creaseAngle = fieldValues[ 0 ]; + break; - case 'xDimension': - xDimension = fieldValues[ 0 ]; - break; + case 'normalPerVertex': + normalPerVertex = fieldValues[ 0 ]; + break; - case 'xSpacing': - xSpacing = fieldValues[ 0 ]; - break; + case 'solid': + solid = fieldValues[ 0 ]; + break; - case 'zDimension': - zDimension = fieldValues[ 0 ]; - break; + case 'xDimension': + xDimension = fieldValues[ 0 ]; + break; - case 'zSpacing': - zSpacing = fieldValues[ 0 ]; - break; + case 'xSpacing': + xSpacing = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'zDimension': + zDimension = fieldValues[ 0 ]; + break; - } + case 'zSpacing': + zSpacing = fieldValues[ 0 ]; + break; + + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - } // vertex data + } + } // vertex data - var vertices = []; - var normals = []; - var colors = []; - var uvs = []; - for ( var i = 0; i < zDimension; i ++ ) { + const vertices = []; + const normals = []; + const colors = []; + const uvs = []; - for ( var j = 0; j < xDimension; j ++ ) { + for ( let i = 0; i < zDimension; i ++ ) { - // compute a row major index - var index = i * xDimension + j; // vertices + for ( let j = 0; j < xDimension; j ++ ) { - var x = xSpacing * i; - var y = height[ index ]; - var z = zSpacing * j; - vertices.push( x, y, z ); // colors + // compute a row major index + const index = i * xDimension + j; // vertices - if ( color && colorPerVertex === true ) { + const x = xSpacing * i; + const y = height[ index ]; + const z = zSpacing * j; + vertices.push( x, y, z ); // colors - var r = color[ index * 3 + 0 ]; - var g = color[ index * 3 + 1 ]; - var b = color[ index * 3 + 2 ]; - colors.push( r, g, b ); + if ( color && colorPerVertex === true ) { - } // normals + const r = color[ index * 3 + 0 ]; + const g = color[ index * 3 + 1 ]; + const b = color[ index * 3 + 2 ]; + colors.push( r, g, b ); + } // normals - if ( normal && normalPerVertex === true ) { - var xn = normal[ index * 3 + 0 ]; - var yn = normal[ index * 3 + 1 ]; - var zn = normal[ index * 3 + 2 ]; - normals.push( xn, yn, zn ); + if ( normal && normalPerVertex === true ) { - } // uvs + const xn = normal[ index * 3 + 0 ]; + const yn = normal[ index * 3 + 1 ]; + const zn = normal[ index * 3 + 2 ]; + normals.push( xn, yn, zn ); + } // uvs - if ( texCoord ) { - var s = texCoord[ index * 2 + 0 ]; - var t = texCoord[ index * 2 + 1 ]; - uvs.push( s, t ); + if ( texCoord ) { - } else { + const s = texCoord[ index * 2 + 0 ]; + const t = texCoord[ index * 2 + 1 ]; + uvs.push( s, t ); - uvs.push( i / ( xDimension - 1 ), j / ( zDimension - 1 ) ); + } else { - } + uvs.push( i / ( xDimension - 1 ), j / ( zDimension - 1 ) ); } - } // indices + } + } // indices - var indices = []; - for ( var i = 0; i < xDimension - 1; i ++ ) { + const indices = []; - for ( var j = 0; j < zDimension - 1; j ++ ) { + for ( let i = 0; i < xDimension - 1; i ++ ) { - // from https://tecfa.unige.ch/guides/vrml/vrml97/spec/part1/nodesRef.html#ElevationGrid - var a = i + j * xDimension; - var b = i + ( j + 1 ) * xDimension; - var c = i + 1 + ( j + 1 ) * xDimension; - var d = i + 1 + j * xDimension; // faces + for ( let j = 0; j < zDimension - 1; j ++ ) { - if ( ccw === true ) { + // from https://tecfa.unige.ch/guides/vrml/vrml97/spec/part1/nodesRef.html#ElevationGrid + const a = i + j * xDimension; + const b = i + ( j + 1 ) * xDimension; + const c = i + 1 + ( j + 1 ) * xDimension; + const d = i + 1 + j * xDimension; // faces - indices.push( a, c, b ); - indices.push( c, a, d ); + if ( ccw === true ) { - } else { + indices.push( a, c, b ); + indices.push( c, a, d ); - indices.push( a, b, c ); - indices.push( c, d, a ); + } else { - } + indices.push( a, b, c ); + indices.push( c, d, a ); } - } // + } + } // - var positionAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( vertices, 3 ) ); - var uvAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( uvs, 2 ) ); - var colorAttribute; - var normalAttribute; // color attribute - if ( color ) { + const positionAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( vertices, 3 ) ); + const uvAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( uvs, 2 ) ); + let colorAttribute; + let normalAttribute; // color attribute - if ( colorPerVertex === false ) { + if ( color ) { - for ( var i = 0; i < xDimension - 1; i ++ ) { + if ( colorPerVertex === false ) { - for ( var j = 0; j < zDimension - 1; j ++ ) { + for ( let i = 0; i < xDimension - 1; i ++ ) { - var index = i + j * ( xDimension - 1 ); - var r = color[ index * 3 + 0 ]; - var g = color[ index * 3 + 1 ]; - var b = color[ index * 3 + 2 ]; // one color per quad + for ( let j = 0; j < zDimension - 1; j ++ ) { - colors.push( r, g, b ); - colors.push( r, g, b ); - colors.push( r, g, b ); - colors.push( r, g, b ); - colors.push( r, g, b ); - colors.push( r, g, b ); + const index = i + j * ( xDimension - 1 ); + const r = color[ index * 3 + 0 ]; + const g = color[ index * 3 + 1 ]; + const b = color[ index * 3 + 2 ]; // one color per quad - } + colors.push( r, g, b ); + colors.push( r, g, b ); + colors.push( r, g, b ); + colors.push( r, g, b ); + colors.push( r, g, b ); + colors.push( r, g, b ); } - colorAttribute = new THREE.Float32BufferAttribute( colors, 3 ); + } - } else { + colorAttribute = new THREE.Float32BufferAttribute( colors, 3 ); - colorAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( colors, 3 ) ); + } else { - } + colorAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( colors, 3 ) ); - } // normal attribute + } + } // normal attribute - if ( normal ) { - if ( normalPerVertex === false ) { + if ( normal ) { - for ( var i = 0; i < xDimension - 1; i ++ ) { + if ( normalPerVertex === false ) { - for ( var j = 0; j < zDimension - 1; j ++ ) { + for ( let i = 0; i < xDimension - 1; i ++ ) { - var index = i + j * ( xDimension - 1 ); - var xn = normal[ index * 3 + 0 ]; - var yn = normal[ index * 3 + 1 ]; - var zn = normal[ index * 3 + 2 ]; // one normal per quad + for ( let j = 0; j < zDimension - 1; j ++ ) { - normals.push( xn, yn, zn ); - normals.push( xn, yn, zn ); - normals.push( xn, yn, zn ); - normals.push( xn, yn, zn ); - normals.push( xn, yn, zn ); - normals.push( xn, yn, zn ); + const index = i + j * ( xDimension - 1 ); + const xn = normal[ index * 3 + 0 ]; + const yn = normal[ index * 3 + 1 ]; + const zn = normal[ index * 3 + 2 ]; // one normal per quad - } + normals.push( xn, yn, zn ); + normals.push( xn, yn, zn ); + normals.push( xn, yn, zn ); + normals.push( xn, yn, zn ); + normals.push( xn, yn, zn ); + normals.push( xn, yn, zn ); } - normalAttribute = new THREE.Float32BufferAttribute( normals, 3 ); + } - } else { + normalAttribute = new THREE.Float32BufferAttribute( normals, 3 ); - normalAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( normals, 3 ) ); + } else { - } + normalAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( normals, 3 ) ); - } else { + } - normalAttribute = computeNormalAttribute( indices, vertices, creaseAngle ); + } else { - } // build geometry + normalAttribute = computeNormalAttribute( indices, vertices, creaseAngle ); + } // build geometry - var geometry = new THREE.BufferGeometry(); - geometry.setAttribute( 'position', positionAttribute ); - geometry.setAttribute( 'normal', normalAttribute ); - geometry.setAttribute( 'uv', uvAttribute ); - if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); // "solid" influences the material so let's store it for later use - geometry._solid = solid; - geometry._type = 'mesh'; - return geometry; + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute( 'position', positionAttribute ); + geometry.setAttribute( 'normal', normalAttribute ); + geometry.setAttribute( 'uv', uvAttribute ); + if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); // "solid" influences the material so let's store it for later use - } + geometry._solid = solid; + geometry._type = 'mesh'; + return geometry; - function buildExtrusionNode( node ) { + } - var crossSection = [ 1, 1, 1, - 1, - 1, - 1, - 1, 1, 1, 1 ]; - var spine = [ 0, 0, 0, 0, 1, 0 ]; - var scale; - var orientation; - var beginCap = true; - var ccw = true; - var creaseAngle = 0; - var endCap = true; - var solid = true; - var fields = node.fields; + function buildExtrusionNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + let crossSection = [ 1, 1, 1, - 1, - 1, - 1, - 1, 1, 1, 1 ]; + let spine = [ 0, 0, 0, 0, 1, 0 ]; + let scale; + let orientation; + let beginCap = true; + let ccw = true; + let creaseAngle = 0; + let endCap = true; + let solid = true; + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'beginCap': - beginCap = fieldValues[ 0 ]; - break; + switch ( fieldName ) { - case 'ccw': - ccw = fieldValues[ 0 ]; - break; + case 'beginCap': + beginCap = fieldValues[ 0 ]; + break; - case 'convex': - // field not supported - break; + case 'ccw': + ccw = fieldValues[ 0 ]; + break; - case 'creaseAngle': - creaseAngle = fieldValues[ 0 ]; - break; + case 'convex': + // field not supported + break; - case 'crossSection': - crossSection = fieldValues; - break; + case 'creaseAngle': + creaseAngle = fieldValues[ 0 ]; + break; - case 'endCap': - endCap = fieldValues[ 0 ]; - break; + case 'crossSection': + crossSection = fieldValues; + break; - case 'orientation': - orientation = fieldValues; - break; + case 'endCap': + endCap = fieldValues[ 0 ]; + break; - case 'scale': - scale = fieldValues; - break; + case 'orientation': + orientation = fieldValues; + break; - case 'solid': - solid = fieldValues[ 0 ]; - break; + case 'scale': + scale = fieldValues; + break; - case 'spine': - spine = fieldValues; // only extrusion along the Y-axis are supported so far + case 'solid': + solid = fieldValues[ 0 ]; + break; - break; + case 'spine': + spine = fieldValues; // only extrusion along the Y-axis are supported so far - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - var crossSectionClosed = crossSection[ 0 ] === crossSection[ crossSection.length - 2 ] && crossSection[ 1 ] === crossSection[ crossSection.length - 1 ]; // vertices + } - var vertices = []; - var spineVector = new THREE.Vector3(); - var scaling = new THREE.Vector3(); - var axis = new THREE.Vector3(); - var vertex = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); + const crossSectionClosed = crossSection[ 0 ] === crossSection[ crossSection.length - 2 ] && crossSection[ 1 ] === crossSection[ crossSection.length - 1 ]; // vertices - for ( var i = 0, j = 0, o = 0, il = spine.length; i < il; i += 3, j += 2, o += 4 ) { + const vertices = []; + const spineVector = new THREE.Vector3(); + const scaling = new THREE.Vector3(); + const axis = new THREE.Vector3(); + const vertex = new THREE.Vector3(); + const quaternion = new THREE.Quaternion(); - spineVector.fromArray( spine, i ); - scaling.x = scale ? scale[ j + 0 ] : 1; - scaling.y = 1; - scaling.z = scale ? scale[ j + 1 ] : 1; - axis.x = orientation ? orientation[ o + 0 ] : 0; - axis.y = orientation ? orientation[ o + 1 ] : 0; - axis.z = orientation ? orientation[ o + 2 ] : 1; - var angle = orientation ? orientation[ o + 3 ] : 0; + for ( let i = 0, j = 0, o = 0, il = spine.length; i < il; i += 3, j += 2, o += 4 ) { - for ( var k = 0, kl = crossSection.length; k < kl; k += 2 ) { + spineVector.fromArray( spine, i ); + scaling.x = scale ? scale[ j + 0 ] : 1; + scaling.y = 1; + scaling.z = scale ? scale[ j + 1 ] : 1; + axis.x = orientation ? orientation[ o + 0 ] : 0; + axis.y = orientation ? orientation[ o + 1 ] : 0; + axis.z = orientation ? orientation[ o + 2 ] : 1; + const angle = orientation ? orientation[ o + 3 ] : 0; - vertex.x = crossSection[ k + 0 ]; - vertex.y = 0; - vertex.z = crossSection[ k + 1 ]; // scale + for ( let k = 0, kl = crossSection.length; k < kl; k += 2 ) { - vertex.multiply( scaling ); // rotate + vertex.x = crossSection[ k + 0 ]; + vertex.y = 0; + vertex.z = crossSection[ k + 1 ]; // scale - quaternion.setFromAxisAngle( axis, angle ); - vertex.applyQuaternion( quaternion ); // translate + vertex.multiply( scaling ); // rotate - vertex.add( spineVector ); - vertices.push( vertex.x, vertex.y, vertex.z ); + quaternion.setFromAxisAngle( axis, angle ); + vertex.applyQuaternion( quaternion ); // translate - } + vertex.add( spineVector ); + vertices.push( vertex.x, vertex.y, vertex.z ); - } // indices + } + } // indices - var indices = []; - var spineCount = spine.length / 3; - var crossSectionCount = crossSection.length / 2; - for ( var i = 0; i < spineCount - 1; i ++ ) { + const indices = []; + const spineCount = spine.length / 3; + const crossSectionCount = crossSection.length / 2; - for ( var j = 0; j < crossSectionCount - 1; j ++ ) { + for ( let i = 0; i < spineCount - 1; i ++ ) { - var a = j + i * crossSectionCount; - var b = j + 1 + i * crossSectionCount; - var c = j + ( i + 1 ) * crossSectionCount; - var d = j + 1 + ( i + 1 ) * crossSectionCount; + for ( let j = 0; j < crossSectionCount - 1; j ++ ) { - if ( j === crossSectionCount - 2 && crossSectionClosed === true ) { + const a = j + i * crossSectionCount; + let b = j + 1 + i * crossSectionCount; + const c = j + ( i + 1 ) * crossSectionCount; + let d = j + 1 + ( i + 1 ) * crossSectionCount; - b = i * crossSectionCount; - d = ( i + 1 ) * crossSectionCount; + if ( j === crossSectionCount - 2 && crossSectionClosed === true ) { - } + b = i * crossSectionCount; + d = ( i + 1 ) * crossSectionCount; - if ( ccw === true ) { + } - indices.push( a, b, c ); - indices.push( c, b, d ); + if ( ccw === true ) { - } else { + indices.push( a, b, c ); + indices.push( c, b, d ); - indices.push( a, c, b ); - indices.push( c, d, b ); + } else { - } + indices.push( a, c, b ); + indices.push( c, d, b ); } - } // triangulate cap + } + } // triangulate cap - if ( beginCap === true || endCap === true ) { - var contour = []; + if ( beginCap === true || endCap === true ) { - for ( var i = 0, l = crossSection.length; i < l; i += 2 ) { + const contour = []; - contour.push( new THREE.Vector2( crossSection[ i ], crossSection[ i + 1 ] ) ); + for ( let i = 0, l = crossSection.length; i < l; i += 2 ) { - } + contour.push( new THREE.Vector2( crossSection[ i ], crossSection[ i + 1 ] ) ); - var faces = THREE.ShapeUtils.triangulateShape( contour, [] ); - var capIndices = []; + } - for ( var i = 0, l = faces.length; i < l; i ++ ) { + const faces = THREE.ShapeUtils.triangulateShape( contour, [] ); + const capIndices = []; - var face = faces[ i ]; - capIndices.push( face[ 0 ], face[ 1 ], face[ 2 ] ); + for ( let i = 0, l = faces.length; i < l; i ++ ) { - } // begin cap + const face = faces[ i ]; + capIndices.push( face[ 0 ], face[ 1 ], face[ 2 ] ); + } // begin cap - if ( beginCap === true ) { - for ( var i = 0, l = capIndices.length; i < l; i += 3 ) { + if ( beginCap === true ) { - if ( ccw === true ) { + for ( let i = 0, l = capIndices.length; i < l; i += 3 ) { - indices.push( capIndices[ i + 0 ], capIndices[ i + 1 ], capIndices[ i + 2 ] ); + if ( ccw === true ) { - } else { + indices.push( capIndices[ i + 0 ], capIndices[ i + 1 ], capIndices[ i + 2 ] ); - indices.push( capIndices[ i + 0 ], capIndices[ i + 2 ], capIndices[ i + 1 ] ); + } else { - } + indices.push( capIndices[ i + 0 ], capIndices[ i + 2 ], capIndices[ i + 1 ] ); } - } // end cap + } + } // end cap - if ( endCap === true ) { - var indexOffset = crossSectionCount * ( spineCount - 1 ); // references to the first vertex of the last cross section + if ( endCap === true ) { - for ( var i = 0, l = capIndices.length; i < l; i += 3 ) { + const indexOffset = crossSectionCount * ( spineCount - 1 ); // references to the first vertex of the last cross section - if ( ccw === true ) { + for ( let i = 0, l = capIndices.length; i < l; i += 3 ) { - indices.push( indexOffset + capIndices[ i + 0 ], indexOffset + capIndices[ i + 2 ], indexOffset + capIndices[ i + 1 ] ); + if ( ccw === true ) { - } else { + indices.push( indexOffset + capIndices[ i + 0 ], indexOffset + capIndices[ i + 2 ], indexOffset + capIndices[ i + 1 ] ); - indices.push( indexOffset + capIndices[ i + 0 ], indexOffset + capIndices[ i + 1 ], indexOffset + capIndices[ i + 2 ] ); + } else { - } + indices.push( indexOffset + capIndices[ i + 0 ], indexOffset + capIndices[ i + 1 ], indexOffset + capIndices[ i + 2 ] ); } @@ -2492,517 +2487,524 @@ } - var positionAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( vertices, 3 ) ); - var normalAttribute = computeNormalAttribute( indices, vertices, creaseAngle ); - var geometry = new THREE.BufferGeometry(); - geometry.setAttribute( 'position', positionAttribute ); - geometry.setAttribute( 'normal', normalAttribute ); // no uvs yet - // "solid" influences the material so let's store it for later use + } - geometry._solid = solid; - geometry._type = 'mesh'; - return geometry; + const positionAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( vertices, 3 ) ); + const normalAttribute = computeNormalAttribute( indices, vertices, creaseAngle ); + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute( 'position', positionAttribute ); + geometry.setAttribute( 'normal', normalAttribute ); // no uvs yet + // "solid" influences the material so let's store it for later use - } // helper functions + geometry._solid = solid; + geometry._type = 'mesh'; + return geometry; + } // helper functions - function resolveUSE( identifier ) { - var node = nodeMap[ identifier ]; - var build = getNode( node ); // because the same 3D objects can have different transformations, it's necessary to clone them. - // materials can be influenced by the geometry (e.g. vertex normals). cloning is necessary to avoid - // any side effects + function resolveUSE( identifier ) { - return build.isObject3D || build.isMaterial ? build.clone() : build; + const node = nodeMap[ identifier ]; + const build = getNode( node ); // because the same 3D objects can have different transformations, it's necessary to clone them. + // materials can be influenced by the geometry (e.g. vertex normals). cloning is necessary to avoid + // any side effects - } + return build.isObject3D || build.isMaterial ? build.clone() : build; - function parseFieldChildren( children, owner ) { + } - for ( var i = 0, l = children.length; i < l; i ++ ) { + function parseFieldChildren( children, owner ) { - var object = getNode( children[ i ] ); - if ( object instanceof THREE.Object3D ) owner.add( object ); + for ( let i = 0, l = children.length; i < l; i ++ ) { - } + const object = getNode( children[ i ] ); + if ( object instanceof THREE.Object3D ) owner.add( object ); } - function triangulateFaceIndex( index, ccw ) { + } - var indices = []; // since face defintions can have more than three vertices, it's necessary to - // perform a simple triangulation + function triangulateFaceIndex( index, ccw ) { - var start = 0; + const indices = []; // since face defintions can have more than three vertices, it's necessary to + // perform a simple triangulation - for ( var i = 0, l = index.length; i < l; i ++ ) { + let start = 0; - var i1 = index[ start ]; - var i2 = index[ i + ( ccw ? 1 : 2 ) ]; - var i3 = index[ i + ( ccw ? 2 : 1 ) ]; - indices.push( i1, i2, i3 ); // an index of -1 indicates that the current face has ended and the next one begins + for ( let i = 0, l = index.length; i < l; i ++ ) { - if ( index[ i + 3 ] === - 1 || i + 3 >= l ) { + const i1 = index[ start ]; + const i2 = index[ i + ( ccw ? 1 : 2 ) ]; + const i3 = index[ i + ( ccw ? 2 : 1 ) ]; + indices.push( i1, i2, i3 ); // an index of -1 indicates that the current face has ended and the next one begins - i += 3; - start = i + 1; + if ( index[ i + 3 ] === - 1 || i + 3 >= l ) { - } + i += 3; + start = i + 1; } - return indices; - } - function triangulateFaceData( data, index ) { + return indices; - var triangulatedData = []; - var start = 0; + } - for ( var i = 0, l = index.length; i < l; i ++ ) { + function triangulateFaceData( data, index ) { - var stride = start * 3; - var x = data[ stride ]; - var y = data[ stride + 1 ]; - var z = data[ stride + 2 ]; - triangulatedData.push( x, y, z ); // an index of -1 indicates that the current face has ended and the next one begins + const triangulatedData = []; + let start = 0; - if ( index[ i + 3 ] === - 1 || i + 3 >= l ) { + for ( let i = 0, l = index.length; i < l; i ++ ) { - i += 3; - start ++; + const stride = start * 3; + const x = data[ stride ]; + const y = data[ stride + 1 ]; + const z = data[ stride + 2 ]; + triangulatedData.push( x, y, z ); // an index of -1 indicates that the current face has ended and the next one begins - } + if ( index[ i + 3 ] === - 1 || i + 3 >= l ) { - } + i += 3; + start ++; - return triangulatedData; + } } - function flattenData( data, index ) { + return triangulatedData; - var flattenData = []; + } - for ( var i = 0, l = index.length; i < l; i ++ ) { + function flattenData( data, index ) { - var i1 = index[ i ]; - var stride = i1 * 3; - var x = data[ stride ]; - var y = data[ stride + 1 ]; - var z = data[ stride + 2 ]; - flattenData.push( x, y, z ); + const flattenData = []; - } + for ( let i = 0, l = index.length; i < l; i ++ ) { - return flattenData; + const i1 = index[ i ]; + const stride = i1 * 3; + const x = data[ stride ]; + const y = data[ stride + 1 ]; + const z = data[ stride + 2 ]; + flattenData.push( x, y, z ); } - function expandLineIndex( index ) { + return flattenData; - var indices = []; + } - for ( var i = 0, l = index.length; i < l; i ++ ) { + function expandLineIndex( index ) { - var i1 = index[ i ]; - var i2 = index[ i + 1 ]; - indices.push( i1, i2 ); // an index of -1 indicates that the current line has ended and the next one begins + const indices = []; - if ( index[ i + 2 ] === - 1 || i + 2 >= l ) { + for ( let i = 0, l = index.length; i < l; i ++ ) { - i += 2; + const i1 = index[ i ]; + const i2 = index[ i + 1 ]; + indices.push( i1, i2 ); // an index of -1 indicates that the current line has ended and the next one begins - } + if ( index[ i + 2 ] === - 1 || i + 2 >= l ) { - } + i += 2; - return indices; + } } - function expandLineData( data, index ) { + return indices; - var triangulatedData = []; - var start = 0; + } - for ( var i = 0, l = index.length; i < l; i ++ ) { + function expandLineData( data, index ) { - var stride = start * 3; - var x = data[ stride ]; - var y = data[ stride + 1 ]; - var z = data[ stride + 2 ]; - triangulatedData.push( x, y, z ); // an index of -1 indicates that the current line has ended and the next one begins + const triangulatedData = []; + let start = 0; - if ( index[ i + 2 ] === - 1 || i + 2 >= l ) { + for ( let i = 0, l = index.length; i < l; i ++ ) { - i += 2; - start ++; + const stride = start * 3; + const x = data[ stride ]; + const y = data[ stride + 1 ]; + const z = data[ stride + 2 ]; + triangulatedData.push( x, y, z ); // an index of -1 indicates that the current line has ended and the next one begins - } + if ( index[ i + 2 ] === - 1 || i + 2 >= l ) { - } + i += 2; + start ++; - return triangulatedData; + } } - var vA = new THREE.Vector3(); - var vB = new THREE.Vector3(); - var vC = new THREE.Vector3(); - var uvA = new THREE.Vector2(); - var uvB = new THREE.Vector2(); - var uvC = new THREE.Vector2(); + return triangulatedData; - function computeAttributeFromIndexedData( coordIndex, index, data, itemSize ) { + } - var array = []; // we use the coordIndex.length as delimiter since normalIndex must contain at least as many indices + const vA = new THREE.Vector3(); + const vB = new THREE.Vector3(); + const vC = new THREE.Vector3(); + const uvA = new THREE.Vector2(); + const uvB = new THREE.Vector2(); + const uvC = new THREE.Vector2(); - for ( var i = 0, l = coordIndex.length; i < l; i += 3 ) { + function computeAttributeFromIndexedData( coordIndex, index, data, itemSize ) { - var a = index[ i ]; - var b = index[ i + 1 ]; - var c = index[ i + 2 ]; + const array = []; // we use the coordIndex.length as delimiter since normalIndex must contain at least as many indices - if ( itemSize === 2 ) { + for ( let i = 0, l = coordIndex.length; i < l; i += 3 ) { - uvA.fromArray( data, a * itemSize ); - uvB.fromArray( data, b * itemSize ); - uvC.fromArray( data, c * itemSize ); - array.push( uvA.x, uvA.y ); - array.push( uvB.x, uvB.y ); - array.push( uvC.x, uvC.y ); + const a = index[ i ]; + const b = index[ i + 1 ]; + const c = index[ i + 2 ]; - } else { + if ( itemSize === 2 ) { - vA.fromArray( data, a * itemSize ); - vB.fromArray( data, b * itemSize ); - vC.fromArray( data, c * itemSize ); - array.push( vA.x, vA.y, vA.z ); - array.push( vB.x, vB.y, vB.z ); - array.push( vC.x, vC.y, vC.z ); + uvA.fromArray( data, a * itemSize ); + uvB.fromArray( data, b * itemSize ); + uvC.fromArray( data, c * itemSize ); + array.push( uvA.x, uvA.y ); + array.push( uvB.x, uvB.y ); + array.push( uvC.x, uvC.y ); - } + } else { - } + vA.fromArray( data, a * itemSize ); + vB.fromArray( data, b * itemSize ); + vC.fromArray( data, c * itemSize ); + array.push( vA.x, vA.y, vA.z ); + array.push( vB.x, vB.y, vB.z ); + array.push( vC.x, vC.y, vC.z ); - return new THREE.Float32BufferAttribute( array, itemSize ); + } } - function computeAttributeFromFaceData( index, faceData ) { + return new THREE.Float32BufferAttribute( array, itemSize ); - var array = []; + } - for ( var i = 0, j = 0, l = index.length; i < l; i += 3, j ++ ) { + function computeAttributeFromFaceData( index, faceData ) { - vA.fromArray( faceData, j * 3 ); - array.push( vA.x, vA.y, vA.z ); - array.push( vA.x, vA.y, vA.z ); - array.push( vA.x, vA.y, vA.z ); + const array = []; - } + for ( let i = 0, j = 0, l = index.length; i < l; i += 3, j ++ ) { - return new THREE.Float32BufferAttribute( array, 3 ); + vA.fromArray( faceData, j * 3 ); + array.push( vA.x, vA.y, vA.z ); + array.push( vA.x, vA.y, vA.z ); + array.push( vA.x, vA.y, vA.z ); } - function computeAttributeFromLineData( index, lineData ) { + return new THREE.Float32BufferAttribute( array, 3 ); - var array = []; + } - for ( var i = 0, j = 0, l = index.length; i < l; i += 2, j ++ ) { + function computeAttributeFromLineData( index, lineData ) { - vA.fromArray( lineData, j * 3 ); - array.push( vA.x, vA.y, vA.z ); - array.push( vA.x, vA.y, vA.z ); + const array = []; - } + for ( let i = 0, j = 0, l = index.length; i < l; i += 2, j ++ ) { - return new THREE.Float32BufferAttribute( array, 3 ); + vA.fromArray( lineData, j * 3 ); + array.push( vA.x, vA.y, vA.z ); + array.push( vA.x, vA.y, vA.z ); } - function toNonIndexedAttribute( indices, attribute ) { + return new THREE.Float32BufferAttribute( array, 3 ); - var array = attribute.array; - var itemSize = attribute.itemSize; - var array2 = new array.constructor( indices.length * itemSize ); - var index = 0, - index2 = 0; + } - for ( var i = 0, l = indices.length; i < l; i ++ ) { + function toNonIndexedAttribute( indices, attribute ) { - index = indices[ i ] * itemSize; + const array = attribute.array; + const itemSize = attribute.itemSize; + const array2 = new array.constructor( indices.length * itemSize ); + let index = 0, + index2 = 0; - for ( var j = 0; j < itemSize; j ++ ) { + for ( let i = 0, l = indices.length; i < l; i ++ ) { - array2[ index2 ++ ] = array[ index ++ ]; + index = indices[ i ] * itemSize; - } + for ( let j = 0; j < itemSize; j ++ ) { - } + array2[ index2 ++ ] = array[ index ++ ]; - return new THREE.Float32BufferAttribute( array2, itemSize ); + } } - var ab = new THREE.Vector3(); - var cb = new THREE.Vector3(); - - function computeNormalAttribute( index, coord, creaseAngle ) { - - var faces = []; - var vertexNormals = {}; // prepare face and raw vertex normals - - for ( var i = 0, l = index.length; i < l; i += 3 ) { - - var a = index[ i ]; - var b = index[ i + 1 ]; - var c = index[ i + 2 ]; - var face = new Face( a, b, c ); - vA.fromArray( coord, a * 3 ); - vB.fromArray( coord, b * 3 ); - vC.fromArray( coord, c * 3 ); - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); - cb.normalize(); - face.normal.copy( cb ); - if ( vertexNormals[ a ] === undefined ) vertexNormals[ a ] = []; - if ( vertexNormals[ b ] === undefined ) vertexNormals[ b ] = []; - if ( vertexNormals[ c ] === undefined ) vertexNormals[ c ] = []; - vertexNormals[ a ].push( face.normal ); - vertexNormals[ b ].push( face.normal ); - vertexNormals[ c ].push( face.normal ); - faces.push( face ); - - } // compute vertex normals and build final geometry - - - var normals = []; - - for ( var i = 0, l = faces.length; i < l; i ++ ) { - - var face = faces[ i ]; - var nA = weightedNormal( vertexNormals[ face.a ], face.normal, creaseAngle ); - var nB = weightedNormal( vertexNormals[ face.b ], face.normal, creaseAngle ); - var nC = weightedNormal( vertexNormals[ face.c ], face.normal, creaseAngle ); - vA.fromArray( coord, face.a * 3 ); - vB.fromArray( coord, face.b * 3 ); - vC.fromArray( coord, face.c * 3 ); - normals.push( nA.x, nA.y, nA.z ); - normals.push( nB.x, nB.y, nB.z ); - normals.push( nC.x, nC.y, nC.z ); + return new THREE.Float32BufferAttribute( array2, itemSize ); - } + } - return new THREE.Float32BufferAttribute( normals, 3 ); + const ab = new THREE.Vector3(); + const cb = new THREE.Vector3(); + + function computeNormalAttribute( index, coord, creaseAngle ) { + + const faces = []; + const vertexNormals = {}; // prepare face and raw vertex normals + + for ( let i = 0, l = index.length; i < l; i += 3 ) { + + const a = index[ i ]; + const b = index[ i + 1 ]; + const c = index[ i + 2 ]; + const face = new Face( a, b, c ); + vA.fromArray( coord, a * 3 ); + vB.fromArray( coord, b * 3 ); + vC.fromArray( coord, c * 3 ); + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); + cb.normalize(); + face.normal.copy( cb ); + if ( vertexNormals[ a ] === undefined ) vertexNormals[ a ] = []; + if ( vertexNormals[ b ] === undefined ) vertexNormals[ b ] = []; + if ( vertexNormals[ c ] === undefined ) vertexNormals[ c ] = []; + vertexNormals[ a ].push( face.normal ); + vertexNormals[ b ].push( face.normal ); + vertexNormals[ c ].push( face.normal ); + faces.push( face ); + + } // compute vertex normals and build final geometry + + + const normals = []; + + for ( let i = 0, l = faces.length; i < l; i ++ ) { + + const face = faces[ i ]; + const nA = weightedNormal( vertexNormals[ face.a ], face.normal, creaseAngle ); + const nB = weightedNormal( vertexNormals[ face.b ], face.normal, creaseAngle ); + const nC = weightedNormal( vertexNormals[ face.c ], face.normal, creaseAngle ); + vA.fromArray( coord, face.a * 3 ); + vB.fromArray( coord, face.b * 3 ); + vC.fromArray( coord, face.c * 3 ); + normals.push( nA.x, nA.y, nA.z ); + normals.push( nB.x, nB.y, nB.z ); + normals.push( nC.x, nC.y, nC.z ); } - function weightedNormal( normals, vector, creaseAngle ) { + return new THREE.Float32BufferAttribute( normals, 3 ); - var normal = new THREE.Vector3(); + } - if ( creaseAngle === 0 ) { + function weightedNormal( normals, vector, creaseAngle ) { - normal.copy( vector ); + const normal = new THREE.Vector3(); - } else { + if ( creaseAngle === 0 ) { - for ( var i = 0, l = normals.length; i < l; i ++ ) { + normal.copy( vector ); - if ( normals[ i ].angleTo( vector ) < creaseAngle ) { + } else { - normal.add( normals[ i ] ); + for ( let i = 0, l = normals.length; i < l; i ++ ) { - } + if ( normals[ i ].angleTo( vector ) < creaseAngle ) { + + normal.add( normals[ i ] ); } } - return normal.normalize(); - } - function toColorArray( colors ) { + return normal.normalize(); - var array = []; + } - for ( var i = 0, l = colors.length; i < l; i += 3 ) { + function toColorArray( colors ) { - array.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + const array = []; - } + for ( let i = 0, l = colors.length; i < l; i += 3 ) { - return array; + array.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); } - /** - * Vertically paints the faces interpolating between the - * specified colors at the specified angels. This is used for the Background - * node, but could be applied to other nodes with multiple faces as well. - * - * When used with the Background node, default is directionIsDown is true if - * interpolating the skyColor down from the Zenith. When interpolationg up from - * the Nadir i.e. interpolating the groundColor, the directionIsDown is false. - * - * The first angle is never specified, it is the Zenith (0 rad). Angles are specified - * in radians. The geometry is thought a sphere, but could be anything. The color interpolation - * is linear along the Y axis in any case. - * - * You must specify one more color than you have angles at the beginning of the colors array. - * This is the color of the Zenith (the top of the shape). - * - * @param {BufferGeometry} geometry - * @param {number} radius - * @param {array} angles - * @param {array} colors - * @param {boolean} topDown - Whether to work top down or bottom up. - */ - - - function paintFaces( geometry, radius, angles, colors, topDown ) { - - // compute threshold values - var thresholds = []; - var startAngle = topDown === true ? 0 : Math.PI; - - for ( var i = 0, l = colors.length; i < l; i ++ ) { - - var angle = i === 0 ? 0 : angles[ i - 1 ]; - angle = topDown === true ? angle : startAngle - angle; - var point = new THREE.Vector3(); - point.setFromSphericalCoords( radius, angle, 0 ); - thresholds.push( point ); - - } // generate vertex colors - - - var indices = geometry.index; - var positionAttribute = geometry.attributes.position; - var colorAttribute = new THREE.BufferAttribute( new Float32Array( geometry.attributes.position.count * 3 ), 3 ); - var position = new THREE.Vector3(); - var color = new THREE.Color(); - - for ( var i = 0; i < indices.count; i ++ ) { - - var index = indices.getX( i ); - position.fromBufferAttribute( positionAttribute, index ); - var thresholdIndexA, thresholdIndexB; - var t = 1; - - for ( var j = 1; j < thresholds.length; j ++ ) { - - thresholdIndexA = j - 1; - thresholdIndexB = j; - var thresholdA = thresholds[ thresholdIndexA ]; - var thresholdB = thresholds[ thresholdIndexB ]; - - if ( topDown === true ) { - - // interpolation for sky color - if ( position.y <= thresholdA.y && position.y > thresholdB.y ) { - - t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y ); - break; - } + return array; - } else { + } + /** + * Vertically paints the faces interpolating between the + * specified colors at the specified angels. This is used for the Background + * node, but could be applied to other nodes with multiple faces as well. + * + * When used with the Background node, default is directionIsDown is true if + * interpolating the skyColor down from the Zenith. When interpolationg up from + * the Nadir i.e. interpolating the groundColor, the directionIsDown is false. + * + * The first angle is never specified, it is the Zenith (0 rad). Angles are specified + * in radians. The geometry is thought a sphere, but could be anything. The color interpolation + * is linear along the Y axis in any case. + * + * You must specify one more color than you have angles at the beginning of the colors array. + * This is the color of the Zenith (the top of the shape). + * + * @param {BufferGeometry} geometry + * @param {number} radius + * @param {array} angles + * @param {array} colors + * @param {boolean} topDown - Whether to work top down or bottom up. + */ - // interpolation for ground color - if ( position.y >= thresholdA.y && position.y < thresholdB.y ) { - t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y ); - break; + function paintFaces( geometry, radius, angles, colors, topDown ) { - } + // compute threshold values + const thresholds = []; + const startAngle = topDown === true ? 0 : Math.PI; + + for ( let i = 0, l = colors.length; i < l; i ++ ) { + + let angle = i === 0 ? 0 : angles[ i - 1 ]; + angle = topDown === true ? angle : startAngle - angle; + const point = new THREE.Vector3(); + point.setFromSphericalCoords( radius, angle, 0 ); + thresholds.push( point ); + + } // generate vertex colors + + + const indices = geometry.index; + const positionAttribute = geometry.attributes.position; + const colorAttribute = new THREE.BufferAttribute( new Float32Array( geometry.attributes.position.count * 3 ), 3 ); + const position = new THREE.Vector3(); + const color = new THREE.Color(); + + for ( let i = 0; i < indices.count; i ++ ) { + + const index = indices.getX( i ); + position.fromBufferAttribute( positionAttribute, index ); + let thresholdIndexA, thresholdIndexB; + let t = 1; + + for ( let j = 1; j < thresholds.length; j ++ ) { + + thresholdIndexA = j - 1; + thresholdIndexB = j; + const thresholdA = thresholds[ thresholdIndexA ]; + const thresholdB = thresholds[ thresholdIndexB ]; + + if ( topDown === true ) { + + // interpolation for sky color + if ( position.y <= thresholdA.y && position.y > thresholdB.y ) { + + t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y ); + break; } - } + } else { + + // interpolation for ground color + if ( position.y >= thresholdA.y && position.y < thresholdB.y ) { + + t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y ); + break; + + } - var colorA = colors[ thresholdIndexA ]; - var colorB = colors[ thresholdIndexB ]; - color.copy( colorA ).lerp( colorB, t ); - colorAttribute.setXYZ( index, color.r, color.g, color.b ); + } } - geometry.setAttribute( 'color', colorAttribute ); + const colorA = colors[ thresholdIndexA ]; + const colorB = colors[ thresholdIndexB ]; + color.copy( colorA ).lerp( colorB, t ); + colorAttribute.setXYZ( index, color.r, color.g, color.b ); - } // + } + geometry.setAttribute( 'color', colorAttribute ); - var textureLoader = new THREE.TextureLoader( this.manager ); - textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin ); // check version (only 2.0 is supported) + } // - if ( data.indexOf( '#VRML V2.0' ) === - 1 ) { - throw Error( 'THREE.VRMLLexer: Version of VRML asset not supported.' ); + const textureLoader = new THREE.TextureLoader( this.manager ); + textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin ); // check version (only 2.0 is supported) - } // create JSON representing the tree structure of the VRML asset + if ( data.indexOf( '#VRML V2.0' ) === - 1 ) { + throw Error( 'THREE.VRMLLexer: Version of VRML asset not supported.' ); - var tree = generateVRMLTree( data ); // parse the tree structure to a three.js scene + } // create JSON representing the tree structure of the VRML asset - var scene = parseTree( tree ); - return scene; - } - } ); + const tree = generateVRMLTree( data ); // parse the tree structure to a three.js scene + + const scene = parseTree( tree ); + return scene; + + } + + } - function VRMLLexer( tokens ) { + class VRMLLexer { + + constructor( tokens ) { this.lexer = new chevrotain.Lexer( tokens ); // eslint-disable-line no-undef } - VRMLLexer.prototype = { - constructor: VRMLLexer, - lex: function ( inputText ) { + lex( inputText ) { - var lexingResult = this.lexer.tokenize( inputText ); + const lexingResult = this.lexer.tokenize( inputText ); - if ( lexingResult.errors.length > 0 ) { + if ( lexingResult.errors.length > 0 ) { - console.error( lexingResult.errors ); - throw Error( 'THREE.VRMLLexer: Lexing errors detected.' ); + console.error( lexingResult.errors ); + throw Error( 'THREE.VRMLLexer: Lexing errors detected.' ); - } + } - return lexingResult; + return lexingResult; - } - }; - - function VRMLParser( tokenVocabulary ) { - - chevrotain.Parser.call( this, tokenVocabulary ); // eslint-disable-line no-undef - - var $ = this; - var Version = tokenVocabulary[ 'Version' ]; - var LCurly = tokenVocabulary[ 'LCurly' ]; - var RCurly = tokenVocabulary[ 'RCurly' ]; - var LSquare = tokenVocabulary[ 'LSquare' ]; - var RSquare = tokenVocabulary[ 'RSquare' ]; - var Identifier = tokenVocabulary[ 'Identifier' ]; - var RouteIdentifier = tokenVocabulary[ 'RouteIdentifier' ]; - var StringLiteral = tokenVocabulary[ 'StringLiteral' ]; - var HexLiteral = tokenVocabulary[ 'HexLiteral' ]; - var NumberLiteral = tokenVocabulary[ 'NumberLiteral' ]; - var TrueLiteral = tokenVocabulary[ 'TrueLiteral' ]; - var FalseLiteral = tokenVocabulary[ 'FalseLiteral' ]; - var NullLiteral = tokenVocabulary[ 'NullLiteral' ]; - var DEF = tokenVocabulary[ 'DEF' ]; - var USE = tokenVocabulary[ 'USE' ]; - var ROUTE = tokenVocabulary[ 'ROUTE' ]; - var TO = tokenVocabulary[ 'TO' ]; - var NodeName = tokenVocabulary[ 'NodeName' ]; + } + + } + + const ChevrotainParser = chevrotain.Parser; // eslint-disable-line no-undef + + class VRMLParser extends ChevrotainParser { + + constructor( tokenVocabulary ) { + + super( tokenVocabulary ); + const $ = this; + const Version = tokenVocabulary[ 'Version' ]; + const LCurly = tokenVocabulary[ 'LCurly' ]; + const RCurly = tokenVocabulary[ 'RCurly' ]; + const LSquare = tokenVocabulary[ 'LSquare' ]; + const RSquare = tokenVocabulary[ 'RSquare' ]; + const Identifier = tokenVocabulary[ 'Identifier' ]; + const RouteIdentifier = tokenVocabulary[ 'RouteIdentifier' ]; + const StringLiteral = tokenVocabulary[ 'StringLiteral' ]; + const HexLiteral = tokenVocabulary[ 'HexLiteral' ]; + const NumberLiteral = tokenVocabulary[ 'NumberLiteral' ]; + const TrueLiteral = tokenVocabulary[ 'TrueLiteral' ]; + const FalseLiteral = tokenVocabulary[ 'FalseLiteral' ]; + const NullLiteral = tokenVocabulary[ 'NullLiteral' ]; + const DEF = tokenVocabulary[ 'DEF' ]; + const USE = tokenVocabulary[ 'USE' ]; + const ROUTE = tokenVocabulary[ 'ROUTE' ]; + const TO = tokenVocabulary[ 'TO' ]; + const NodeName = tokenVocabulary[ 'NodeName' ]; $.RULE( 'vrml', function () { $.SUBRULE( $.version ); @@ -3210,11 +3212,11 @@ } - VRMLParser.prototype = Object.create( chevrotain.Parser.prototype ); // eslint-disable-line no-undef + } - VRMLParser.prototype.constructor = VRMLParser; + class Face { - function Face( a, b, c ) { + constructor( a, b, c ) { this.a = a; this.b = b; @@ -3223,15 +3225,14 @@ } - var TEXTURE_TYPE = { - INTENSITY: 1, - INTENSITY_ALPHA: 2, - RGB: 3, - RGBA: 4 - }; - return VRMLLoader; + } - }(); + const TEXTURE_TYPE = { + INTENSITY: 1, + INTENSITY_ALPHA: 2, + RGB: 3, + RGBA: 4 + }; THREE.VRMLLoader = VRMLLoader; diff --git a/examples/js/loaders/VRMLoader.js b/examples/js/loaders/VRMLoader.js index d00599532cc878..107a5cd6f05a2c 100644 --- a/examples/js/loaders/VRMLoader.js +++ b/examples/js/loaders/VRMLoader.js @@ -4,9 +4,9 @@ // VRM is based on glTF 2.0 and VRM extension is defined // in top-level json.extensions.VRM - var VRMLoader = function () { + class VRMLoader extends THREE.Loader { - function VRMLoader( manager ) { + constructor( manager ) { if ( THREE.GLTFLoader === undefined ) { @@ -14,60 +14,58 @@ } - THREE.Loader.call( this, manager ); - this.gltfLoader = new THREE.GLTFLoader( this.manager ); + super( manager ); + this.gltfLoader = new THREE.GLTFLoader( manager ); } - VRMLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { - constructor: VRMLoader, - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; - this.gltfLoader.load( url, function ( gltf ) { + const scope = this; + this.gltfLoader.load( url, function ( gltf ) { - try { + try { - scope.parse( gltf, onLoad ); + scope.parse( gltf, onLoad ); - } catch ( e ) { + } catch ( e ) { - if ( onError ) { + if ( onError ) { - onError( e ); + onError( e ); - } else { + } else { - console.error( e ); + console.error( e ); - } + } - scope.manager.itemError( url ); + scope.manager.itemError( url ); - } + } + + }, onProgress, onError ); + + } - }, onProgress, onError ); + setDRACOLoader( dracoLoader ) { - }, - setDRACOLoader: function ( dracoLoader ) { + this.gltfLoader.setDRACOLoader( dracoLoader ); + return this; - this.gltfLoader.setDRACOLoader( dracoLoader ); - return this; + } - }, - parse: function ( gltf, onLoad ) { + parse( gltf, onLoad ) { - // var gltfParser = gltf.parser; - // var gltfExtensions = gltf.userData.gltfExtensions || {}; - // var vrmExtension = gltfExtensions.VRM || {}; - // handle VRM Extension here - onLoad( gltf ); + // const gltfParser = gltf.parser; + // const gltfExtensions = gltf.userData.gltfExtensions || {}; + // const vrmExtension = gltfExtensions.VRM || {}; + // handle VRM Extension here + onLoad( gltf ); - } - } ); - return VRMLoader; + } - }(); + } THREE.VRMLoader = VRMLoader; diff --git a/examples/jsm/loaders/3MFLoader.js b/examples/jsm/loaders/3MFLoader.js index 7fda0036e62ae8..a6c517e26427bc 100644 --- a/examples/jsm/loaders/3MFLoader.js +++ b/examples/jsm/loaders/3MFLoader.js @@ -40,22 +40,20 @@ import * as fflate from '../libs/fflate.module.min.js'; * - Metallic Display Properties (PBR) */ -var ThreeMFLoader = function ( manager ) { +class ThreeMFLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { - this.availableExtensions = []; + super( manager ); -}; + this.availableExtensions = []; -ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: ThreeMFLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; - var loader = new FileLoader( scope.manager ); + const scope = this; + const loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( scope.requestHeader ); @@ -84,31 +82,30 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } - parse: function ( data ) { + parse( data ) { - var scope = this; - var textureLoader = new TextureLoader( this.manager ); + const scope = this; + const textureLoader = new TextureLoader( this.manager ); function loadDocument( data ) { - var zip = null; - var file = null; + let zip = null; + let file = null; - var relsName; - var modelRelsName; - var modelPartNames = []; - var printTicketPartNames = []; - var texturesPartNames = []; - var otherPartNames = []; + let relsName; + let modelRelsName; + const modelPartNames = []; + const printTicketPartNames = []; + const texturesPartNames = []; + const otherPartNames = []; - var rels; - var modelRels; - var modelParts = {}; - var printTicketParts = {}; - var texturesParts = {}; - var otherParts = {}; + let modelRels; + const modelParts = {}; + const printTicketParts = {}; + const texturesParts = {}; + const otherParts = {}; try { @@ -157,29 +154,29 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // - var relsView = zip[ relsName ]; - var relsFileText = LoaderUtils.decodeText( relsView ); - rels = parseRelsXml( relsFileText ); + const relsView = zip[ relsName ]; + const relsFileText = LoaderUtils.decodeText( relsView ); + const rels = parseRelsXml( relsFileText ); // if ( modelRelsName ) { - var relsView = zip[ modelRelsName ]; - var relsFileText = LoaderUtils.decodeText( relsView ); + const relsView = zip[ modelRelsName ]; + const relsFileText = LoaderUtils.decodeText( relsView ); modelRels = parseRelsXml( relsFileText ); } // - for ( var i = 0; i < modelPartNames.length; i ++ ) { + for ( let i = 0; i < modelPartNames.length; i ++ ) { - var modelPart = modelPartNames[ i ]; - var view = zip[ modelPart ]; + const modelPart = modelPartNames[ i ]; + const view = zip[ modelPart ]; - var fileText = LoaderUtils.decodeText( view ); - var xmlData = new DOMParser().parseFromString( fileText, 'application/xml' ); + const fileText = LoaderUtils.decodeText( view ); + const xmlData = new DOMParser().parseFromString( fileText, 'application/xml' ); if ( xmlData.documentElement.nodeName.toLowerCase() !== 'model' ) { @@ -187,12 +184,12 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var modelNode = xmlData.querySelector( 'model' ); - var extensions = {}; + const modelNode = xmlData.querySelector( 'model' ); + const extensions = {}; - for ( var i = 0; i < modelNode.attributes.length; i ++ ) { + for ( let i = 0; i < modelNode.attributes.length; i ++ ) { - var attr = modelNode.attributes[ i ]; + const attr = modelNode.attributes[ i ]; if ( attr.name.match( /^xmlns:(.+)$/ ) ) { extensions[ attr.value ] = RegExp.$1; @@ -201,7 +198,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var modelData = parseModelNode( modelNode ); + const modelData = parseModelNode( modelNode ); modelData[ 'xml' ] = modelNode; if ( 0 < Object.keys( extensions ).length ) { @@ -216,9 +213,9 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // - for ( var i = 0; i < texturesPartNames.length; i ++ ) { + for ( let i = 0; i < texturesPartNames.length; i ++ ) { - var texturesPartName = texturesPartNames[ i ]; + const texturesPartName = texturesPartNames[ i ]; texturesParts[ texturesPartName ] = zip[ texturesPartName ].buffer; } @@ -236,17 +233,17 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseRelsXml( relsFileText ) { - var relationships = []; + const relationships = []; - var relsXmlData = new DOMParser().parseFromString( relsFileText, 'application/xml' ); + const relsXmlData = new DOMParser().parseFromString( relsFileText, 'application/xml' ); - var relsNodes = relsXmlData.querySelectorAll( 'Relationship' ); + const relsNodes = relsXmlData.querySelectorAll( 'Relationship' ); - for ( var i = 0; i < relsNodes.length; i ++ ) { + for ( let i = 0; i < relsNodes.length; i ++ ) { - var relsNode = relsNodes[ i ]; + const relsNode = relsNodes[ i ]; - var relationship = { + const relationship = { target: relsNode.getAttribute( 'Target' ), //required id: relsNode.getAttribute( 'Id' ), //required type: relsNode.getAttribute( 'Type' ) //required @@ -262,13 +259,13 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseMetadataNodes( metadataNodes ) { - var metadataData = {}; + const metadataData = {}; - for ( var i = 0; i < metadataNodes.length; i ++ ) { + for ( let i = 0; i < metadataNodes.length; i ++ ) { - var metadataNode = metadataNodes[ i ]; - var name = metadataNode.getAttribute( 'name' ); - var validNames = [ + const metadataNode = metadataNodes[ i ]; + const name = metadataNode.getAttribute( 'name' ); + const validNames = [ 'Title', 'Designer', 'Description', @@ -293,17 +290,17 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseBasematerialsNode( basematerialsNode ) { - var basematerialsData = { + const basematerialsData = { id: basematerialsNode.getAttribute( 'id' ), // required basematerials: [] }; - var basematerialNodes = basematerialsNode.querySelectorAll( 'base' ); + const basematerialNodes = basematerialsNode.querySelectorAll( 'base' ); - for ( var i = 0; i < basematerialNodes.length; i ++ ) { + for ( let i = 0; i < basematerialNodes.length; i ++ ) { - var basematerialNode = basematerialNodes[ i ]; - var basematerialData = parseBasematerialNode( basematerialNode ); + const basematerialNode = basematerialNodes[ i ]; + const basematerialData = parseBasematerialNode( basematerialNode ); basematerialData.index = i; // the order and count of the material nodes form an implicit 0-based index basematerialsData.basematerials.push( basematerialData ); @@ -315,7 +312,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseTexture2DNode( texture2DNode ) { - var texture2dData = { + const texture2dData = { id: texture2DNode.getAttribute( 'id' ), // required path: texture2DNode.getAttribute( 'path' ), // required contenttype: texture2DNode.getAttribute( 'contenttype' ), // required @@ -330,21 +327,21 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseTextures2DGroupNode( texture2DGroupNode ) { - var texture2DGroupData = { + const texture2DGroupData = { id: texture2DGroupNode.getAttribute( 'id' ), // required texid: texture2DGroupNode.getAttribute( 'texid' ), // required displaypropertiesid: texture2DGroupNode.getAttribute( 'displaypropertiesid' ) }; - var tex2coordNodes = texture2DGroupNode.querySelectorAll( 'tex2coord' ); + const tex2coordNodes = texture2DGroupNode.querySelectorAll( 'tex2coord' ); - var uvs = []; + const uvs = []; - for ( var i = 0; i < tex2coordNodes.length; i ++ ) { + for ( let i = 0; i < tex2coordNodes.length; i ++ ) { - var tex2coordNode = tex2coordNodes[ i ]; - var u = tex2coordNode.getAttribute( 'u' ); - var v = tex2coordNode.getAttribute( 'v' ); + const tex2coordNode = tex2coordNodes[ i ]; + const u = tex2coordNode.getAttribute( 'u' ); + const v = tex2coordNode.getAttribute( 'v' ); uvs.push( parseFloat( u ), parseFloat( v ) ); @@ -358,20 +355,20 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseColorGroupNode( colorGroupNode ) { - var colorGroupData = { + const colorGroupData = { id: colorGroupNode.getAttribute( 'id' ), // required displaypropertiesid: colorGroupNode.getAttribute( 'displaypropertiesid' ) }; - var colorNodes = colorGroupNode.querySelectorAll( 'color' ); + const colorNodes = colorGroupNode.querySelectorAll( 'color' ); - var colors = []; - var colorObject = new Color(); + const colors = []; + const colorObject = new Color(); - for ( var i = 0; i < colorNodes.length; i ++ ) { + for ( let i = 0; i < colorNodes.length; i ++ ) { - var colorNode = colorNodes[ i ]; - var color = colorNode.getAttribute( 'color' ); + const colorNode = colorNodes[ i ]; + const color = colorNode.getAttribute( 'color' ); colorObject.setStyle( color.substring( 0, 7 ) ); colorObject.convertSRGBToLinear(); // color is in sRGB @@ -388,17 +385,17 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseMetallicDisplaypropertiesNode( metallicDisplaypropetiesNode ) { - var metallicDisplaypropertiesData = { + const metallicDisplaypropertiesData = { id: metallicDisplaypropetiesNode.getAttribute( 'id' ) // required }; - var metallicNodes = metallicDisplaypropetiesNode.querySelectorAll( 'pbmetallic' ); + const metallicNodes = metallicDisplaypropetiesNode.querySelectorAll( 'pbmetallic' ); - var metallicData = []; + const metallicData = []; - for ( var i = 0; i < metallicNodes.length; i ++ ) { + for ( let i = 0; i < metallicNodes.length; i ++ ) { - var metallicNode = metallicNodes[ i ]; + const metallicNode = metallicNodes[ i ]; metallicData.push( { name: metallicNode.getAttribute( 'name' ), // required @@ -416,7 +413,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseBasematerialNode( basematerialNode ) { - var basematerialData = {}; + const basematerialData = {}; basematerialData[ 'name' ] = basematerialNode.getAttribute( 'name' ); // required basematerialData[ 'displaycolor' ] = basematerialNode.getAttribute( 'displaycolor' ); // required @@ -428,17 +425,17 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseMeshNode( meshNode ) { - var meshData = {}; + const meshData = {}; - var vertices = []; - var vertexNodes = meshNode.querySelectorAll( 'vertices vertex' ); + const vertices = []; + const vertexNodes = meshNode.querySelectorAll( 'vertices vertex' ); - for ( var i = 0; i < vertexNodes.length; i ++ ) { + for ( let i = 0; i < vertexNodes.length; i ++ ) { - var vertexNode = vertexNodes[ i ]; - var x = vertexNode.getAttribute( 'x' ); - var y = vertexNode.getAttribute( 'y' ); - var z = vertexNode.getAttribute( 'z' ); + const vertexNode = vertexNodes[ i ]; + const x = vertexNode.getAttribute( 'x' ); + const y = vertexNode.getAttribute( 'y' ); + const z = vertexNode.getAttribute( 'z' ); vertices.push( parseFloat( x ), parseFloat( y ), parseFloat( z ) ); @@ -446,22 +443,22 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { meshData[ 'vertices' ] = new Float32Array( vertices ); - var triangleProperties = []; - var triangles = []; - var triangleNodes = meshNode.querySelectorAll( 'triangles triangle' ); + const triangleProperties = []; + const triangles = []; + const triangleNodes = meshNode.querySelectorAll( 'triangles triangle' ); - for ( var i = 0; i < triangleNodes.length; i ++ ) { + for ( let i = 0; i < triangleNodes.length; i ++ ) { - var triangleNode = triangleNodes[ i ]; - var v1 = triangleNode.getAttribute( 'v1' ); - var v2 = triangleNode.getAttribute( 'v2' ); - var v3 = triangleNode.getAttribute( 'v3' ); - var p1 = triangleNode.getAttribute( 'p1' ); - var p2 = triangleNode.getAttribute( 'p2' ); - var p3 = triangleNode.getAttribute( 'p3' ); - var pid = triangleNode.getAttribute( 'pid' ); + const triangleNode = triangleNodes[ i ]; + const v1 = triangleNode.getAttribute( 'v1' ); + const v2 = triangleNode.getAttribute( 'v2' ); + const v3 = triangleNode.getAttribute( 'v3' ); + const p1 = triangleNode.getAttribute( 'p1' ); + const p2 = triangleNode.getAttribute( 'p2' ); + const p3 = triangleNode.getAttribute( 'p3' ); + const pid = triangleNode.getAttribute( 'pid' ); - var triangleProperty = {}; + const triangleProperty = {}; triangleProperty[ 'v1' ] = parseInt( v1, 10 ); triangleProperty[ 'v2' ] = parseInt( v2, 10 ); @@ -512,14 +509,14 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseComponentsNode( componentsNode ) { - var components = []; + const components = []; - var componentNodes = componentsNode.querySelectorAll( 'component' ); + const componentNodes = componentsNode.querySelectorAll( 'component' ); - for ( var i = 0; i < componentNodes.length; i ++ ) { + for ( let i = 0; i < componentNodes.length; i ++ ) { - var componentNode = componentNodes[ i ]; - var componentData = parseComponentNode( componentNode ); + const componentNode = componentNodes[ i ]; + const componentData = parseComponentNode( componentNode ); components.push( componentData ); } @@ -530,11 +527,11 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseComponentNode( componentNode ) { - var componentData = {}; + const componentData = {}; componentData[ 'objectId' ] = componentNode.getAttribute( 'objectid' ); // required - var transform = componentNode.getAttribute( 'transform' ); + const transform = componentNode.getAttribute( 'transform' ); if ( transform ) { @@ -548,14 +545,14 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseTransform( transform ) { - var t = []; + const t = []; transform.split( ' ' ).forEach( function ( s ) { t.push( parseFloat( s ) ); } ); - var matrix = new Matrix4(); + const matrix = new Matrix4(); matrix.set( t[ 0 ], t[ 3 ], t[ 6 ], t[ 9 ], t[ 1 ], t[ 4 ], t[ 7 ], t[ 10 ], @@ -569,11 +566,11 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseObjectNode( objectNode ) { - var objectData = { + const objectData = { type: objectNode.getAttribute( 'type' ) }; - var id = objectNode.getAttribute( 'id' ); + const id = objectNode.getAttribute( 'id' ); if ( id ) { @@ -581,7 +578,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var pid = objectNode.getAttribute( 'pid' ); + const pid = objectNode.getAttribute( 'pid' ); if ( pid ) { @@ -589,7 +586,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var pindex = objectNode.getAttribute( 'pindex' ); + const pindex = objectNode.getAttribute( 'pindex' ); if ( pindex ) { @@ -597,7 +594,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var thumbnail = objectNode.getAttribute( 'thumbnail' ); + const thumbnail = objectNode.getAttribute( 'thumbnail' ); if ( thumbnail ) { @@ -605,7 +602,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var partnumber = objectNode.getAttribute( 'partnumber' ); + const partnumber = objectNode.getAttribute( 'partnumber' ); if ( partnumber ) { @@ -613,7 +610,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var name = objectNode.getAttribute( 'name' ); + const name = objectNode.getAttribute( 'name' ); if ( name ) { @@ -621,7 +618,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var meshNode = objectNode.querySelector( 'mesh' ); + const meshNode = objectNode.querySelector( 'mesh' ); if ( meshNode ) { @@ -629,7 +626,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var componentsNode = objectNode.querySelector( 'components' ); + const componentsNode = objectNode.querySelector( 'components' ); if ( componentsNode ) { @@ -643,15 +640,15 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseResourcesNode( resourcesNode ) { - var resourcesData = {}; + const resourcesData = {}; resourcesData[ 'basematerials' ] = {}; - var basematerialsNodes = resourcesNode.querySelectorAll( 'basematerials' ); + const basematerialsNodes = resourcesNode.querySelectorAll( 'basematerials' ); - for ( var i = 0; i < basematerialsNodes.length; i ++ ) { + for ( let i = 0; i < basematerialsNodes.length; i ++ ) { - var basematerialsNode = basematerialsNodes[ i ]; - var basematerialsData = parseBasematerialsNode( basematerialsNode ); + const basematerialsNode = basematerialsNodes[ i ]; + const basematerialsData = parseBasematerialsNode( basematerialsNode ); resourcesData[ 'basematerials' ][ basematerialsData[ 'id' ] ] = basematerialsData; } @@ -659,12 +656,12 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // resourcesData[ 'texture2d' ] = {}; - var textures2DNodes = resourcesNode.querySelectorAll( 'texture2d' ); + const textures2DNodes = resourcesNode.querySelectorAll( 'texture2d' ); - for ( var i = 0; i < textures2DNodes.length; i ++ ) { + for ( let i = 0; i < textures2DNodes.length; i ++ ) { - var textures2DNode = textures2DNodes[ i ]; - var texture2DData = parseTexture2DNode( textures2DNode ); + const textures2DNode = textures2DNodes[ i ]; + const texture2DData = parseTexture2DNode( textures2DNode ); resourcesData[ 'texture2d' ][ texture2DData[ 'id' ] ] = texture2DData; } @@ -672,12 +669,12 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // resourcesData[ 'colorgroup' ] = {}; - var colorGroupNodes = resourcesNode.querySelectorAll( 'colorgroup' ); + const colorGroupNodes = resourcesNode.querySelectorAll( 'colorgroup' ); - for ( var i = 0; i < colorGroupNodes.length; i ++ ) { + for ( let i = 0; i < colorGroupNodes.length; i ++ ) { - var colorGroupNode = colorGroupNodes[ i ]; - var colorGroupData = parseColorGroupNode( colorGroupNode ); + const colorGroupNode = colorGroupNodes[ i ]; + const colorGroupData = parseColorGroupNode( colorGroupNode ); resourcesData[ 'colorgroup' ][ colorGroupData[ 'id' ] ] = colorGroupData; } @@ -685,12 +682,12 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // resourcesData[ 'pbmetallicdisplayproperties' ] = {}; - var pbmetallicdisplaypropertiesNodes = resourcesNode.querySelectorAll( 'pbmetallicdisplayproperties' ); + const pbmetallicdisplaypropertiesNodes = resourcesNode.querySelectorAll( 'pbmetallicdisplayproperties' ); - for ( var i = 0; i < pbmetallicdisplaypropertiesNodes.length; i ++ ) { + for ( let i = 0; i < pbmetallicdisplaypropertiesNodes.length; i ++ ) { - var pbmetallicdisplaypropertiesNode = pbmetallicdisplaypropertiesNodes[ i ]; - var pbmetallicdisplaypropertiesData = parseMetallicDisplaypropertiesNode( pbmetallicdisplaypropertiesNode ); + const pbmetallicdisplaypropertiesNode = pbmetallicdisplaypropertiesNodes[ i ]; + const pbmetallicdisplaypropertiesData = parseMetallicDisplaypropertiesNode( pbmetallicdisplaypropertiesNode ); resourcesData[ 'pbmetallicdisplayproperties' ][ pbmetallicdisplaypropertiesData[ 'id' ] ] = pbmetallicdisplaypropertiesData; } @@ -698,12 +695,12 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // resourcesData[ 'texture2dgroup' ] = {}; - var textures2DGroupNodes = resourcesNode.querySelectorAll( 'texture2dgroup' ); + const textures2DGroupNodes = resourcesNode.querySelectorAll( 'texture2dgroup' ); - for ( var i = 0; i < textures2DGroupNodes.length; i ++ ) { + for ( let i = 0; i < textures2DGroupNodes.length; i ++ ) { - var textures2DGroupNode = textures2DGroupNodes[ i ]; - var textures2DGroupData = parseTextures2DGroupNode( textures2DGroupNode ); + const textures2DGroupNode = textures2DGroupNodes[ i ]; + const textures2DGroupData = parseTextures2DGroupNode( textures2DGroupNode ); resourcesData[ 'texture2dgroup' ][ textures2DGroupData[ 'id' ] ] = textures2DGroupData; } @@ -711,12 +708,12 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // resourcesData[ 'object' ] = {}; - var objectNodes = resourcesNode.querySelectorAll( 'object' ); + const objectNodes = resourcesNode.querySelectorAll( 'object' ); - for ( var i = 0; i < objectNodes.length; i ++ ) { + for ( let i = 0; i < objectNodes.length; i ++ ) { - var objectNode = objectNodes[ i ]; - var objectData = parseObjectNode( objectNode ); + const objectNode = objectNodes[ i ]; + const objectData = parseObjectNode( objectNode ); resourcesData[ 'object' ][ objectData[ 'id' ] ] = objectData; } @@ -727,16 +724,16 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseBuildNode( buildNode ) { - var buildData = []; - var itemNodes = buildNode.querySelectorAll( 'item' ); + const buildData = []; + const itemNodes = buildNode.querySelectorAll( 'item' ); - for ( var i = 0; i < itemNodes.length; i ++ ) { + for ( let i = 0; i < itemNodes.length; i ++ ) { - var itemNode = itemNodes[ i ]; - var buildItem = { + const itemNode = itemNodes[ i ]; + const buildItem = { objectId: itemNode.getAttribute( 'objectid' ) }; - var transform = itemNode.getAttribute( 'transform' ); + const transform = itemNode.getAttribute( 'transform' ); if ( transform ) { @@ -754,8 +751,8 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseModelNode( modelNode ) { - var modelData = { unit: modelNode.getAttribute( 'unit' ) || 'millimeter' }; - var metadataNodes = modelNode.querySelectorAll( 'metadata' ); + const modelData = { unit: modelNode.getAttribute( 'unit' ) || 'millimeter' }; + const metadataNodes = modelNode.querySelectorAll( 'metadata' ); if ( metadataNodes ) { @@ -763,7 +760,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var resourcesNode = modelNode.querySelector( 'resources' ); + const resourcesNode = modelNode.querySelector( 'resources' ); if ( resourcesNode ) { @@ -771,7 +768,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var buildNode = modelNode.querySelector( 'build' ); + const buildNode = modelNode.querySelector( 'build' ); if ( buildNode ) { @@ -785,19 +782,19 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildTexture( texture2dgroup, objects, modelData, textureData ) { - var texid = texture2dgroup.texid; - var texture2ds = modelData.resources.texture2d; - var texture2d = texture2ds[ texid ]; + const texid = texture2dgroup.texid; + const texture2ds = modelData.resources.texture2d; + const texture2d = texture2ds[ texid ]; if ( texture2d ) { - var data = textureData[ texture2d.path ]; - var type = texture2d.contenttype; + const data = textureData[ texture2d.path ]; + const type = texture2d.contenttype; - var blob = new Blob( [ data ], { type: type } ); - var sourceURI = URL.createObjectURL( blob ); + const blob = new Blob( [ data ], { type: type } ); + const sourceURI = URL.createObjectURL( blob ); - var texture = textureLoader.load( sourceURI, function () { + const texture = textureLoader.load( sourceURI, function () { URL.revokeObjectURL( sourceURI ); @@ -880,16 +877,16 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - function buildBasematerialsMeshes( basematerials, triangleProperties, modelData, meshData, textureData, objectData ) { + function buildBasematerialsMeshes( basematerials, triangleProperties, meshData, objects, modelData, textureData, objectData ) { - var objectPindex = objectData.pindex; + const objectPindex = objectData.pindex; - var materialMap = {}; + const materialMap = {}; - for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) { + for ( let i = 0, l = triangleProperties.length; i < l; i ++ ) { - var triangleProperty = triangleProperties[ i ]; - var pindex = ( triangleProperty.p1 !== undefined ) ? triangleProperty.p1 : objectPindex; + const triangleProperty = triangleProperties[ i ]; + const pindex = ( triangleProperty.p1 !== undefined ) ? triangleProperty.p1 : objectPindex; if ( materialMap[ pindex ] === undefined ) materialMap[ pindex ] = []; @@ -899,27 +896,27 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // - var keys = Object.keys( materialMap ); - var meshes = []; + const keys = Object.keys( materialMap ); + const meshes = []; - for ( var i = 0, l = keys.length; i < l; i ++ ) { + for ( let i = 0, l = keys.length; i < l; i ++ ) { - var materialIndex = keys[ i ]; - var trianglePropertiesProps = materialMap[ materialIndex ]; - var basematerialData = basematerials.basematerials[ materialIndex ]; - var material = getBuild( basematerialData, objects, modelData, textureData, objectData, buildBasematerial ); + const materialIndex = keys[ i ]; + const trianglePropertiesProps = materialMap[ materialIndex ]; + const basematerialData = basematerials.basematerials[ materialIndex ]; + const material = getBuild( basematerialData, objects, modelData, textureData, objectData, buildBasematerial ); // - var geometry = new BufferGeometry(); + const geometry = new BufferGeometry(); - var positionData = []; + const positionData = []; - var vertices = meshData.vertices; + const vertices = meshData.vertices; - for ( var j = 0, jl = trianglePropertiesProps.length; j < jl; j ++ ) { + for ( let j = 0, jl = trianglePropertiesProps.length; j < jl; j ++ ) { - var triangleProperty = trianglePropertiesProps[ j ]; + const triangleProperty = trianglePropertiesProps[ j ]; positionData.push( vertices[ ( triangleProperty.v1 * 3 ) + 0 ] ); positionData.push( vertices[ ( triangleProperty.v1 * 3 ) + 1 ] ); @@ -940,7 +937,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // - var mesh = new Mesh( geometry, material ); + const mesh = new Mesh( geometry, material ); meshes.push( mesh ); } @@ -949,21 +946,21 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - function buildTexturedMesh( texture2dgroup, triangleProperties, modelData, meshData, textureData, objectData ) { + function buildTexturedMesh( texture2dgroup, triangleProperties, meshData, objects, modelData, textureData, objectData ) { // geometry - var geometry = new BufferGeometry(); + const geometry = new BufferGeometry(); - var positionData = []; - var uvData = []; + const positionData = []; + const uvData = []; - var vertices = meshData.vertices; - var uvs = texture2dgroup.uvs; + const vertices = meshData.vertices; + const uvs = texture2dgroup.uvs; - for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) { + for ( let i = 0, l = triangleProperties.length; i < l; i ++ ) { - var triangleProperty = triangleProperties[ i ]; + const triangleProperty = triangleProperties[ i ]; positionData.push( vertices[ ( triangleProperty.v1 * 3 ) + 0 ] ); positionData.push( vertices[ ( triangleProperty.v1 * 3 ) + 1 ] ); @@ -995,37 +992,37 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // material - var texture = getBuild( texture2dgroup, objects, modelData, textureData, objectData, buildTexture ); + const texture = getBuild( texture2dgroup, objects, modelData, textureData, objectData, buildTexture ); - var material = new MeshPhongMaterial( { map: texture, flatShading: true } ); + const material = new MeshPhongMaterial( { map: texture, flatShading: true } ); // mesh - var mesh = new Mesh( geometry, material ); + const mesh = new Mesh( geometry, material ); return mesh; } - function buildVertexColorMesh( colorgroup, triangleProperties, modelData, meshData, objectData ) { + function buildVertexColorMesh( colorgroup, triangleProperties, meshData, objects, modelData, objectData ) { // geometry - var geometry = new BufferGeometry(); + const geometry = new BufferGeometry(); - var positionData = []; - var colorData = []; + const positionData = []; + const colorData = []; - var vertices = meshData.vertices; - var colors = colorgroup.colors; + const vertices = meshData.vertices; + const colors = colorgroup.colors; - for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) { + for ( let i = 0, l = triangleProperties.length; i < l; i ++ ) { - var triangleProperty = triangleProperties[ i ]; + const triangleProperty = triangleProperties[ i ]; - var v1 = triangleProperty.v1; - var v2 = triangleProperty.v2; - var v3 = triangleProperty.v3; + const v1 = triangleProperty.v1; + const v2 = triangleProperty.v2; + const v3 = triangleProperty.v3; positionData.push( vertices[ ( v1 * 3 ) + 0 ] ); positionData.push( vertices[ ( v1 * 3 ) + 1 ] ); @@ -1041,9 +1038,9 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // - var p1 = ( triangleProperty.p1 !== undefined ) ? triangleProperty.p1 : objectData.pindex; - var p2 = ( triangleProperty.p2 !== undefined ) ? triangleProperty.p2 : p1; - var p3 = ( triangleProperty.p3 !== undefined ) ? triangleProperty.p3 : p1; + const p1 = ( triangleProperty.p1 !== undefined ) ? triangleProperty.p1 : objectData.pindex; + const p2 = ( triangleProperty.p2 !== undefined ) ? triangleProperty.p2 : p1; + const p3 = ( triangleProperty.p3 !== undefined ) ? triangleProperty.p3 : p1; colorData.push( colors[ ( p1 * 3 ) + 0 ] ); colorData.push( colors[ ( p1 * 3 ) + 1 ] ); @@ -1064,11 +1061,11 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // material - var material = new MeshPhongMaterial( { vertexColors: true, flatShading: true } ); + const material = new MeshPhongMaterial( { vertexColors: true, flatShading: true } ); // mesh - var mesh = new Mesh( geometry, material ); + const mesh = new Mesh( geometry, material ); return mesh; @@ -1076,36 +1073,36 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildDefaultMesh( meshData ) { - var geometry = new BufferGeometry(); + const geometry = new BufferGeometry(); geometry.setIndex( new BufferAttribute( meshData[ 'triangles' ], 1 ) ); geometry.setAttribute( 'position', new BufferAttribute( meshData[ 'vertices' ], 3 ) ); - var material = new MeshPhongMaterial( { color: 0xaaaaff, flatShading: true } ); + const material = new MeshPhongMaterial( { color: 0xaaaaff, flatShading: true } ); - var mesh = new Mesh( geometry, material ); + const mesh = new Mesh( geometry, material ); return mesh; } - function buildMeshes( resourceMap, modelData, meshData, textureData, objectData ) { + function buildMeshes( resourceMap, meshData, objects, modelData, textureData, objectData ) { - var keys = Object.keys( resourceMap ); - var meshes = []; + const keys = Object.keys( resourceMap ); + const meshes = []; - for ( var i = 0, il = keys.length; i < il; i ++ ) { + for ( let i = 0, il = keys.length; i < il; i ++ ) { - var resourceId = keys[ i ]; - var triangleProperties = resourceMap[ resourceId ]; - var resourceType = getResourceType( resourceId, modelData ); + const resourceId = keys[ i ]; + const triangleProperties = resourceMap[ resourceId ]; + const resourceType = getResourceType( resourceId, modelData ); switch ( resourceType ) { case 'material': - var basematerials = modelData.resources.basematerials[ resourceId ]; - var newMeshes = buildBasematerialsMeshes( basematerials, triangleProperties, modelData, meshData, textureData, objectData ); + const basematerials = modelData.resources.basematerials[ resourceId ]; + const newMeshes = buildBasematerialsMeshes( basematerials, triangleProperties, meshData, objects, modelData, textureData, objectData ); - for ( var j = 0, jl = newMeshes.length; j < jl; j ++ ) { + for ( let j = 0, jl = newMeshes.length; j < jl; j ++ ) { meshes.push( newMeshes[ j ] ); @@ -1114,13 +1111,13 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { break; case 'texture': - var texture2dgroup = modelData.resources.texture2dgroup[ resourceId ]; - meshes.push( buildTexturedMesh( texture2dgroup, triangleProperties, modelData, meshData, textureData, objectData ) ); + const texture2dgroup = modelData.resources.texture2dgroup[ resourceId ]; + meshes.push( buildTexturedMesh( texture2dgroup, triangleProperties, meshData, objects, modelData, textureData, objectData ) ); break; case 'vertexColors': - var colorgroup = modelData.resources.colorgroup[ resourceId ]; - meshes.push( buildVertexColorMesh( colorgroup, triangleProperties, modelData, meshData, objectData ) ); + const colorgroup = modelData.resources.colorgroup[ resourceId ]; + meshes.push( buildVertexColorMesh( colorgroup, triangleProperties, meshData, objects, modelData, objectData ) ); break; case 'default': @@ -1166,16 +1163,16 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function analyzeObject( modelData, meshData, objectData ) { - var resourceMap = {}; + const resourceMap = {}; - var triangleProperties = meshData[ 'triangleProperties' ]; + const triangleProperties = meshData[ 'triangleProperties' ]; - var objectPid = objectData.pid; + const objectPid = objectData.pid; - for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) { + for ( let i = 0, l = triangleProperties.length; i < l; i ++ ) { - var triangleProperty = triangleProperties[ i ]; - var pid = ( triangleProperty.pid !== undefined ) ? triangleProperty.pid : objectPid; + const triangleProperty = triangleProperties[ i ]; + let pid = ( triangleProperty.pid !== undefined ) ? triangleProperty.pid : objectPid; if ( pid === undefined ) pid = 'default'; @@ -1191,12 +1188,12 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildGroup( meshData, objects, modelData, textureData, objectData ) { - var group = new Group(); + const group = new Group(); - var resourceMap = analyzeObject( modelData, meshData, objectData ); - var meshes = buildMeshes( resourceMap, modelData, meshData, textureData, objectData ); + const resourceMap = analyzeObject( modelData, meshData, objectData ); + const meshes = buildMeshes( resourceMap, meshData, objects, modelData, textureData, objectData ); - for ( var i = 0, l = meshes.length; i < l; i ++ ) { + for ( let i = 0, l = meshes.length; i < l; i ++ ) { group.add( meshes[ i ] ); @@ -1214,16 +1211,16 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var availableExtensions = []; - var keys = Object.keys( extensions ); + const availableExtensions = []; + const keys = Object.keys( extensions ); - for ( var i = 0; i < keys.length; i ++ ) { + for ( let i = 0; i < keys.length; i ++ ) { - var ns = keys[ i ]; + const ns = keys[ i ]; - for ( var j = 0; j < scope.availableExtensions.length; j ++ ) { + for ( let j = 0; j < scope.availableExtensions.length; j ++ ) { - var extension = scope.availableExtensions[ j ]; + const extension = scope.availableExtensions[ j ]; if ( extension.ns === ns ) { @@ -1235,9 +1232,9 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - for ( var i = 0; i < availableExtensions.length; i ++ ) { + for ( let i = 0; i < availableExtensions.length; i ++ ) { - var extension = availableExtensions[ i ]; + const extension = availableExtensions[ i ]; extension.apply( modelXml, extensions[ extension[ 'ns' ] ], meshData ); } @@ -1256,17 +1253,17 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildBasematerial( materialData, objects, modelData ) { - var material; + let material; - var displaypropertiesid = materialData.displaypropertiesid; - var pbmetallicdisplayproperties = modelData.resources.pbmetallicdisplayproperties; + const displaypropertiesid = materialData.displaypropertiesid; + const pbmetallicdisplayproperties = modelData.resources.pbmetallicdisplayproperties; if ( displaypropertiesid !== null && pbmetallicdisplayproperties[ displaypropertiesid ] !== undefined ) { // metallic display property, use StandardMaterial - var pbmetallicdisplayproperty = pbmetallicdisplayproperties[ displaypropertiesid ]; - var metallicData = pbmetallicdisplayproperty.data[ materialData.index ]; + const pbmetallicdisplayproperty = pbmetallicdisplayproperties[ displaypropertiesid ]; + const metallicData = pbmetallicdisplayproperty.data[ materialData.index ]; material = new MeshStandardMaterial( { flatShading: true, roughness: metallicData.roughness, metalness: metallicData.metallicness } ); @@ -1282,9 +1279,9 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // displaycolor MUST be specified with a value of a 6 or 8 digit hexadecimal number, e.g. "#RRGGBB" or "#RRGGBBAA" - var displaycolor = materialData.displaycolor; + const displaycolor = materialData.displaycolor; - var color = displaycolor.substring( 0, 7 ); + const color = displaycolor.substring( 0, 7 ); material.color.setStyle( color ); material.color.convertSRGBToLinear(); // displaycolor is in sRGB @@ -1302,12 +1299,12 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildComposite( compositeData, objects, modelData, textureData ) { - var composite = new Group(); + const composite = new Group(); - for ( var j = 0; j < compositeData.length; j ++ ) { + for ( let j = 0; j < compositeData.length; j ++ ) { - var component = compositeData[ j ]; - var build = objects[ component.objectId ]; + const component = compositeData[ j ]; + let build = objects[ component.objectId ]; if ( build === undefined ) { @@ -1316,11 +1313,11 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var object3D = build.clone(); + const object3D = build.clone(); // apply component transform - var transform = component.transform; + const transform = component.transform; if ( transform ) { @@ -1338,14 +1335,14 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildObject( objectId, objects, modelData, textureData ) { - var objectData = modelData[ 'resources' ][ 'object' ][ objectId ]; + const objectData = modelData[ 'resources' ][ 'object' ][ objectId ]; if ( objectData[ 'mesh' ] ) { - var meshData = objectData[ 'mesh' ]; + const meshData = objectData[ 'mesh' ]; - var extensions = modelData[ 'extensions' ]; - var modelXml = modelData[ 'xml' ]; + const extensions = modelData[ 'extensions' ]; + const modelXml = modelData[ 'xml' ]; applyExtensions( extensions, meshData, modelXml ); @@ -1353,7 +1350,7 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else { - var compositeData = objectData[ 'components' ]; + const compositeData = objectData[ 'components' ]; objects[ objectData.id ] = getBuild( compositeData, objects, modelData, textureData, objectData, buildComposite ); @@ -1363,20 +1360,20 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildObjects( data3mf ) { - var modelsData = data3mf.model; - var modelRels = data3mf.modelRels; - var objects = {}; - var modelsKeys = Object.keys( modelsData ); - var textureData = {}; + const modelsData = data3mf.model; + const modelRels = data3mf.modelRels; + const objects = {}; + const modelsKeys = Object.keys( modelsData ); + const textureData = {}; // evaluate model relationships to textures if ( modelRels ) { - for ( var i = 0, l = modelRels.length; i < l; i ++ ) { + for ( let i = 0, l = modelRels.length; i < l; i ++ ) { - var modelRel = modelRels[ i ]; - var textureKey = modelRel.target.substring( 1 ); + const modelRel = modelRels[ i ]; + const textureKey = modelRel.target.substring( 1 ); if ( data3mf.texture[ textureKey ] ) { @@ -1390,16 +1387,16 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // start build - for ( var i = 0; i < modelsKeys.length; i ++ ) { + for ( let i = 0; i < modelsKeys.length; i ++ ) { - var modelsKey = modelsKeys[ i ]; - var modelData = modelsData[ modelsKey ]; + const modelsKey = modelsKeys[ i ]; + const modelData = modelsData[ modelsKey ]; - var objectIds = Object.keys( modelData[ 'resources' ][ 'object' ] ); + const objectIds = Object.keys( modelData[ 'resources' ][ 'object' ] ); - for ( var j = 0; j < objectIds.length; j ++ ) { + for ( let j = 0; j < objectIds.length; j ++ ) { - var objectId = objectIds[ j ]; + const objectId = objectIds[ j ]; buildObject( objectId, objects, modelData, textureData ); @@ -1413,10 +1410,10 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function fetch3DModelPart( rels ) { - for ( var i = 0; i < rels.length; i ++ ) { + for ( let i = 0; i < rels.length; i ++ ) { - var rel = rels[ i ]; - var extension = rel.target.split( '.' ).pop(); + const rel = rels[ i ]; + const extension = rel.target.split( '.' ).pop(); if ( extension.toLowerCase() === 'model' ) return rel; @@ -1426,19 +1423,19 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function build( objects, data3mf ) { - var group = new Group(); + const group = new Group(); - var relationship = fetch3DModelPart( data3mf[ 'rels' ] ); - var buildData = data3mf.model[ relationship[ 'target' ].substring( 1 ) ][ 'build' ]; + const relationship = fetch3DModelPart( data3mf[ 'rels' ] ); + const buildData = data3mf.model[ relationship[ 'target' ].substring( 1 ) ][ 'build' ]; - for ( var i = 0; i < buildData.length; i ++ ) { + for ( let i = 0; i < buildData.length; i ++ ) { - var buildItem = buildData[ i ]; - var object3D = objects[ buildItem[ 'objectId' ] ]; + const buildItem = buildData[ i ]; + const object3D = objects[ buildItem[ 'objectId' ] ]; // apply transform - var transform = buildItem[ 'transform' ]; + const transform = buildItem[ 'transform' ]; if ( transform ) { @@ -1454,19 +1451,19 @@ ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var data3mf = loadDocument( data ); - var objects = buildObjects( data3mf ); + const data3mf = loadDocument( data ); + const objects = buildObjects( data3mf ); return build( objects, data3mf ); - }, + } - addExtension: function ( extension ) { + addExtension( extension ) { this.availableExtensions.push( extension ); } -} ); +} export { ThreeMFLoader }; diff --git a/examples/jsm/loaders/AMFLoader.js b/examples/jsm/loaders/AMFLoader.js index 683c6395f1c9c8..359a69a87d4295 100644 --- a/examples/jsm/loaders/AMFLoader.js +++ b/examples/jsm/loaders/AMFLoader.js @@ -18,7 +18,7 @@ import * as fflate from '../libs/fflate.module.min.js'; * More information about the AMF format: http://amf.wikispaces.com * * Usage: - * var loader = new AMFLoader(); + * const loader = new AMFLoader(); * loader.load('/path/to/project.amf', function(objecttree) { * scene.add(objecttree); * }); @@ -29,21 +29,19 @@ import * as fflate from '../libs/fflate.module.min.js'; * */ -var AMFLoader = function ( manager ) { +class AMFLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { -}; + super( manager ); -AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: AMFLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var loader = new FileLoader( scope.manager ); + const loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( scope.requestHeader ); @@ -72,19 +70,19 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } - parse: function ( data ) { + parse( data ) { function loadDocument( data ) { - var view = new DataView( data ); - var magic = String.fromCharCode( view.getUint8( 0 ), view.getUint8( 1 ) ); + let view = new DataView( data ); + const magic = String.fromCharCode( view.getUint8( 0 ), view.getUint8( 1 ) ); if ( magic === 'PK' ) { - var zip = null; - var file = null; + let zip = null; + let file = null; console.log( 'THREE.AMFLoader: Loading Zip' ); @@ -103,7 +101,7 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - for ( var file in zip ) { + for ( file in zip ) { if ( file.toLowerCase().substr( - 4 ) === '.amf' ) { @@ -118,8 +116,8 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var fileText = LoaderUtils.decodeText( view ); - var xmlData = new DOMParser().parseFromString( fileText, 'application/xml' ); + const fileText = LoaderUtils.decodeText( view ); + const xmlData = new DOMParser().parseFromString( fileText, 'application/xml' ); if ( xmlData.documentElement.nodeName.toLowerCase() !== 'amf' ) { @@ -134,8 +132,8 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function loadDocumentScale( node ) { - var scale = 1.0; - var unit = 'millimeter'; + let scale = 1.0; + let unit = 'millimeter'; if ( node.documentElement.attributes.unit !== undefined ) { @@ -143,7 +141,7 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var scaleUnits = { + const scaleUnits = { millimeter: 1.0, inch: 25.4, feet: 304.8, @@ -164,15 +162,15 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function loadMaterials( node ) { - var matName = 'AMF Material'; - var matId = node.attributes.id.textContent; - var color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; + let matName = 'AMF Material'; + const matId = node.attributes.id.textContent; + let color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; - var loadedMaterial = null; + let loadedMaterial = null; - for ( var i = 0; i < node.childNodes.length; i ++ ) { + for ( let i = 0; i < node.childNodes.length; i ++ ) { - var matChildEl = node.childNodes[ i ]; + const matChildEl = node.childNodes[ i ]; if ( matChildEl.nodeName === 'metadata' && matChildEl.attributes.type !== undefined ) { @@ -209,11 +207,11 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function loadColor( node ) { - var color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; + const color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; - for ( var i = 0; i < node.childNodes.length; i ++ ) { + for ( let i = 0; i < node.childNodes.length; i ++ ) { - var matColor = node.childNodes[ i ]; + const matColor = node.childNodes[ i ]; if ( matColor.nodeName === 'r' ) { @@ -241,9 +239,9 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function loadMeshVolume( node ) { - var volume = { name: '', triangles: [], materialid: null }; + const volume = { name: '', triangles: [], materialid: null }; - var currVolumeNode = node.firstElementChild; + let currVolumeNode = node.firstElementChild; if ( node.attributes.materialid !== undefined ) { @@ -267,9 +265,9 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else if ( currVolumeNode.nodeName === 'triangle' ) { - var v1 = currVolumeNode.getElementsByTagName( 'v1' )[ 0 ].textContent; - var v2 = currVolumeNode.getElementsByTagName( 'v2' )[ 0 ].textContent; - var v3 = currVolumeNode.getElementsByTagName( 'v3' )[ 0 ].textContent; + const v1 = currVolumeNode.getElementsByTagName( 'v1' )[ 0 ].textContent; + const v2 = currVolumeNode.getElementsByTagName( 'v2' )[ 0 ].textContent; + const v3 = currVolumeNode.getElementsByTagName( 'v3' )[ 0 ].textContent; volume.triangles.push( v1, v2, v3 ); @@ -285,31 +283,31 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function loadMeshVertices( node ) { - var vertArray = []; - var normalArray = []; - var currVerticesNode = node.firstElementChild; + const vertArray = []; + const normalArray = []; + let currVerticesNode = node.firstElementChild; while ( currVerticesNode ) { if ( currVerticesNode.nodeName === 'vertex' ) { - var vNode = currVerticesNode.firstElementChild; + let vNode = currVerticesNode.firstElementChild; while ( vNode ) { if ( vNode.nodeName === 'coordinates' ) { - var x = vNode.getElementsByTagName( 'x' )[ 0 ].textContent; - var y = vNode.getElementsByTagName( 'y' )[ 0 ].textContent; - var z = vNode.getElementsByTagName( 'z' )[ 0 ].textContent; + const x = vNode.getElementsByTagName( 'x' )[ 0 ].textContent; + const y = vNode.getElementsByTagName( 'y' )[ 0 ].textContent; + const z = vNode.getElementsByTagName( 'z' )[ 0 ].textContent; vertArray.push( x, y, z ); } else if ( vNode.nodeName === 'normal' ) { - var nx = vNode.getElementsByTagName( 'nx' )[ 0 ].textContent; - var ny = vNode.getElementsByTagName( 'ny' )[ 0 ].textContent; - var nz = vNode.getElementsByTagName( 'nz' )[ 0 ].textContent; + const nx = vNode.getElementsByTagName( 'nx' )[ 0 ].textContent; + const ny = vNode.getElementsByTagName( 'ny' )[ 0 ].textContent; + const nz = vNode.getElementsByTagName( 'nz' )[ 0 ].textContent; normalArray.push( nx, ny, nz ); @@ -331,10 +329,10 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function loadObject( node ) { - var objId = node.attributes.id.textContent; - var loadedObject = { name: 'amfobject', meshes: [] }; - var currColor = null; - var currObjNode = node.firstElementChild; + const objId = node.attributes.id.textContent; + const loadedObject = { name: 'amfobject', meshes: [] }; + let currColor = null; + let currObjNode = node.firstElementChild; while ( currObjNode ) { @@ -356,14 +354,14 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else if ( currObjNode.nodeName === 'mesh' ) { - var currMeshNode = currObjNode.firstElementChild; - var mesh = { vertices: [], normals: [], volumes: [], color: currColor }; + let currMeshNode = currObjNode.firstElementChild; + const mesh = { vertices: [], normals: [], volumes: [], color: currColor }; while ( currMeshNode ) { if ( currMeshNode.nodeName === 'vertices' ) { - var loadedVertices = loadMeshVertices( currMeshNode ); + const loadedVertices = loadMeshVertices( currMeshNode ); mesh.normals = mesh.normals.concat( loadedVertices.normals ); mesh.vertices = mesh.vertices.concat( loadedVertices.vertices ); @@ -390,19 +388,19 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var xmlData = loadDocument( data ); - var amfName = ''; - var amfAuthor = ''; - var amfScale = loadDocumentScale( xmlData ); - var amfMaterials = {}; - var amfObjects = {}; - var childNodes = xmlData.documentElement.childNodes; + const xmlData = loadDocument( data ); + let amfName = ''; + let amfAuthor = ''; + const amfScale = loadDocumentScale( xmlData ); + const amfMaterials = {}; + const amfObjects = {}; + const childNodes = xmlData.documentElement.childNodes; - var i, j; + let i, j; for ( i = 0; i < childNodes.length; i ++ ) { - var child = childNodes[ i ]; + const child = childNodes[ i ]; if ( child.nodeName === 'metadata' ) { @@ -422,13 +420,13 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else if ( child.nodeName === 'material' ) { - var loadedMaterial = loadMaterials( child ); + const loadedMaterial = loadMaterials( child ); amfMaterials[ loadedMaterial.id ] = loadedMaterial.material; } else if ( child.nodeName === 'object' ) { - var loadedObject = loadObject( child ); + const loadedObject = loadObject( child ); amfObjects[ loadedObject.id ] = loadedObject.obj; @@ -436,26 +434,26 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var sceneObject = new Group(); - var defaultMaterial = new MeshPhongMaterial( { color: 0xaaaaff, flatShading: true } ); + const sceneObject = new Group(); + const defaultMaterial = new MeshPhongMaterial( { color: 0xaaaaff, flatShading: true } ); sceneObject.name = amfName; sceneObject.userData.author = amfAuthor; sceneObject.userData.loader = 'AMF'; - for ( var id in amfObjects ) { + for ( const id in amfObjects ) { - var part = amfObjects[ id ]; - var meshes = part.meshes; - var newObject = new Group(); + const part = amfObjects[ id ]; + const meshes = part.meshes; + const newObject = new Group(); newObject.name = part.name || ''; for ( i = 0; i < meshes.length; i ++ ) { - var objDefaultMaterial = defaultMaterial; - var mesh = meshes[ i ]; - var vertices = new Float32BufferAttribute( mesh.vertices, 3 ); - var normals = null; + let objDefaultMaterial = defaultMaterial; + const mesh = meshes[ i ]; + const vertices = new Float32BufferAttribute( mesh.vertices, 3 ); + let normals = null; if ( mesh.normals.length ) { @@ -465,7 +463,7 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( mesh.color ) { - var color = mesh.color; + const color = mesh.color; objDefaultMaterial = defaultMaterial.clone(); objDefaultMaterial.color = new Color( color.r, color.g, color.b ); @@ -479,13 +477,13 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var volumes = mesh.volumes; + const volumes = mesh.volumes; for ( j = 0; j < volumes.length; j ++ ) { - var volume = volumes[ j ]; - var newGeometry = new BufferGeometry(); - var material = objDefaultMaterial; + const volume = volumes[ j ]; + const newGeometry = new BufferGeometry(); + let material = objDefaultMaterial; newGeometry.setIndex( volume.triangles ); newGeometry.setAttribute( 'position', vertices.clone() ); @@ -517,6 +515,6 @@ AMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } -} ); +} export { AMFLoader }; diff --git a/examples/jsm/loaders/BVHLoader.js b/examples/jsm/loaders/BVHLoader.js index 9230767410e0ae..b916e86338496a 100644 --- a/examples/jsm/loaders/BVHLoader.js +++ b/examples/jsm/loaders/BVHLoader.js @@ -17,24 +17,22 @@ import { * */ -var BVHLoader = function ( manager ) { +class BVHLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { - this.animateBonePositions = true; - this.animateBoneRotations = true; + super( manager ); -}; + this.animateBonePositions = true; + this.animateBoneRotations = true; -BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: BVHLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var loader = new FileLoader( scope.manager ); + const loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setRequestHeader( scope.requestHeader ); loader.setWithCredentials( scope.withCredentials ); @@ -62,9 +60,9 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } - parse: function ( text ) { + parse( text ) { /* reads a string array (lines) from a BVH file @@ -83,8 +81,8 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var list = []; // collects flat array of all bones - var root = readNode( lines, nextLine( lines ), list ); + const list = []; // collects flat array of all bones + const root = readNode( lines, nextLine( lines ), list ); // read motion data @@ -96,8 +94,8 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // number of frames - var tokens = nextLine( lines ).split( /[\s]+/ ); - var numFrames = parseInt( tokens[ 1 ] ); + let tokens = nextLine( lines ).split( /[\s]+/ ); + const numFrames = parseInt( tokens[ 1 ] ); if ( isNaN( numFrames ) ) { @@ -108,7 +106,7 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // frame time tokens = nextLine( lines ).split( /[\s]+/ ); - var frameTime = parseFloat( tokens[ 2 ] ); + const frameTime = parseFloat( tokens[ 2 ] ); if ( isNaN( frameTime ) ) { @@ -118,7 +116,7 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // read frame data line by line - for ( var i = 0; i < numFrames; i ++ ) { + for ( let i = 0; i < numFrames; i ++ ) { tokens = nextLine( lines ).split( /[\s]+/ ); readFrameData( tokens, i * frameTime, root ); @@ -147,7 +145,7 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // add keyframe - var keyframe = { + const keyframe = { time: frameTime, position: new Vector3(), rotation: new Quaternion() @@ -155,15 +153,15 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { bone.frames.push( keyframe ); - var quat = new Quaternion(); + const quat = new Quaternion(); - var vx = new Vector3( 1, 0, 0 ); - var vy = new Vector3( 0, 1, 0 ); - var vz = new Vector3( 0, 0, 1 ); + const vx = new Vector3( 1, 0, 0 ); + const vy = new Vector3( 0, 1, 0 ); + const vz = new Vector3( 0, 0, 1 ); // parse values for each channel in node - for ( var i = 0; i < bone.channels.length; i ++ ) { + for ( let i = 0; i < bone.channels.length; i ++ ) { switch ( bone.channels[ i ] ) { @@ -197,7 +195,7 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // parse child nodes - for ( var i = 0; i < bone.children.length; i ++ ) { + for ( let i = 0; i < bone.children.length; i ++ ) { readFrameData( data, frameTime, bone.children[ i ] ); @@ -216,12 +214,12 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { */ function readNode( lines, firstline, list ) { - var node = { name: '', type: '', frames: [] }; + const node = { name: '', type: '', frames: [] }; list.push( node ); // parse node type and name - var tokens = firstline.split( /[\s]+/ ); + let tokens = firstline.split( /[\s]+/ ); if ( tokens[ 0 ].toUpperCase() === 'END' && tokens[ 1 ].toUpperCase() === 'SITE' ) { @@ -257,7 +255,7 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var offset = new Vector3( + const offset = new Vector3( parseFloat( tokens[ 1 ] ), parseFloat( tokens[ 2 ] ), parseFloat( tokens[ 3 ] ) @@ -283,7 +281,7 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var numChannels = parseInt( tokens[ 1 ] ); + const numChannels = parseInt( tokens[ 1 ] ); node.channels = tokens.splice( 2, numChannels ); node.children = []; @@ -293,7 +291,7 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { while ( true ) { - var line = nextLine( lines ); + const line = nextLine( lines ); if ( line === '}' ) { @@ -319,7 +317,7 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { */ function toTHREEBone( source, list ) { - var bone = new Bone(); + const bone = new Bone(); list.push( bone ); bone.position.add( source.offset ); @@ -327,7 +325,7 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( source.type !== 'ENDSITE' ) { - for ( var i = 0; i < source.children.length; i ++ ) { + for ( let i = 0; i < source.children.length; i ++ ) { bone.add( toTHREEBone( source.children[ i ], list ) ); @@ -348,26 +346,26 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { */ function toTHREEAnimation( bones ) { - var tracks = []; + const tracks = []; // create a position and quaternion animation track for each node - for ( var i = 0; i < bones.length; i ++ ) { + for ( let i = 0; i < bones.length; i ++ ) { - var bone = bones[ i ]; + const bone = bones[ i ]; if ( bone.type === 'ENDSITE' ) continue; // track data - var times = []; - var positions = []; - var rotations = []; + const times = []; + const positions = []; + const rotations = []; - for ( var j = 0; j < bone.frames.length; j ++ ) { + for ( let j = 0; j < bone.frames.length; j ++ ) { - var frame = bone.frames[ j ]; + const frame = bone.frames[ j ]; times.push( frame.time ); @@ -408,7 +406,7 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { */ function nextLine( lines ) { - var line; + let line; // skip empty lines while ( ( line = lines.shift().trim() ).length === 0 ) { } @@ -416,16 +414,16 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var scope = this; + const scope = this; - var lines = text.split( /[\r\n]+/g ); + const lines = text.split( /[\r\n]+/g ); - var bones = readBvh( lines ); + const bones = readBvh( lines ); - var threeBones = []; + const threeBones = []; toTHREEBone( bones[ 0 ], threeBones ); - var threeClip = toTHREEAnimation( bones ); + const threeClip = toTHREEAnimation( bones ); return { skeleton: new Skeleton( threeBones ), @@ -434,6 +432,6 @@ BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } -} ); +} export { BVHLoader }; diff --git a/examples/jsm/loaders/BasisTextureLoader.js b/examples/jsm/loaders/BasisTextureLoader.js index ca59ec034787c0..65e7f67278acf5 100644 --- a/examples/jsm/loaders/BasisTextureLoader.js +++ b/examples/jsm/loaders/BasisTextureLoader.js @@ -29,45 +29,44 @@ import { * of web workers, before transferring the transcoded compressed texture back * to the main thread. */ -var BasisTextureLoader = function ( manager ) { - Loader.call( this, manager ); +const _taskCache = new WeakMap(); - this.transcoderPath = ''; - this.transcoderBinary = null; - this.transcoderPending = null; +class BasisTextureLoader extends Loader { - this.workerLimit = 4; - this.workerPool = []; - this.workerNextTaskID = 1; - this.workerSourceURL = ''; - this.workerConfig = null; + constructor( manager ) { -}; + super( manager ); -BasisTextureLoader.taskCache = new WeakMap(); + this.transcoderPath = ''; + this.transcoderBinary = null; + this.transcoderPending = null; -BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + this.workerLimit = 4; + this.workerPool = []; + this.workerNextTaskID = 1; + this.workerSourceURL = ''; + this.workerConfig = null; - constructor: BasisTextureLoader, + } - setTranscoderPath: function ( path ) { + setTranscoderPath( path ) { this.transcoderPath = path; return this; - }, + } - setWorkerLimit: function ( workerLimit ) { + setWorkerLimit( workerLimit ) { this.workerLimit = workerLimit; return this; - }, + } - detectSupport: function ( renderer ) { + detectSupport( renderer ) { this.workerConfig = { astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ), @@ -81,24 +80,24 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), return this; - }, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var loader = new FileLoader( this.manager ); + const loader = new FileLoader( this.manager ); loader.setResponseType( 'arraybuffer' ); loader.setWithCredentials( this.withCredentials ); - var texture = new CompressedTexture(); + const texture = new CompressedTexture(); loader.load( url, ( buffer ) => { // Check for an existing task using this buffer. A transferred buffer cannot be transferred // again from this thread. - if ( BasisTextureLoader.taskCache.has( buffer ) ) { + if ( _taskCache.has( buffer ) ) { - var cachedTask = BasisTextureLoader.taskCache.get( buffer ); + const cachedTask = _taskCache.get( buffer ); return cachedTask.promise.then( onLoad ).catch( onError ); @@ -119,16 +118,16 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), return texture; - }, + } /** Low-level transcoding API, exposed for use by KTX2Loader. */ - parseInternalAsync: function ( options ) { + parseInternalAsync( options ) { - var { levels } = options; + const { levels } = options; - var buffers = new Set(); + const buffers = new Set(); - for ( var i = 0; i < levels.length; i ++ ) { + for ( let i = 0; i < levels.length; i ++ ) { buffers.add( levels[ i ].data.buffer ); @@ -136,28 +135,28 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), return this._createTexture( Array.from( buffers ), { ...options, lowLevel: true } ); - }, + } /** * @param {ArrayBuffer[]} buffers * @param {object?} config * @return {Promise} */ - _createTexture: function ( buffers, config ) { + _createTexture( buffers, config = {} ) { - var worker; - var taskID; + let worker; + let taskID; - var taskConfig = config || {}; - var taskCost = 0; + const taskConfig = config; + let taskCost = 0; - for ( var i = 0; i < buffers.length; i ++ ) { + for ( let i = 0; i < buffers.length; i ++ ) { taskCost += buffers[ i ].byteLength; } - var texturePending = this._allocateWorker( taskCost ) + const texturePending = this._allocateWorker( taskCost ) .then( ( _worker ) => { worker = _worker; @@ -174,9 +173,9 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), } ) .then( ( message ) => { - var { mipmaps, width, height, format } = message; + const { mipmaps, width, height, format } = message; - var texture = new CompressedTexture( mipmaps, width, height, format, UnsignedByteType ); + const texture = new CompressedTexture( mipmaps, width, height, format, UnsignedByteType ); texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; texture.magFilter = LinearFilter; texture.generateMipmaps = false; @@ -201,32 +200,32 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), } ); // Cache the task result. - BasisTextureLoader.taskCache.set( buffers[ 0 ], { promise: texturePending } ); + _taskCache.set( buffers[ 0 ], { promise: texturePending } ); return texturePending; - }, + } - _initTranscoder: function () { + _initTranscoder() { if ( ! this.transcoderPending ) { // Load transcoder wrapper. - var jsLoader = new FileLoader( this.manager ); + const jsLoader = new FileLoader( this.manager ); jsLoader.setPath( this.transcoderPath ); jsLoader.setWithCredentials( this.withCredentials ); - var jsContent = new Promise( ( resolve, reject ) => { + const jsContent = new Promise( ( resolve, reject ) => { jsLoader.load( 'basis_transcoder.js', resolve, undefined, reject ); } ); // Load transcoder WASM binary. - var binaryLoader = new FileLoader( this.manager ); + const binaryLoader = new FileLoader( this.manager ); binaryLoader.setPath( this.transcoderPath ); binaryLoader.setResponseType( 'arraybuffer' ); binaryLoader.setWithCredentials( this.withCredentials ); - var binaryContent = new Promise( ( resolve, reject ) => { + const binaryContent = new Promise( ( resolve, reject ) => { binaryLoader.load( 'basis_transcoder.wasm', resolve, undefined, reject ); @@ -235,13 +234,13 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), this.transcoderPending = Promise.all( [ jsContent, binaryContent ] ) .then( ( [ jsContent, binaryContent ] ) => { - var fn = BasisTextureLoader.BasisWorker.toString(); + const fn = BasisTextureLoader.BasisWorker.toString(); - var body = [ + const body = [ '/* constants */', - 'var _EngineFormat = ' + JSON.stringify( BasisTextureLoader.EngineFormat ), - 'var _TranscoderFormat = ' + JSON.stringify( BasisTextureLoader.TranscoderFormat ), - 'var _BasisFormat = ' + JSON.stringify( BasisTextureLoader.BasisFormat ), + 'let _EngineFormat = ' + JSON.stringify( BasisTextureLoader.EngineFormat ), + 'let _TranscoderFormat = ' + JSON.stringify( BasisTextureLoader.TranscoderFormat ), + 'let _BasisFormat = ' + JSON.stringify( BasisTextureLoader.BasisFormat ), '/* basis_transcoder.js */', jsContent, '/* worker */', @@ -257,15 +256,15 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), return this.transcoderPending; - }, + } - _allocateWorker: function ( taskCost ) { + _allocateWorker( taskCost ) { return this._initTranscoder().then( () => { if ( this.workerPool.length < this.workerLimit ) { - var worker = new Worker( this.workerSourceURL ); + const worker = new Worker( this.workerSourceURL ); worker._callbacks = {}; worker._taskLoad = 0; @@ -278,7 +277,7 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), worker.onmessage = function ( e ) { - var message = e.data; + const message = e.data; switch ( message.type ) { @@ -309,7 +308,7 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), } - var worker = this.workerPool[ this.workerPool.length - 1 ]; + const worker = this.workerPool[ this.workerPool.length - 1 ]; worker._taskLoad += taskCost; @@ -317,11 +316,11 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), } ); - }, + } - dispose: function () { + dispose() { - for ( var i = 0; i < this.workerPool.length; i ++ ) { + for ( let i = 0; i < this.workerPool.length; i ++ ) { this.workerPool[ i ].terminate(); @@ -333,7 +332,7 @@ BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), } -} ); +} /* CONSTANTS */ @@ -380,17 +379,17 @@ BasisTextureLoader.EngineFormat = { BasisTextureLoader.BasisWorker = function () { - var config; - var transcoderPending; - var BasisModule; + let config; + let transcoderPending; + let BasisModule; - var EngineFormat = _EngineFormat; // eslint-disable-line no-undef - var TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef - var BasisFormat = _BasisFormat; // eslint-disable-line no-undef + const EngineFormat = _EngineFormat; // eslint-disable-line no-undef + const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef + const BasisFormat = _BasisFormat; // eslint-disable-line no-undef onmessage = function ( e ) { - var message = e.data; + const message = e.data; switch ( message.type ) { @@ -404,13 +403,13 @@ BasisTextureLoader.BasisWorker = function () { try { - var { width, height, hasAlpha, mipmaps, format } = message.taskConfig.lowLevel + const { width, height, hasAlpha, mipmaps, format } = message.taskConfig.lowLevel ? transcodeLowLevel( message.taskConfig ) : transcode( message.buffers[ 0 ] ); - var buffers = []; + const buffers = []; - for ( var i = 0; i < mipmaps.length; ++ i ) { + for ( let i = 0; i < mipmaps.length; ++ i ) { buffers.push( mipmaps[ i ].data.buffer ); @@ -450,25 +449,25 @@ BasisTextureLoader.BasisWorker = function () { function transcodeLowLevel( taskConfig ) { - var { basisFormat, width, height, hasAlpha } = taskConfig; + const { basisFormat, width, height, hasAlpha } = taskConfig; - var { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha ); + const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha ); - var blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat ); + const blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat ); assert( BasisModule.isFormatSupported( transcoderFormat ), 'THREE.BasisTextureLoader: Unsupported format.' ); - var mipmaps = []; + const mipmaps = []; if ( basisFormat === BasisFormat.ETC1S ) { - var transcoder = new BasisModule.LowLevelETC1SImageTranscoder(); + const transcoder = new BasisModule.LowLevelETC1SImageTranscoder(); - var { endpointCount, endpointsData, selectorCount, selectorsData, tablesData } = taskConfig.globalData; + const { endpointCount, endpointsData, selectorCount, selectorsData, tablesData } = taskConfig.globalData; try { - var ok; + let ok; ok = transcoder.decodePalettes( endpointCount, endpointsData, selectorCount, selectorsData ); @@ -478,13 +477,13 @@ BasisTextureLoader.BasisWorker = function () { assert( ok, 'THREE.BasisTextureLoader: decodeTables() failed.' ); - for ( var i = 0; i < taskConfig.levels.length; i ++ ) { + for ( let i = 0; i < taskConfig.levels.length; i ++ ) { - var level = taskConfig.levels[ i ]; - var imageDesc = taskConfig.globalData.imageDescs[ i ]; + const level = taskConfig.levels[ i ]; + const imageDesc = taskConfig.globalData.imageDescs[ i ]; - var dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height ); - var dst = new Uint8Array( dstByteLength ); + const dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height ); + const dst = new Uint8Array( dstByteLength ); ok = transcoder.transcodeImage( transcoderFormat, @@ -515,14 +514,14 @@ BasisTextureLoader.BasisWorker = function () { } else { - for ( var i = 0; i < taskConfig.levels.length; i ++ ) { + for ( let i = 0; i < taskConfig.levels.length; i ++ ) { - var level = taskConfig.levels[ i ]; + const level = taskConfig.levels[ i ]; - var dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height ); - var dst = new Uint8Array( dstByteLength ); + const dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height ); + const dst = new Uint8Array( dstByteLength ); - var ok = BasisModule.transcodeUASTCImage( + const ok = BasisModule.transcodeUASTCImage( transcoderFormat, dst, dstByteLength / blockByteLength, level.data, @@ -552,13 +551,13 @@ BasisTextureLoader.BasisWorker = function () { function transcode( buffer ) { - var basisFile = new BasisModule.BasisFile( new Uint8Array( buffer ) ); + const basisFile = new BasisModule.BasisFile( new Uint8Array( buffer ) ); - var basisFormat = basisFile.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S; - var width = basisFile.getImageWidth( 0, 0 ); - var height = basisFile.getImageHeight( 0, 0 ); - var levels = basisFile.getNumLevels( 0 ); - var hasAlpha = basisFile.getHasAlpha(); + const basisFormat = basisFile.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S; + const width = basisFile.getImageWidth( 0, 0 ); + const height = basisFile.getImageHeight( 0, 0 ); + const levels = basisFile.getNumLevels( 0 ); + const hasAlpha = basisFile.getHasAlpha(); function cleanup() { @@ -567,7 +566,7 @@ BasisTextureLoader.BasisWorker = function () { } - var { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha ); + const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha ); if ( ! width || ! height || ! levels ) { @@ -583,15 +582,15 @@ BasisTextureLoader.BasisWorker = function () { } - var mipmaps = []; + const mipmaps = []; - for ( var mip = 0; mip < levels; mip ++ ) { + for ( let mip = 0; mip < levels; mip ++ ) { - var mipWidth = basisFile.getImageWidth( 0, mip ); - var mipHeight = basisFile.getImageHeight( 0, mip ); - var dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, transcoderFormat ) ); + const mipWidth = basisFile.getImageWidth( 0, mip ); + const mipHeight = basisFile.getImageHeight( 0, mip ); + const dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, transcoderFormat ) ); - var status = basisFile.transcodeImage( + const status = basisFile.transcodeImage( dst, 0, mip, @@ -626,7 +625,7 @@ BasisTextureLoader.BasisWorker = function () { // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently // chooses RGBA32 only as a last resort and does not expose that option to the caller. - var FORMAT_OPTIONS = [ + const FORMAT_OPTIONS = [ { if: 'astcSupported', basisFormat: [ BasisFormat.UASTC_4x4 ], @@ -683,12 +682,12 @@ BasisTextureLoader.BasisWorker = function () { }, ]; - var ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) { + const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) { return a.priorityETC1S - b.priorityETC1S; } ); - var UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) { + const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) { return a.priorityUASTC - b.priorityUASTC; @@ -696,14 +695,14 @@ BasisTextureLoader.BasisWorker = function () { function getTranscoderFormat( basisFormat, width, height, hasAlpha ) { - var transcoderFormat; - var engineFormat; + let transcoderFormat; + let engineFormat; - var options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; + const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; - for ( var i = 0; i < options.length; i ++ ) { + for ( let i = 0; i < options.length; i ++ ) { - var opt = options[ i ]; + const opt = options[ i ]; if ( ! config[ opt.if ] ) continue; if ( ! opt.basisFormat.includes( basisFormat ) ) continue; @@ -745,7 +744,7 @@ BasisTextureLoader.BasisWorker = function () { function getTranscodedImageByteLength( transcoderFormat, width, height ) { - var blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat ); + const blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat ); if ( BasisModule.formatIsUncompressed( transcoderFormat ) ) { @@ -758,8 +757,8 @@ BasisTextureLoader.BasisWorker = function () { // GL requires extra padding for very small textures: // https://www.khronos.org/registry/OpenGL/extensions/IMG/IMG_texture_compression_pvrtc.txt - var paddedWidth = ( width + 3 ) & ~ 3; - var paddedHeight = ( height + 3 ) & ~ 3; + const paddedWidth = ( width + 3 ) & ~ 3; + const paddedHeight = ( height + 3 ) & ~ 3; return ( Math.max( 8, paddedWidth ) * Math.max( 8, paddedHeight ) * 4 + 7 ) / 8; diff --git a/examples/jsm/loaders/ColladaLoader.js b/examples/jsm/loaders/ColladaLoader.js index be9a4749178bb0..e78ac4a14fa941 100644 --- a/examples/jsm/loaders/ColladaLoader.js +++ b/examples/jsm/loaders/ColladaLoader.js @@ -38,23 +38,21 @@ import { } from '../../../build/three.module.js'; import { TGALoader } from '../loaders/TGALoader.js'; -var ColladaLoader = function ( manager ) { +class ColladaLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { -}; + super( manager ); -ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: ColladaLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var path = ( scope.path === '' ) ? LoaderUtils.extractUrlBase( url ) : scope.path; + const path = ( scope.path === '' ) ? LoaderUtils.extractUrlBase( url ) : scope.path; - var loader = new FileLoader( scope.manager ); + const loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setRequestHeader( scope.requestHeader ); loader.setWithCredentials( scope.withCredentials ); @@ -82,30 +80,20 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, - - options: { - - set convertUpAxis( value ) { - - console.warn( 'THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.' ); - - } - - }, + } - parse: function ( text, path ) { + parse( text, path ) { function getElementsByTagName( xml, name ) { // Non recursive xml.getElementsByTagName() ... - var array = []; - var childNodes = xml.childNodes; + const array = []; + const childNodes = xml.childNodes; - for ( var i = 0, l = childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = childNodes.length; i < l; i ++ ) { - var child = childNodes[ i ]; + const child = childNodes[ i ]; if ( child.nodeName === name ) { @@ -123,10 +111,10 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( text.length === 0 ) return []; - var parts = text.trim().split( /\s+/ ); - var array = new Array( parts.length ); + const parts = text.trim().split( /\s+/ ); + const array = new Array( parts.length ); - for ( var i = 0, l = parts.length; i < l; i ++ ) { + for ( let i = 0, l = parts.length; i < l; i ++ ) { array[ i ] = parts[ i ]; @@ -140,10 +128,10 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( text.length === 0 ) return []; - var parts = text.trim().split( /\s+/ ); - var array = new Array( parts.length ); + const parts = text.trim().split( /\s+/ ); + const array = new Array( parts.length ); - for ( var i = 0, l = parts.length; i < l; i ++ ) { + for ( let i = 0, l = parts.length; i < l; i ++ ) { array[ i ] = parseFloat( parts[ i ] ); @@ -157,10 +145,10 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( text.length === 0 ) return []; - var parts = text.trim().split( /\s+/ ); - var array = new Array( parts.length ); + const parts = text.trim().split( /\s+/ ); + const array = new Array( parts.length ); - for ( var i = 0, l = parts.length; i < l; i ++ ) { + for ( let i = 0, l = parts.length; i < l; i ++ ) { array[ i ] = parseInt( parts[ i ] ); @@ -223,13 +211,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseLibrary( xml, libraryName, nodeName, parser ) { - var library = getElementsByTagName( xml, libraryName )[ 0 ]; + const library = getElementsByTagName( xml, libraryName )[ 0 ]; if ( library !== undefined ) { - var elements = getElementsByTagName( library, nodeName ); + const elements = getElementsByTagName( library, nodeName ); - for ( var i = 0; i < elements.length; i ++ ) { + for ( let i = 0; i < elements.length; i ++ ) { parser( elements[ i ] ); @@ -241,9 +229,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildLibrary( data, builder ) { - for ( var name in data ) { + for ( const name in data ) { - var object = data[ name ]; + const object = data[ name ]; object.build = builder( data[ name ] ); } @@ -266,21 +254,21 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseAnimation( xml ) { - var data = { + const data = { sources: {}, samplers: {}, channels: {} }; - var hasChildren = false; + let hasChildren = false; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; - var id; + let id; switch ( child.nodeName ) { @@ -324,21 +312,21 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseAnimationSampler( xml ) { - var data = { + const data = { inputs: {}, }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'input': - var id = parseId( child.getAttribute( 'source' ) ); - var semantic = child.getAttribute( 'semantic' ); + const id = parseId( child.getAttribute( 'source' ) ); + const semantic = child.getAttribute( 'semantic' ); data.inputs[ semantic ] = id; break; @@ -352,21 +340,21 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseAnimationChannel( xml ) { - var data = {}; + const data = {}; - var target = xml.getAttribute( 'target' ); + const target = xml.getAttribute( 'target' ); // parsing SID Addressing Syntax - var parts = target.split( '/' ); + let parts = target.split( '/' ); - var id = parts.shift(); - var sid = parts.shift(); + const id = parts.shift(); + let sid = parts.shift(); // check selection syntax - var arraySyntax = ( sid.indexOf( '(' ) !== - 1 ); - var memberSyntax = ( sid.indexOf( '.' ) !== - 1 ); + const arraySyntax = ( sid.indexOf( '(' ) !== - 1 ); + const memberSyntax = ( sid.indexOf( '.' ) !== - 1 ); if ( memberSyntax ) { @@ -380,10 +368,10 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices. - var indices = sid.split( '(' ); + const indices = sid.split( '(' ); sid = indices.shift(); - for ( var i = 0; i < indices.length; i ++ ) { + for ( let i = 0; i < indices.length; i ++ ) { indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) ); @@ -407,26 +395,26 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildAnimation( data ) { - var tracks = []; + const tracks = []; - var channels = data.channels; - var samplers = data.samplers; - var sources = data.sources; + const channels = data.channels; + const samplers = data.samplers; + const sources = data.sources; - for ( var target in channels ) { + for ( const target in channels ) { if ( channels.hasOwnProperty( target ) ) { - var channel = channels[ target ]; - var sampler = samplers[ channel.sampler ]; + const channel = channels[ target ]; + const sampler = samplers[ channel.sampler ]; - var inputId = sampler.inputs.INPUT; - var outputId = sampler.inputs.OUTPUT; + const inputId = sampler.inputs.INPUT; + const outputId = sampler.inputs.OUTPUT; - var inputSource = sources[ inputId ]; - var outputSource = sources[ outputId ]; + const inputSource = sources[ inputId ]; + const outputSource = sources[ outputId ]; - var animation = buildAnimationChannel( channel, inputSource, outputSource ); + const animation = buildAnimationChannel( channel, inputSource, outputSource ); createKeyframeTracks( animation, tracks ); @@ -446,16 +434,16 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildAnimationChannel( channel, inputSource, outputSource ) { - var node = library.nodes[ channel.id ]; - var object3D = getNode( node.id ); + const node = library.nodes[ channel.id ]; + const object3D = getNode( node.id ); - var transform = node.transforms[ channel.sid ]; - var defaultMatrix = node.matrix.clone().transpose(); + const transform = node.transforms[ channel.sid ]; + const defaultMatrix = node.matrix.clone().transpose(); - var time, stride; - var i, il, j, jl; + let time, stride; + let i, il, j, jl; - var data = {}; + const data = {}; // the collada spec allows the animation of data in various ways. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic @@ -473,8 +461,8 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( channel.arraySyntax === true ) { - var value = outputSource.array[ stride ]; - var index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ]; + const value = outputSource.array[ stride ]; + const index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ]; data[ time ][ index ] = value; @@ -506,9 +494,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var keyframes = prepareAnimationData( data, defaultMatrix ); + const keyframes = prepareAnimationData( data, defaultMatrix ); - var animation = { + const animation = { name: object3D.uuid, keyframes: keyframes }; @@ -519,11 +507,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function prepareAnimationData( data, defaultMatrix ) { - var keyframes = []; + const keyframes = []; // transfer data into a sortable array - for ( var time in data ) { + for ( const time in data ) { keyframes.push( { time: parseFloat( time ), value: data[ time ] } ); @@ -535,7 +523,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // now we clean up all animation data, so we can use them for keyframe tracks - for ( var i = 0; i < 16; i ++ ) { + for ( let i = 0; i < 16; i ++ ) { transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] ); @@ -553,26 +541,26 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var position = new Vector3(); - var scale = new Vector3(); - var quaternion = new Quaternion(); + const position = new Vector3(); + const scale = new Vector3(); + const quaternion = new Quaternion(); function createKeyframeTracks( animation, tracks ) { - var keyframes = animation.keyframes; - var name = animation.name; + const keyframes = animation.keyframes; + const name = animation.name; - var times = []; - var positionData = []; - var quaternionData = []; - var scaleData = []; + const times = []; + const positionData = []; + const quaternionData = []; + const scaleData = []; - for ( var i = 0, l = keyframes.length; i < l; i ++ ) { + for ( let i = 0, l = keyframes.length; i < l; i ++ ) { - var keyframe = keyframes[ i ]; + const keyframe = keyframes[ i ]; - var time = keyframe.time; - var value = keyframe.value; + const time = keyframe.time; + const value = keyframe.value; matrix.fromArray( value ).transpose(); matrix.decompose( position, quaternion, scale ); @@ -594,10 +582,10 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function transformAnimationData( keyframes, property, defaultValue ) { - var keyframe; + let keyframe; - var empty = true; - var i, l; + let empty = true; + let i, l; // check, if values of a property are missing in our keyframes @@ -641,11 +629,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function createMissingKeyframes( keyframes, property ) { - var prev, next; + let prev, next; - for ( var i = 0, l = keyframes.length; i < l; i ++ ) { + for ( let i = 0, l = keyframes.length; i < l; i ++ ) { - var keyframe = keyframes[ i ]; + const keyframe = keyframes[ i ]; if ( keyframe.value[ property ] === null ) { @@ -678,7 +666,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { while ( i >= 0 ) { - var keyframe = keyframes[ i ]; + const keyframe = keyframes[ i ]; if ( keyframe.value[ property ] !== null ) return keyframe; @@ -694,7 +682,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { while ( i < keyframes.length ) { - var keyframe = keyframes[ i ]; + const keyframe = keyframes[ i ]; if ( keyframe.value[ property ] !== null ) return keyframe; @@ -723,16 +711,16 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseAnimationClip( xml ) { - var data = { + const data = { name: xml.getAttribute( 'id' ) || 'default', start: parseFloat( xml.getAttribute( 'start' ) || 0 ), end: parseFloat( xml.getAttribute( 'end' ) || 0 ), animations: [] }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -752,17 +740,17 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildAnimationClip( data ) { - var tracks = []; + const tracks = []; - var name = data.name; - var duration = ( data.end - data.start ) || - 1; - var animations = data.animations; + const name = data.name; + const duration = ( data.end - data.start ) || - 1; + const animations = data.animations; - for ( var i = 0, il = animations.length; i < il; i ++ ) { + for ( let i = 0, il = animations.length; i < il; i ++ ) { - var animationTracks = getAnimation( animations[ i ] ); + const animationTracks = getAnimation( animations[ i ] ); - for ( var j = 0, jl = animationTracks.length; j < jl; j ++ ) { + for ( let j = 0, jl = animationTracks.length; j < jl; j ++ ) { tracks.push( animationTracks[ j ] ); @@ -784,11 +772,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseController( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -815,13 +803,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseSkin( xml ) { - var data = { + const data = { sources: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -832,7 +820,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { break; case 'source': - var id = child.getAttribute( 'id' ); + const id = child.getAttribute( 'id' ); data.sources[ id ] = parseSource( child ); break; @@ -854,21 +842,21 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseJoints( xml ) { - var data = { + const data = { inputs: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'input': - var semantic = child.getAttribute( 'semantic' ); - var id = parseId( child.getAttribute( 'source' ) ); + const semantic = child.getAttribute( 'semantic' ); + const id = parseId( child.getAttribute( 'source' ) ); data.inputs[ semantic ] = id; break; @@ -882,22 +870,22 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseVertexWeights( xml ) { - var data = { + const data = { inputs: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'input': - var semantic = child.getAttribute( 'semantic' ); - var id = parseId( child.getAttribute( 'source' ) ); - var offset = parseInt( child.getAttribute( 'offset' ) ); + const semantic = child.getAttribute( 'semantic' ); + const id = parseId( child.getAttribute( 'source' ) ); + const offset = parseInt( child.getAttribute( 'offset' ) ); data.inputs[ semantic ] = { id: id, offset: offset }; break; @@ -919,11 +907,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildController( data ) { - var build = { + const build = { id: data.id }; - var geometry = library.geometries[ build.id ]; + const geometry = library.geometries[ build.id ]; if ( data.skin !== undefined ) { @@ -942,9 +930,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildSkin( data ) { - var BONE_LIMIT = 4; + const BONE_LIMIT = 4; - var build = { + const build = { joints: [], // this must be an array to preserve the joint order indices: { array: [], @@ -956,34 +944,34 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } }; - var sources = data.sources; - var vertexWeights = data.vertexWeights; + const sources = data.sources; + const vertexWeights = data.vertexWeights; - var vcount = vertexWeights.vcount; - var v = vertexWeights.v; - var jointOffset = vertexWeights.inputs.JOINT.offset; - var weightOffset = vertexWeights.inputs.WEIGHT.offset; + const vcount = vertexWeights.vcount; + const v = vertexWeights.v; + const jointOffset = vertexWeights.inputs.JOINT.offset; + const weightOffset = vertexWeights.inputs.WEIGHT.offset; - var jointSource = data.sources[ data.joints.inputs.JOINT ]; - var inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ]; + const jointSource = data.sources[ data.joints.inputs.JOINT ]; + const inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ]; - var weights = sources[ vertexWeights.inputs.WEIGHT.id ].array; - var stride = 0; + const weights = sources[ vertexWeights.inputs.WEIGHT.id ].array; + let stride = 0; - var i, j, l; + let i, j, l; // procces skin data for each vertex for ( i = 0, l = vcount.length; i < l; i ++ ) { - var jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex - var vertexSkinData = []; + const jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex + const vertexSkinData = []; for ( j = 0; j < jointCount; j ++ ) { - var skinIndex = v[ stride + jointOffset ]; - var weightId = v[ stride + weightOffset ]; - var skinWeight = weights[ weightId ]; + const skinIndex = v[ stride + jointOffset ]; + const weightId = v[ stride + weightOffset ]; + const skinWeight = weights[ weightId ]; vertexSkinData.push( { index: skinIndex, weight: skinWeight } ); @@ -1001,7 +989,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { for ( j = 0; j < BONE_LIMIT; j ++ ) { - var d = vertexSkinData[ j ]; + const d = vertexSkinData[ j ]; if ( d !== undefined ) { @@ -1035,8 +1023,8 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { for ( i = 0, l = jointSource.array.length; i < l; i ++ ) { - var name = jointSource.array[ i ]; - var boneInverse = new Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose(); + const name = jointSource.array[ i ]; + const boneInverse = new Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose(); build.joints.push( { name: name, boneInverse: boneInverse } ); @@ -1064,7 +1052,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseImage( xml ) { - var data = { + const data = { init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent }; @@ -1082,7 +1070,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function getImage( id ) { - var data = library.images[ id ]; + const data = library.images[ id ]; if ( data !== undefined ) { @@ -1100,11 +1088,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffect( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1124,14 +1112,14 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectProfileCOMMON( xml ) { - var data = { + const data = { surfaces: {}, samplers: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1159,11 +1147,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectNewparam( xml, data ) { - var sid = xml.getAttribute( 'sid' ); + const sid = xml.getAttribute( 'sid' ); - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1185,11 +1173,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectSurface( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1209,11 +1197,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectSampler( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1233,11 +1221,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectTechnique( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1261,11 +1249,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectParameters( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1297,11 +1285,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectParameter( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1329,13 +1317,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectParameterTexture( xml ) { - var data = { + const data = { technique: {} }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1355,9 +1343,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectParameterTextureExtra( xml, data ) { - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1375,9 +1363,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectParameterTextureExtraTechnique( xml, data ) { - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1419,11 +1407,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectExtra( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1443,11 +1431,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseEffectExtraTechnique( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1481,13 +1469,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseMaterial( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ) }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1507,9 +1495,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function getTextureLoader( image ) { - var loader; + let loader; - var extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/ + let extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/ extension = extension.toLowerCase(); switch ( extension ) { @@ -1529,11 +1517,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildMaterial( data ) { - var effect = getEffect( data.url ); - var technique = effect.profile.technique; - var extra = effect.profile.extra; + const effect = getEffect( data.url ); + const technique = effect.profile.technique; + const extra = effect.profile.extra; - var material; + let material; switch ( technique.type ) { @@ -1556,14 +1544,14 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function getTexture( textureObject ) { - var sampler = effect.profile.samplers[ textureObject.id ]; - var image = null; + const sampler = effect.profile.samplers[ textureObject.id ]; + let image = null; // get image if ( sampler !== undefined ) { - var surface = effect.profile.surfaces[ sampler.source ]; + const surface = effect.profile.surfaces[ sampler.source ]; image = getImage( surface.init_from ); } else { @@ -1577,17 +1565,17 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( image !== null ) { - var loader = getTextureLoader( image ); + const loader = getTextureLoader( image ); if ( loader !== undefined ) { - var texture = loader.load( image ); + const texture = loader.load( image ); - var extra = textureObject.extra; + const extra = textureObject.extra; if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) { - var technique = extra.technique; + const technique = extra.technique; texture.wrapS = technique.wrapU ? RepeatWrapping : ClampToEdgeWrapping; texture.wrapT = technique.wrapV ? RepeatWrapping : ClampToEdgeWrapping; @@ -1622,11 +1610,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var parameters = technique.parameters; + const parameters = technique.parameters; - for ( var key in parameters ) { + for ( const key in parameters ) { - var parameter = parameters[ key ]; + const parameter = parameters[ key ]; switch ( key ) { @@ -1658,8 +1646,8 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // - var transparent = parameters[ 'transparent' ]; - var transparency = parameters[ 'transparency' ]; + let transparent = parameters[ 'transparent' ]; + let transparency = parameters[ 'transparency' ]; // does not exist but @@ -1695,7 +1683,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else { - var color = transparent.data.color; + const color = transparent.data.color; switch ( transparent.opaque ) { @@ -1744,13 +1732,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseCamera( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ) }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1770,9 +1758,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseCameraOptics( xml ) { - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; switch ( child.nodeName ) { @@ -1789,11 +1777,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseCameraTechnique( xml ) { - var data = {}; + const data = {}; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; switch ( child.nodeName ) { @@ -1815,11 +1803,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseCameraParameters( xml ) { - var data = {}; + const data = {}; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; switch ( child.nodeName ) { @@ -1843,7 +1831,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildCamera( data ) { - var camera; + let camera; switch ( data.optics.technique ) { @@ -1857,9 +1845,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { break; case 'orthographic': - var ymag = data.optics.parameters.ymag; - var xmag = data.optics.parameters.xmag; - var aspectRatio = data.optics.parameters.aspect_ratio; + let ymag = data.optics.parameters.ymag; + let xmag = data.optics.parameters.xmag; + const aspectRatio = data.optics.parameters.aspect_ratio; xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag; ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag; @@ -1888,7 +1876,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function getCamera( id ) { - var data = library.cameras[ id ]; + const data = library.cameras[ id ]; if ( data !== undefined ) { @@ -1906,11 +1894,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseLight( xml ) { - var data = {}; + let data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1930,11 +1918,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseLightTechnique( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -1958,18 +1946,18 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseLightParameters( xml ) { - var data = {}; + const data = {}; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'color': - var array = parseFloats( child.textContent ); + const array = parseFloats( child.textContent ); data.color = new Color().fromArray( array ); break; @@ -1978,7 +1966,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { break; case 'quadratic_attenuation': - var f = parseFloat( child.textContent ); + const f = parseFloat( child.textContent ); data.distance = f ? Math.sqrt( 1 / f ) : 0; break; @@ -1992,7 +1980,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildLight( data ) { - var light; + let light; switch ( data.technique ) { @@ -2023,7 +2011,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function getLight( id ) { - var data = library.lights[ id ]; + const data = library.lights[ id ]; if ( data !== undefined ) { @@ -2041,25 +2029,25 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseGeometry( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ), sources: {}, vertices: {}, primitives: [] }; - var mesh = getElementsByTagName( xml, 'mesh' )[ 0 ]; + const mesh = getElementsByTagName( xml, 'mesh' )[ 0 ]; // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep if ( mesh === undefined ) return; - for ( var i = 0; i < mesh.childNodes.length; i ++ ) { + for ( let i = 0; i < mesh.childNodes.length; i ++ ) { - var child = mesh.childNodes[ i ]; + const child = mesh.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; - var id = child.getAttribute( 'id' ); + const id = child.getAttribute( 'id' ); switch ( child.nodeName ) { @@ -2096,14 +2084,14 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseSource( xml ) { - var data = { + const data = { array: [], stride: 3 }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2118,7 +2106,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { break; case 'technique_common': - var accessor = getElementsByTagName( child, 'accessor' )[ 0 ]; + const accessor = getElementsByTagName( child, 'accessor' )[ 0 ]; if ( accessor !== undefined ) { @@ -2138,11 +2126,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseGeometryVertices( xml ) { - var data = {}; + const data = {}; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2156,7 +2144,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseGeometryPrimitive( xml ) { - var primitive = { + const primitive = { type: xml.nodeName, material: xml.getAttribute( 'material' ), count: parseInt( xml.getAttribute( 'count' ) ), @@ -2165,20 +2153,20 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { hasUV: false }; - for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) { + for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'input': - var id = parseId( child.getAttribute( 'source' ) ); - var semantic = child.getAttribute( 'semantic' ); - var offset = parseInt( child.getAttribute( 'offset' ) ); - var set = parseInt( child.getAttribute( 'set' ) ); - var inputname = ( set > 0 ? semantic + set : semantic ); + const id = parseId( child.getAttribute( 'source' ) ); + const semantic = child.getAttribute( 'semantic' ); + const offset = parseInt( child.getAttribute( 'offset' ) ); + const set = parseInt( child.getAttribute( 'set' ) ); + const inputname = ( set > 0 ? semantic + set : semantic ); primitive.inputs[ inputname ] = { id: id, offset: offset }; primitive.stride = Math.max( primitive.stride, offset + 1 ); if ( semantic === 'TEXCOORD' ) primitive.hasUV = true; @@ -2202,11 +2190,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function groupPrimitives( primitives ) { - var build = {}; + const build = {}; - for ( var i = 0; i < primitives.length; i ++ ) { + for ( let i = 0; i < primitives.length; i ++ ) { - var primitive = primitives[ i ]; + const primitive = primitives[ i ]; if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = []; @@ -2220,11 +2208,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function checkUVCoordinates( primitives ) { - var count = 0; + let count = 0; - for ( var i = 0, l = primitives.length; i < l; i ++ ) { + for ( let i = 0, l = primitives.length; i < l; i ++ ) { - var primitive = primitives[ i ]; + const primitive = primitives[ i ]; if ( primitive.hasUV === true ) { @@ -2244,22 +2232,22 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildGeometry( data ) { - var build = {}; + const build = {}; - var sources = data.sources; - var vertices = data.vertices; - var primitives = data.primitives; + const sources = data.sources; + const vertices = data.vertices; + const primitives = data.primitives; if ( primitives.length === 0 ) return {}; // our goal is to create one buffer geometry for a single type of primitives // first, we group all primitives by their type - var groupedPrimitives = groupPrimitives( primitives ); + const groupedPrimitives = groupPrimitives( primitives ); - for ( var type in groupedPrimitives ) { + for ( const type in groupedPrimitives ) { - var primitiveType = groupedPrimitives[ type ]; + const primitiveType = groupedPrimitives[ type ]; // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines) @@ -2277,31 +2265,31 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildGeometryType( primitives, sources, vertices ) { - var build = {}; + const build = {}; - var position = { array: [], stride: 0 }; - var normal = { array: [], stride: 0 }; - var uv = { array: [], stride: 0 }; - var uv2 = { array: [], stride: 0 }; - var color = { array: [], stride: 0 }; + const position = { array: [], stride: 0 }; + const normal = { array: [], stride: 0 }; + const uv = { array: [], stride: 0 }; + const uv2 = { array: [], stride: 0 }; + const color = { array: [], stride: 0 }; - var skinIndex = { array: [], stride: 4 }; - var skinWeight = { array: [], stride: 4 }; + const skinIndex = { array: [], stride: 4 }; + const skinWeight = { array: [], stride: 4 }; - var geometry = new BufferGeometry(); + const geometry = new BufferGeometry(); - var materialKeys = []; + const materialKeys = []; - var start = 0; + let start = 0; - for ( var p = 0; p < primitives.length; p ++ ) { + for ( let p = 0; p < primitives.length; p ++ ) { - var primitive = primitives[ p ]; - var inputs = primitive.inputs; + const primitive = primitives[ p ]; + const inputs = primitive.inputs; // groups - var count = 0; + let count = 0; switch ( primitive.type ) { @@ -2316,9 +2304,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { case 'polylist': - for ( var g = 0; g < primitive.count; g ++ ) { + for ( let g = 0; g < primitive.count; g ++ ) { - var vc = primitive.vcount[ g ]; + const vc = primitive.vcount[ g ]; switch ( vc ) { @@ -2358,21 +2346,21 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // geometry data - for ( var name in inputs ) { + for ( const name in inputs ) { - var input = inputs[ name ]; + const input = inputs[ name ]; switch ( name ) { case 'VERTEX': - for ( var key in vertices ) { + for ( const key in vertices ) { - var id = vertices[ key ]; + const id = vertices[ key ]; switch ( key ) { case 'POSITION': - var prevLength = position.array.length; + const prevLength = position.array.length; buildGeometryData( primitive, sources[ id ], input.offset, position.array ); position.stride = sources[ id ].stride; @@ -2387,9 +2375,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) { - var count = ( position.array.length - prevLength ) / position.stride; + const count = ( position.array.length - prevLength ) / position.stride; - for ( var i = 0; i < count; i ++ ) { + for ( let i = 0; i < count; i ++ ) { // fill missing uv coordinates @@ -2477,14 +2465,14 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildGeometryData( primitive, source, offset, array ) { - var indices = primitive.p; - var stride = primitive.stride; - var vcount = primitive.vcount; + const indices = primitive.p; + const stride = primitive.stride; + const vcount = primitive.vcount; function pushVector( i ) { - var index = indices[ i + offset ] * sourceStride; - var length = index + sourceStride; + let index = indices[ i + offset ] * sourceStride; + const length = index + sourceStride; for ( ; index < length; index ++ ) { @@ -2494,42 +2482,42 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var sourceArray = source.array; - var sourceStride = source.stride; + const sourceArray = source.array; + const sourceStride = source.stride; if ( primitive.vcount !== undefined ) { - var index = 0; + let index = 0; - for ( var i = 0, l = vcount.length; i < l; i ++ ) { + for ( let i = 0, l = vcount.length; i < l; i ++ ) { - var count = vcount[ i ]; + const count = vcount[ i ]; if ( count === 4 ) { - var a = index + stride * 0; - var b = index + stride * 1; - var c = index + stride * 2; - var d = index + stride * 3; + const a = index + stride * 0; + const b = index + stride * 1; + const c = index + stride * 2; + const d = index + stride * 3; pushVector( a ); pushVector( b ); pushVector( d ); pushVector( b ); pushVector( c ); pushVector( d ); } else if ( count === 3 ) { - var a = index + stride * 0; - var b = index + stride * 1; - var c = index + stride * 2; + const a = index + stride * 0; + const b = index + stride * 1; + const c = index + stride * 2; pushVector( a ); pushVector( b ); pushVector( c ); } else if ( count > 4 ) { - for ( var k = 1, kl = ( count - 2 ); k <= kl; k ++ ) { + for ( let k = 1, kl = ( count - 2 ); k <= kl; k ++ ) { - var a = index + stride * 0; - var b = index + stride * k; - var c = index + stride * ( k + 1 ); + const a = index + stride * 0; + const b = index + stride * k; + const c = index + stride * ( k + 1 ); pushVector( a ); pushVector( b ); pushVector( c ); @@ -2543,7 +2531,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else { - for ( var i = 0, l = indices.length; i < l; i += stride ) { + for ( let i = 0, l = indices.length; i < l; i += stride ) { pushVector( i ); @@ -2563,15 +2551,15 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseKinematicsModel( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ) || '', joints: {}, links: [] }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2605,9 +2593,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseKinematicsTechniqueCommon( xml, data ) { - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2629,11 +2617,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseKinematicsJoint( xml ) { - var data; + let data; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2652,9 +2640,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - function parseKinematicsJointParameter( xml, data ) { + function parseKinematicsJointParameter( xml ) { - var data = { + const data = { sid: xml.getAttribute( 'sid' ), name: xml.getAttribute( 'name' ) || '', axis: new Vector3(), @@ -2668,21 +2656,21 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { middlePosition: 0 }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'axis': - var array = parseFloats( child.textContent ); + const array = parseFloats( child.textContent ); data.axis.fromArray( array ); break; case 'limits': - var max = child.getElementsByTagName( 'max' )[ 0 ]; - var min = child.getElementsByTagName( 'min' )[ 0 ]; + const max = child.getElementsByTagName( 'max' )[ 0 ]; + const min = child.getElementsByTagName( 'min' )[ 0 ]; data.limits.max = parseFloat( max.textContent ); data.limits.min = parseFloat( min.textContent ); @@ -2710,16 +2698,16 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseKinematicsLink( xml ) { - var data = { + const data = { sid: xml.getAttribute( 'sid' ), name: xml.getAttribute( 'name' ) || '', attachments: [], transforms: [] }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2745,15 +2733,15 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseKinematicsAttachment( xml ) { - var data = { + const data = { joint: xml.getAttribute( 'joint' ).split( '/' ).pop(), transforms: [], links: [] }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2779,11 +2767,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseKinematicsTransform( xml ) { - var data = { + const data = { type: xml.nodeName }; - var array = parseFloats( xml.textContent ); + const array = parseFloats( xml.textContent ); switch ( data.type ) { @@ -2813,14 +2801,14 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parsePhysicsModel( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ) || '', rigidBodies: {} }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2841,9 +2829,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parsePhysicsRigidBody( xml, data ) { - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2861,9 +2849,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parsePhysicsTechniqueCommon( xml, data ) { - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2887,13 +2875,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseKinematicsScene( xml ) { - var data = { + const data = { bindJointAxis: [] }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; @@ -2913,22 +2901,22 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseKinematicsBindJointAxis( xml ) { - var data = { + const data = { target: xml.getAttribute( 'target' ).split( '/' ).pop() }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'axis': - var param = child.getElementsByTagName( 'param' )[ 0 ]; + const param = child.getElementsByTagName( 'param' )[ 0 ]; data.axis = param.textContent; - var tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ]; + const tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ]; data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 ); break; @@ -2956,32 +2944,32 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function setupKinematics() { - var kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ]; - var kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ]; - var visualSceneId = Object.keys( library.visualScenes )[ 0 ]; + const kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ]; + const kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ]; + const visualSceneId = Object.keys( library.visualScenes )[ 0 ]; if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return; - var kinematicsModel = getKinematicsModel( kinematicsModelId ); - var kinematicsScene = getKinematicsScene( kinematicsSceneId ); - var visualScene = getVisualScene( visualSceneId ); + const kinematicsModel = getKinematicsModel( kinematicsModelId ); + const kinematicsScene = getKinematicsScene( kinematicsSceneId ); + const visualScene = getVisualScene( visualSceneId ); - var bindJointAxis = kinematicsScene.bindJointAxis; - var jointMap = {}; + const bindJointAxis = kinematicsScene.bindJointAxis; + const jointMap = {}; - for ( var i = 0, l = bindJointAxis.length; i < l; i ++ ) { + for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) { - var axis = bindJointAxis[ i ]; + const axis = bindJointAxis[ i ]; // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix' - var targetElement = collada.querySelector( '[sid="' + axis.target + '"]' ); + const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' ); if ( targetElement ) { // get the parent of the transform element - var parentVisualElement = targetElement.parentElement; + const parentVisualElement = targetElement.parentElement; // connect the joint of the kinematics model with the element in the visual scene @@ -2993,8 +2981,8 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function connect( jointIndex, visualElement ) { - var visualElementName = visualElement.getAttribute( 'name' ); - var joint = kinematicsModel.joints[ jointIndex ]; + const visualElementName = visualElement.getAttribute( 'name' ); + const joint = kinematicsModel.joints[ jointIndex ]; visualScene.traverse( function ( object ) { @@ -3013,7 +3001,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var m0 = new Matrix4(); + const m0 = new Matrix4(); kinematics = { @@ -3021,7 +3009,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { getJointValue: function ( jointIndex ) { - var jointData = jointMap[ jointIndex ]; + const jointData = jointMap[ jointIndex ]; if ( jointData ) { @@ -3037,11 +3025,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { setJointValue: function ( jointIndex, value ) { - var jointData = jointMap[ jointIndex ]; + const jointData = jointMap[ jointIndex ]; if ( jointData ) { - var joint = jointData.joint; + const joint = jointData.joint; if ( value > joint.limits.max || value < joint.limits.min ) { @@ -3053,17 +3041,17 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else { - var object = jointData.object; - var axis = joint.axis; - var transforms = jointData.transforms; + const object = jointData.object; + const axis = joint.axis; + const transforms = jointData.transforms; matrix.identity(); // each update, we have to apply all transforms in the correct order - for ( var i = 0; i < transforms.length; i ++ ) { + for ( let i = 0; i < transforms.length; i ++ ) { - var transform = transforms[ i ]; + const transform = transforms[ i ]; // if there is a connection of the transform node with a joint, apply the joint value @@ -3132,21 +3120,23 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildTransformList( node ) { - var transforms = []; + const transforms = []; - var xml = collada.querySelector( '[id="' + node.id + '"]' ); + const xml = collada.querySelector( '[id="' + node.id + '"]' ); - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; + let array, vector; + switch ( child.nodeName ) { case 'matrix': - var array = parseFloats( child.textContent ); - var matrix = new Matrix4().fromArray( array ).transpose(); + array = parseFloats( child.textContent ); + const matrix = new Matrix4().fromArray( array ).transpose(); transforms.push( { sid: child.getAttribute( 'sid' ), type: child.nodeName, @@ -3156,8 +3146,8 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { case 'translate': case 'scale': - var array = parseFloats( child.textContent ); - var vector = new Vector3().fromArray( array ); + array = parseFloats( child.textContent ); + vector = new Vector3().fromArray( array ); transforms.push( { sid: child.getAttribute( 'sid' ), type: child.nodeName, @@ -3166,9 +3156,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { break; case 'rotate': - var array = parseFloats( child.textContent ); - var vector = new Vector3().fromArray( array ); - var angle = MathUtils.degToRad( array[ 3 ] ); + array = parseFloats( child.textContent ); + vector = new Vector3().fromArray( array ); + const angle = MathUtils.degToRad( array[ 3 ] ); transforms.push( { sid: child.getAttribute( 'sid' ), type: child.nodeName, @@ -3189,13 +3179,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function prepareNodes( xml ) { - var elements = xml.getElementsByTagName( 'node' ); + const elements = xml.getElementsByTagName( 'node' ); // ensure all node elements have id attributes - for ( var i = 0; i < elements.length; i ++ ) { + for ( let i = 0; i < elements.length; i ++ ) { - var element = elements[ i ]; + const element = elements[ i ]; if ( element.hasAttribute( 'id' ) === false ) { @@ -3207,12 +3197,12 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var matrix = new Matrix4(); - var vector = new Vector3(); + const matrix = new Matrix4(); + const vector = new Vector3(); function parseNode( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ) || '', type: xml.getAttribute( 'type' ), id: xml.getAttribute( 'id' ), @@ -3227,12 +3217,14 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { transforms: {} }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; + let array; + switch ( child.nodeName ) { case 'node': @@ -3261,27 +3253,27 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { break; case 'matrix': - var array = parseFloats( child.textContent ); + array = parseFloats( child.textContent ); data.matrix.multiply( matrix.fromArray( array ).transpose() ); data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName; break; case 'translate': - var array = parseFloats( child.textContent ); + array = parseFloats( child.textContent ); vector.fromArray( array ); data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) ); data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName; break; case 'rotate': - var array = parseFloats( child.textContent ); - var angle = MathUtils.degToRad( array[ 3 ] ); + array = parseFloats( child.textContent ); + const angle = MathUtils.degToRad( array[ 3 ] ); data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) ); data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName; break; case 'scale': - var array = parseFloats( child.textContent ); + array = parseFloats( child.textContent ); data.matrix.scale( vector.fromArray( array ) ); data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName; break; @@ -3312,26 +3304,26 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseNodeInstance( xml ) { - var data = { + const data = { id: parseId( xml.getAttribute( 'url' ) ), materials: {}, skeletons: [] }; - for ( var i = 0; i < xml.childNodes.length; i ++ ) { + for ( let i = 0; i < xml.childNodes.length; i ++ ) { - var child = xml.childNodes[ i ]; + const child = xml.childNodes[ i ]; switch ( child.nodeName ) { case 'bind_material': - var instances = child.getElementsByTagName( 'instance_material' ); + const instances = child.getElementsByTagName( 'instance_material' ); - for ( var j = 0; j < instances.length; j ++ ) { + for ( let j = 0; j < instances.length; j ++ ) { - var instance = instances[ j ]; - var symbol = instance.getAttribute( 'symbol' ); - var target = instance.getAttribute( 'target' ); + const instance = instances[ j ]; + const symbol = instance.getAttribute( 'symbol' ); + const target = instance.getAttribute( 'target' ); data.materials[ symbol ] = parseId( target ); @@ -3356,19 +3348,19 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildSkeleton( skeletons, joints ) { - var boneData = []; - var sortedBoneData = []; + const boneData = []; + const sortedBoneData = []; - var i, j, data; + let i, j, data; // a skeleton can have multiple root bones. collada expresses this // situtation with multiple "skeleton" tags per controller instance for ( i = 0; i < skeletons.length; i ++ ) { - var skeleton = skeletons[ i ]; + const skeleton = skeletons[ i ]; - var root; + let root; if ( hasNode( skeleton ) ) { @@ -3379,16 +3371,16 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // handle case where the skeleton refers to the visual scene (#13335) - var visualScene = library.visualScenes[ skeleton ]; - var children = visualScene.children; + const visualScene = library.visualScenes[ skeleton ]; + const children = visualScene.children; - for ( var j = 0; j < children.length; j ++ ) { + for ( let j = 0; j < children.length; j ++ ) { - var child = children[ j ]; + const child = children[ j ]; if ( child.type === 'JOINT' ) { - var root = getNode( child.id ); + const root = getNode( child.id ); buildBoneHierarchy( root, joints, boneData ); } @@ -3440,8 +3432,8 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // setup arrays for skeleton creation - var bones = []; - var boneInverses = []; + const bones = []; + const boneInverses = []; for ( i = 0; i < sortedBoneData.length; i ++ ) { @@ -3464,13 +3456,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( object.isBone === true ) { - var boneInverse; + let boneInverse; // retrieve the boneInverse from the controller data - for ( var i = 0; i < joints.length; i ++ ) { + for ( let i = 0; i < joints.length; i ++ ) { - var joint = joints[ i ]; + const joint = joints[ i ]; if ( joint.name === object.name ) { @@ -3503,20 +3495,20 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildNode( data ) { - var objects = []; + const objects = []; - var matrix = data.matrix; - var nodes = data.nodes; - var type = data.type; - var instanceCameras = data.instanceCameras; - var instanceControllers = data.instanceControllers; - var instanceLights = data.instanceLights; - var instanceGeometries = data.instanceGeometries; - var instanceNodes = data.instanceNodes; + const matrix = data.matrix; + const nodes = data.nodes; + const type = data.type; + const instanceCameras = data.instanceCameras; + const instanceControllers = data.instanceControllers; + const instanceLights = data.instanceLights; + const instanceGeometries = data.instanceGeometries; + const instanceNodes = data.instanceNodes; // nodes - for ( var i = 0, l = nodes.length; i < l; i ++ ) { + for ( let i = 0, l = nodes.length; i < l; i ++ ) { objects.push( getNode( nodes[ i ] ) ); @@ -3524,9 +3516,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // instance cameras - for ( var i = 0, l = instanceCameras.length; i < l; i ++ ) { + for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) { - var instanceCamera = getCamera( instanceCameras[ i ] ); + const instanceCamera = getCamera( instanceCameras[ i ] ); if ( instanceCamera !== null ) { @@ -3538,21 +3530,21 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // instance controllers - for ( var i = 0, l = instanceControllers.length; i < l; i ++ ) { + for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) { - var instance = instanceControllers[ i ]; - var controller = getController( instance.id ); - var geometries = getGeometry( controller.id ); - var newObjects = buildObjects( geometries, instance.materials ); + const instance = instanceControllers[ i ]; + const controller = getController( instance.id ); + const geometries = getGeometry( controller.id ); + const newObjects = buildObjects( geometries, instance.materials ); - var skeletons = instance.skeletons; - var joints = controller.skin.joints; + const skeletons = instance.skeletons; + const joints = controller.skin.joints; - var skeleton = buildSkeleton( skeletons, joints ); + const skeleton = buildSkeleton( skeletons, joints ); - for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) { + for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) { - var object = newObjects[ j ]; + const object = newObjects[ j ]; if ( object.isSkinnedMesh ) { @@ -3569,9 +3561,9 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // instance lights - for ( var i = 0, l = instanceLights.length; i < l; i ++ ) { + for ( let i = 0, l = instanceLights.length; i < l; i ++ ) { - var instanceLight = getLight( instanceLights[ i ] ); + const instanceLight = getLight( instanceLights[ i ] ); if ( instanceLight !== null ) { @@ -3583,17 +3575,17 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // instance geometries - for ( var i = 0, l = instanceGeometries.length; i < l; i ++ ) { + for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) { - var instance = instanceGeometries[ i ]; + const instance = instanceGeometries[ i ]; // a single geometry instance in collada can lead to multiple object3Ds. // this is the case when primitives are combined like triangles and lines - var geometries = getGeometry( instance.id ); - var newObjects = buildObjects( geometries, instance.materials ); + const geometries = getGeometry( instance.id ); + const newObjects = buildObjects( geometries, instance.materials ); - for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) { + for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) { objects.push( newObjects[ j ] ); @@ -3603,13 +3595,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // instance nodes - for ( var i = 0, l = instanceNodes.length; i < l; i ++ ) { + for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) { objects.push( getNode( instanceNodes[ i ] ).clone() ); } - var object; + let object; if ( nodes.length === 0 && objects.length === 1 ) { @@ -3619,7 +3611,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { object = ( type === 'JOINT' ) ? new Bone() : new Group(); - for ( var i = 0; i < objects.length; i ++ ) { + for ( let i = 0; i < objects.length; i ++ ) { object.add( objects[ i ] ); @@ -3635,15 +3627,15 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var fallbackMaterial = new MeshBasicMaterial( { color: 0xff00ff } ); + const fallbackMaterial = new MeshBasicMaterial( { color: 0xff00ff } ); function resolveMaterialBinding( keys, instanceMaterials ) { - var materials = []; + const materials = []; - for ( var i = 0, l = keys.length; i < l; i ++ ) { + for ( let i = 0, l = keys.length; i < l; i ++ ) { - var id = instanceMaterials[ keys[ i ] ]; + const id = instanceMaterials[ keys[ i ] ]; if ( id === undefined ) { @@ -3664,13 +3656,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildObjects( geometries, instanceMaterials ) { - var objects = []; + const objects = []; - for ( var type in geometries ) { + for ( const type in geometries ) { - var geometry = geometries[ type ]; + const geometry = geometries[ type ]; - var materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials ); + const materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials ); // handle case if no materials are defined @@ -3690,11 +3682,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // regard skinning - var skinning = ( geometry.data.attributes.skinIndex !== undefined ); + const skinning = ( geometry.data.attributes.skinIndex !== undefined ); if ( skinning ) { - for ( var i = 0, l = materials.length; i < l; i ++ ) { + for ( let i = 0, l = materials.length; i < l; i ++ ) { materials[ i ].skinning = true; @@ -3704,11 +3696,11 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // choose between a single or multi materials (material array) - var material = ( materials.length === 1 ) ? materials[ 0 ] : materials; + const material = ( materials.length === 1 ) ? materials[ 0 ] : materials; // now create a specific 3D object - var object; + let object; switch ( type ) { @@ -3760,16 +3752,16 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseVisualScene( xml ) { - var data = { + const data = { name: xml.getAttribute( 'name' ), children: [] }; prepareNodes( xml ); - var elements = getElementsByTagName( xml, 'node' ); + const elements = getElementsByTagName( xml, 'node' ); - for ( var i = 0; i < elements.length; i ++ ) { + for ( let i = 0; i < elements.length; i ++ ) { data.children.push( parseNode( elements[ i ] ) ); @@ -3781,14 +3773,14 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildVisualScene( data ) { - var group = new Group(); + const group = new Group(); group.name = data.name; - var children = data.children; + const children = data.children; - for ( var i = 0; i < children.length; i ++ ) { + for ( let i = 0; i < children.length; i ++ ) { - var child = children[ i ]; + const child = children[ i ]; group.add( getNode( child.id ) ); @@ -3814,14 +3806,14 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseScene( xml ) { - var instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ]; + const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ]; return getVisualScene( parseId( instance.getAttribute( 'url' ) ) ); } function setupAnimations() { - var clips = library.clips; + const clips = library.clips; if ( isEmpty( clips ) === true ) { @@ -3829,13 +3821,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // if there are animations but no clips, we create a default clip for playback - var tracks = []; + const tracks = []; - for ( var id in library.animations ) { + for ( const id in library.animations ) { - var animationTracks = getAnimation( id ); + const animationTracks = getAnimation( id ); - for ( var i = 0, l = animationTracks.length; i < l; i ++ ) { + for ( let i = 0, l = animationTracks.length; i < l; i ++ ) { tracks.push( animationTracks[ i ] ); @@ -3849,7 +3841,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else { - for ( var id in clips ) { + for ( const id in clips ) { animations.push( getAnimationClip( id ) ); @@ -3864,12 +3856,12 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parserErrorToText( parserError ) { - var result = ''; - var stack = [ parserError ]; + let result = ''; + const stack = [ parserError ]; while ( stack.length ) { - var node = stack.shift(); + const node = stack.shift(); if ( node.nodeType === Node.TEXT_NODE ) { @@ -3894,17 +3886,17 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var xml = new DOMParser().parseFromString( text, 'application/xml' ); + const xml = new DOMParser().parseFromString( text, 'application/xml' ); - var collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ]; + const collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ]; - var parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ]; + const parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ]; if ( parserError !== undefined ) { // Chrome will return parser error with a div in it - var errorElement = getElementsByTagName( parserError, 'div' )[ 0 ]; - var errorText; + const errorElement = getElementsByTagName( parserError, 'div' )[ 0 ]; + let errorText; if ( errorElement ) { @@ -3924,14 +3916,14 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // metadata - var version = collada.getAttribute( 'version' ); + const version = collada.getAttribute( 'version' ); console.log( 'THREE.ColladaLoader: File version', version ); - var asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] ); - var textureLoader = new TextureLoader( this.manager ); + const asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] ); + const textureLoader = new TextureLoader( this.manager ); textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin ); - var tgaLoader; + let tgaLoader; if ( TGALoader ) { @@ -3942,13 +3934,13 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // - var animations = []; - var kinematics = {}; - var count = 0; + const animations = []; + let kinematics = {}; + let count = 0; // - var library = { + const library = { animations: {}, clips: {}, controllers: {}, @@ -3994,7 +3986,7 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { setupAnimations(); setupKinematics(); - var scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] ); + const scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] ); scene.animations = animations; if ( asset.upAxis === 'Z_UP' ) { @@ -4019,6 +4011,6 @@ ColladaLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } -} ); +} export { ColladaLoader }; diff --git a/examples/jsm/loaders/DDSLoader.js b/examples/jsm/loaders/DDSLoader.js index 673cc5fe3f46ae..4a2eb786a60374 100644 --- a/examples/jsm/loaders/DDSLoader.js +++ b/examples/jsm/loaders/DDSLoader.js @@ -7,19 +7,17 @@ import { RGB_S3TC_DXT1_Format } from '../../../build/three.module.js'; -var DDSLoader = function ( manager ) { +class DDSLoader extends CompressedTextureLoader { - CompressedTextureLoader.call( this, manager ); + constructor( manager ) { -}; + super( manager ); -DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prototype ), { - - constructor: DDSLoader, + } - parse: function ( buffer, loadMipmaps ) { + parse( buffer, loadMipmaps ) { - var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 }; + const dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 }; // Adapted from @toji's DDS utils // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js @@ -27,36 +25,36 @@ DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prot // All values and structures referenced from: // http://msdn.microsoft.com/en-us/library/bb943991.aspx/ - var DDS_MAGIC = 0x20534444; - - // var DDSD_CAPS = 0x1; - // var DDSD_HEIGHT = 0x2; - // var DDSD_WIDTH = 0x4; - // var DDSD_PITCH = 0x8; - // var DDSD_PIXELFORMAT = 0x1000; - var DDSD_MIPMAPCOUNT = 0x20000; - // var DDSD_LINEARSIZE = 0x80000; - // var DDSD_DEPTH = 0x800000; - - // var DDSCAPS_COMPLEX = 0x8; - // var DDSCAPS_MIPMAP = 0x400000; - // var DDSCAPS_TEXTURE = 0x1000; - - var DDSCAPS2_CUBEMAP = 0x200; - var DDSCAPS2_CUBEMAP_POSITIVEX = 0x400; - var DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800; - var DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000; - var DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000; - var DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000; - var DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000; - // var DDSCAPS2_VOLUME = 0x200000; - - // var DDPF_ALPHAPIXELS = 0x1; - // var DDPF_ALPHA = 0x2; - var DDPF_FOURCC = 0x4; - // var DDPF_RGB = 0x40; - // var DDPF_YUV = 0x200; - // var DDPF_LUMINANCE = 0x20000; + const DDS_MAGIC = 0x20534444; + + // let DDSD_CAPS = 0x1; + // let DDSD_HEIGHT = 0x2; + // let DDSD_WIDTH = 0x4; + // let DDSD_PITCH = 0x8; + // let DDSD_PIXELFORMAT = 0x1000; + const DDSD_MIPMAPCOUNT = 0x20000; + // let DDSD_LINEARSIZE = 0x80000; + // let DDSD_DEPTH = 0x800000; + + // let DDSCAPS_COMPLEX = 0x8; + // let DDSCAPS_MIPMAP = 0x400000; + // let DDSCAPS_TEXTURE = 0x1000; + + const DDSCAPS2_CUBEMAP = 0x200; + const DDSCAPS2_CUBEMAP_POSITIVEX = 0x400; + const DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800; + const DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000; + const DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000; + const DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000; + const DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000; + // let DDSCAPS2_VOLUME = 0x200000; + + // let DDPF_ALPHAPIXELS = 0x1; + // let DDPF_ALPHA = 0x2; + const DDPF_FOURCC = 0x4; + // let DDPF_RGB = 0x40; + // let DDPF_YUV = 0x200; + // let DDPF_LUMINANCE = 0x20000; function fourCCToInt32( value ) { @@ -80,19 +78,19 @@ DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prot function loadARGBMip( buffer, dataOffset, width, height ) { - var dataLength = width * height * 4; - var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength ); - var byteArray = new Uint8Array( dataLength ); - var dst = 0; - var src = 0; - for ( var y = 0; y < height; y ++ ) { + const dataLength = width * height * 4; + const srcBuffer = new Uint8Array( buffer, dataOffset, dataLength ); + const byteArray = new Uint8Array( dataLength ); + let dst = 0; + let src = 0; + for ( let y = 0; y < height; y ++ ) { - for ( var x = 0; x < width; x ++ ) { + for ( let x = 0; x < width; x ++ ) { - var b = srcBuffer[ src ]; src ++; - var g = srcBuffer[ src ]; src ++; - var r = srcBuffer[ src ]; src ++; - var a = srcBuffer[ src ]; src ++; + const b = srcBuffer[ src ]; src ++; + const g = srcBuffer[ src ]; src ++; + const r = srcBuffer[ src ]; src ++; + const a = srcBuffer[ src ]; src ++; byteArray[ dst ] = r; dst ++; //r byteArray[ dst ] = g; dst ++; //g byteArray[ dst ] = b; dst ++; //b @@ -106,40 +104,40 @@ DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prot } - var FOURCC_DXT1 = fourCCToInt32( 'DXT1' ); - var FOURCC_DXT3 = fourCCToInt32( 'DXT3' ); - var FOURCC_DXT5 = fourCCToInt32( 'DXT5' ); - var FOURCC_ETC1 = fourCCToInt32( 'ETC1' ); + const FOURCC_DXT1 = fourCCToInt32( 'DXT1' ); + const FOURCC_DXT3 = fourCCToInt32( 'DXT3' ); + const FOURCC_DXT5 = fourCCToInt32( 'DXT5' ); + const FOURCC_ETC1 = fourCCToInt32( 'ETC1' ); - var headerLengthInt = 31; // The header length in 32 bit ints + const headerLengthInt = 31; // The header length in 32 bit ints // Offsets into the header array - var off_magic = 0; + const off_magic = 0; - var off_size = 1; - var off_flags = 2; - var off_height = 3; - var off_width = 4; + const off_size = 1; + const off_flags = 2; + const off_height = 3; + const off_width = 4; - var off_mipmapCount = 7; + const off_mipmapCount = 7; - var off_pfFlags = 20; - var off_pfFourCC = 21; - var off_RGBBitCount = 22; - var off_RBitMask = 23; - var off_GBitMask = 24; - var off_BBitMask = 25; - var off_ABitMask = 26; + const off_pfFlags = 20; + const off_pfFourCC = 21; + const off_RGBBitCount = 22; + const off_RBitMask = 23; + const off_GBitMask = 24; + const off_BBitMask = 25; + const off_ABitMask = 26; - // var off_caps = 27; - var off_caps2 = 28; - // var off_caps3 = 29; - // var off_caps4 = 30; + // let off_caps = 27; + const off_caps2 = 28; + // let off_caps3 = 29; + // let off_caps4 = 30; // Parse header - var header = new Int32Array( buffer, 0, headerLengthInt ); + const header = new Int32Array( buffer, 0, headerLengthInt ); if ( header[ off_magic ] !== DDS_MAGIC ) { @@ -155,11 +153,11 @@ DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prot } - var blockBytes; + let blockBytes; - var fourCC = header[ off_pfFourCC ]; + const fourCC = header[ off_pfFourCC ]; - var isRGBAUncompressed = false; + let isRGBAUncompressed = false; switch ( fourCC ) { @@ -216,7 +214,7 @@ DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prot } - var caps2 = header[ off_caps2 ]; + const caps2 = header[ off_caps2 ]; dds.isCubemap = caps2 & DDSCAPS2_CUBEMAP ? true : false; if ( dds.isCubemap && ( ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEX ) || @@ -235,32 +233,34 @@ DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prot dds.width = header[ off_width ]; dds.height = header[ off_height ]; - var dataOffset = header[ off_size ] + 4; + let dataOffset = header[ off_size ] + 4; // Extract mipmaps buffers - var faces = dds.isCubemap ? 6 : 1; + const faces = dds.isCubemap ? 6 : 1; + + for ( let face = 0; face < faces; face ++ ) { - for ( var face = 0; face < faces; face ++ ) { + let width = dds.width; + let height = dds.height; - var width = dds.width; - var height = dds.height; + for ( let i = 0; i < dds.mipmapCount; i ++ ) { - for ( var i = 0; i < dds.mipmapCount; i ++ ) { + let byteArray, dataLength; if ( isRGBAUncompressed ) { - var byteArray = loadARGBMip( buffer, dataOffset, width, height ); - var dataLength = byteArray.length; + byteArray = loadARGBMip( buffer, dataOffset, width, height ); + dataLength = byteArray.length; } else { - var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes; - var byteArray = new Uint8Array( buffer, dataOffset, dataLength ); + dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes; + byteArray = new Uint8Array( buffer, dataOffset, dataLength ); } - var mipmap = { 'data': byteArray, 'width': width, 'height': height }; + const mipmap = { 'data': byteArray, 'width': width, 'height': height }; dds.mipmaps.push( mipmap ); dataOffset += dataLength; @@ -276,6 +276,6 @@ DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prot } -} ); +} export { DDSLoader }; diff --git a/examples/jsm/loaders/KMZLoader.js b/examples/jsm/loaders/KMZLoader.js index 0237c06c7dbf05..d4a9484f37dfde 100644 --- a/examples/jsm/loaders/KMZLoader.js +++ b/examples/jsm/loaders/KMZLoader.js @@ -7,21 +7,19 @@ import { import { ColladaLoader } from '../loaders/ColladaLoader.js'; import * as fflate from '../libs/fflate.module.min.js'; -var KMZLoader = function ( manager ) { +class KMZLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { -}; + super( manager ); -KMZLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: KMZLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var loader = new FileLoader( scope.manager ); + const loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( scope.requestHeader ); @@ -50,13 +48,13 @@ KMZLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } - parse: function ( data ) { + parse( data ) { function findFile( url ) { - for ( var path in zip ) { + for ( const path in zip ) { if ( path.substr( - url.length ) === url ) { @@ -68,16 +66,16 @@ KMZLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var manager = new LoadingManager(); + const manager = new LoadingManager(); manager.setURLModifier( function ( url ) { - var image = findFile( url ); + const image = findFile( url ); if ( image ) { console.log( 'Loading', url ); - var blob = new Blob( [ image.buffer ], { type: 'application/octet-stream' } ); + const blob = new Blob( [ image.buffer ], { type: 'application/octet-stream' } ); return URL.createObjectURL( blob ); } @@ -88,17 +86,17 @@ KMZLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // - var zip = fflate.unzipSync( new Uint8Array( data ) ); // eslint-disable-line no-undef + const zip = fflate.unzipSync( new Uint8Array( data ) ); // eslint-disable-line no-undef if ( zip[ 'doc.kml' ] ) { - var xml = new DOMParser().parseFromString( fflate.strFromU8( zip[ 'doc.kml' ] ), 'application/xml' ); // eslint-disable-line no-undef + const xml = new DOMParser().parseFromString( fflate.strFromU8( zip[ 'doc.kml' ] ), 'application/xml' ); // eslint-disable-line no-undef - var model = xml.querySelector( 'Placemark Model Link href' ); + const model = xml.querySelector( 'Placemark Model Link href' ); if ( model ) { - var loader = new ColladaLoader( manager ); + const loader = new ColladaLoader( manager ); return loader.parse( fflate.strFromU8( zip[ model.textContent ] ) ); // eslint-disable-line no-undef } @@ -107,13 +105,13 @@ KMZLoader.prototype = Object.assign( Object.create( Loader.prototype ), { console.warn( 'KMZLoader: Missing doc.kml file.' ); - for ( var path in zip ) { + for ( const path in zip ) { - var extension = path.split( '.' ).pop().toLowerCase(); + const extension = path.split( '.' ).pop().toLowerCase(); if ( extension === 'dae' ) { - var loader = new ColladaLoader( manager ); + const loader = new ColladaLoader( manager ); return loader.parse( fflate.strFromU8( zip[ path ] ) ); // eslint-disable-line no-undef } @@ -127,6 +125,6 @@ KMZLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } -} ); +} export { KMZLoader }; diff --git a/examples/jsm/loaders/MD2Loader.js b/examples/jsm/loaders/MD2Loader.js index 38850caf7342d3..b0c7248dea1501 100644 --- a/examples/jsm/loaders/MD2Loader.js +++ b/examples/jsm/loaders/MD2Loader.js @@ -7,21 +7,103 @@ import { Vector3 } from '../../../build/three.module.js'; -var MD2Loader = function ( manager ) { - - Loader.call( this, manager ); - -}; - -MD2Loader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: MD2Loader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - - var loader = new FileLoader( scope.manager ); +const _normalData = [ + [ - 0.525731, 0.000000, 0.850651 ], [ - 0.442863, 0.238856, 0.864188 ], + [ - 0.295242, 0.000000, 0.955423 ], [ - 0.309017, 0.500000, 0.809017 ], + [ - 0.162460, 0.262866, 0.951056 ], [ 0.000000, 0.000000, 1.000000 ], + [ 0.000000, 0.850651, 0.525731 ], [ - 0.147621, 0.716567, 0.681718 ], + [ 0.147621, 0.716567, 0.681718 ], [ 0.000000, 0.525731, 0.850651 ], + [ 0.309017, 0.500000, 0.809017 ], [ 0.525731, 0.000000, 0.850651 ], + [ 0.295242, 0.000000, 0.955423 ], [ 0.442863, 0.238856, 0.864188 ], + [ 0.162460, 0.262866, 0.951056 ], [ - 0.681718, 0.147621, 0.716567 ], + [ - 0.809017, 0.309017, 0.500000 ], [ - 0.587785, 0.425325, 0.688191 ], + [ - 0.850651, 0.525731, 0.000000 ], [ - 0.864188, 0.442863, 0.238856 ], + [ - 0.716567, 0.681718, 0.147621 ], [ - 0.688191, 0.587785, 0.425325 ], + [ - 0.500000, 0.809017, 0.309017 ], [ - 0.238856, 0.864188, 0.442863 ], + [ - 0.425325, 0.688191, 0.587785 ], [ - 0.716567, 0.681718, - 0.147621 ], + [ - 0.500000, 0.809017, - 0.309017 ], [ - 0.525731, 0.850651, 0.000000 ], + [ 0.000000, 0.850651, - 0.525731 ], [ - 0.238856, 0.864188, - 0.442863 ], + [ 0.000000, 0.955423, - 0.295242 ], [ - 0.262866, 0.951056, - 0.162460 ], + [ 0.000000, 1.000000, 0.000000 ], [ 0.000000, 0.955423, 0.295242 ], + [ - 0.262866, 0.951056, 0.162460 ], [ 0.238856, 0.864188, 0.442863 ], + [ 0.262866, 0.951056, 0.162460 ], [ 0.500000, 0.809017, 0.309017 ], + [ 0.238856, 0.864188, - 0.442863 ], [ 0.262866, 0.951056, - 0.162460 ], + [ 0.500000, 0.809017, - 0.309017 ], [ 0.850651, 0.525731, 0.000000 ], + [ 0.716567, 0.681718, 0.147621 ], [ 0.716567, 0.681718, - 0.147621 ], + [ 0.525731, 0.850651, 0.000000 ], [ 0.425325, 0.688191, 0.587785 ], + [ 0.864188, 0.442863, 0.238856 ], [ 0.688191, 0.587785, 0.425325 ], + [ 0.809017, 0.309017, 0.500000 ], [ 0.681718, 0.147621, 0.716567 ], + [ 0.587785, 0.425325, 0.688191 ], [ 0.955423, 0.295242, 0.000000 ], + [ 1.000000, 0.000000, 0.000000 ], [ 0.951056, 0.162460, 0.262866 ], + [ 0.850651, - 0.525731, 0.000000 ], [ 0.955423, - 0.295242, 0.000000 ], + [ 0.864188, - 0.442863, 0.238856 ], [ 0.951056, - 0.162460, 0.262866 ], + [ 0.809017, - 0.309017, 0.500000 ], [ 0.681718, - 0.147621, 0.716567 ], + [ 0.850651, 0.000000, 0.525731 ], [ 0.864188, 0.442863, - 0.238856 ], + [ 0.809017, 0.309017, - 0.500000 ], [ 0.951056, 0.162460, - 0.262866 ], + [ 0.525731, 0.000000, - 0.850651 ], [ 0.681718, 0.147621, - 0.716567 ], + [ 0.681718, - 0.147621, - 0.716567 ], [ 0.850651, 0.000000, - 0.525731 ], + [ 0.809017, - 0.309017, - 0.500000 ], [ 0.864188, - 0.442863, - 0.238856 ], + [ 0.951056, - 0.162460, - 0.262866 ], [ 0.147621, 0.716567, - 0.681718 ], + [ 0.309017, 0.500000, - 0.809017 ], [ 0.425325, 0.688191, - 0.587785 ], + [ 0.442863, 0.238856, - 0.864188 ], [ 0.587785, 0.425325, - 0.688191 ], + [ 0.688191, 0.587785, - 0.425325 ], [ - 0.147621, 0.716567, - 0.681718 ], + [ - 0.309017, 0.500000, - 0.809017 ], [ 0.000000, 0.525731, - 0.850651 ], + [ - 0.525731, 0.000000, - 0.850651 ], [ - 0.442863, 0.238856, - 0.864188 ], + [ - 0.295242, 0.000000, - 0.955423 ], [ - 0.162460, 0.262866, - 0.951056 ], + [ 0.000000, 0.000000, - 1.000000 ], [ 0.295242, 0.000000, - 0.955423 ], + [ 0.162460, 0.262866, - 0.951056 ], [ - 0.442863, - 0.238856, - 0.864188 ], + [ - 0.309017, - 0.500000, - 0.809017 ], [ - 0.162460, - 0.262866, - 0.951056 ], + [ 0.000000, - 0.850651, - 0.525731 ], [ - 0.147621, - 0.716567, - 0.681718 ], + [ 0.147621, - 0.716567, - 0.681718 ], [ 0.000000, - 0.525731, - 0.850651 ], + [ 0.309017, - 0.500000, - 0.809017 ], [ 0.442863, - 0.238856, - 0.864188 ], + [ 0.162460, - 0.262866, - 0.951056 ], [ 0.238856, - 0.864188, - 0.442863 ], + [ 0.500000, - 0.809017, - 0.309017 ], [ 0.425325, - 0.688191, - 0.587785 ], + [ 0.716567, - 0.681718, - 0.147621 ], [ 0.688191, - 0.587785, - 0.425325 ], + [ 0.587785, - 0.425325, - 0.688191 ], [ 0.000000, - 0.955423, - 0.295242 ], + [ 0.000000, - 1.000000, 0.000000 ], [ 0.262866, - 0.951056, - 0.162460 ], + [ 0.000000, - 0.850651, 0.525731 ], [ 0.000000, - 0.955423, 0.295242 ], + [ 0.238856, - 0.864188, 0.442863 ], [ 0.262866, - 0.951056, 0.162460 ], + [ 0.500000, - 0.809017, 0.309017 ], [ 0.716567, - 0.681718, 0.147621 ], + [ 0.525731, - 0.850651, 0.000000 ], [ - 0.238856, - 0.864188, - 0.442863 ], + [ - 0.500000, - 0.809017, - 0.309017 ], [ - 0.262866, - 0.951056, - 0.162460 ], + [ - 0.850651, - 0.525731, 0.000000 ], [ - 0.716567, - 0.681718, - 0.147621 ], + [ - 0.716567, - 0.681718, 0.147621 ], [ - 0.525731, - 0.850651, 0.000000 ], + [ - 0.500000, - 0.809017, 0.309017 ], [ - 0.238856, - 0.864188, 0.442863 ], + [ - 0.262866, - 0.951056, 0.162460 ], [ - 0.864188, - 0.442863, 0.238856 ], + [ - 0.809017, - 0.309017, 0.500000 ], [ - 0.688191, - 0.587785, 0.425325 ], + [ - 0.681718, - 0.147621, 0.716567 ], [ - 0.442863, - 0.238856, 0.864188 ], + [ - 0.587785, - 0.425325, 0.688191 ], [ - 0.309017, - 0.500000, 0.809017 ], + [ - 0.147621, - 0.716567, 0.681718 ], [ - 0.425325, - 0.688191, 0.587785 ], + [ - 0.162460, - 0.262866, 0.951056 ], [ 0.442863, - 0.238856, 0.864188 ], + [ 0.162460, - 0.262866, 0.951056 ], [ 0.309017, - 0.500000, 0.809017 ], + [ 0.147621, - 0.716567, 0.681718 ], [ 0.000000, - 0.525731, 0.850651 ], + [ 0.425325, - 0.688191, 0.587785 ], [ 0.587785, - 0.425325, 0.688191 ], + [ 0.688191, - 0.587785, 0.425325 ], [ - 0.955423, 0.295242, 0.000000 ], + [ - 0.951056, 0.162460, 0.262866 ], [ - 1.000000, 0.000000, 0.000000 ], + [ - 0.850651, 0.000000, 0.525731 ], [ - 0.955423, - 0.295242, 0.000000 ], + [ - 0.951056, - 0.162460, 0.262866 ], [ - 0.864188, 0.442863, - 0.238856 ], + [ - 0.951056, 0.162460, - 0.262866 ], [ - 0.809017, 0.309017, - 0.500000 ], + [ - 0.864188, - 0.442863, - 0.238856 ], [ - 0.951056, - 0.162460, - 0.262866 ], + [ - 0.809017, - 0.309017, - 0.500000 ], [ - 0.681718, 0.147621, - 0.716567 ], + [ - 0.681718, - 0.147621, - 0.716567 ], [ - 0.850651, 0.000000, - 0.525731 ], + [ - 0.688191, 0.587785, - 0.425325 ], [ - 0.587785, 0.425325, - 0.688191 ], + [ - 0.425325, 0.688191, - 0.587785 ], [ - 0.425325, - 0.688191, - 0.587785 ], + [ - 0.587785, - 0.425325, - 0.688191 ], [ - 0.688191, - 0.587785, - 0.425325 ] +]; + +class MD2Loader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( scope.requestHeader ); @@ -50,355 +132,267 @@ MD2Loader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, - - parse: ( function () { - - var normalData = [ - [ - 0.525731, 0.000000, 0.850651 ], [ - 0.442863, 0.238856, 0.864188 ], - [ - 0.295242, 0.000000, 0.955423 ], [ - 0.309017, 0.500000, 0.809017 ], - [ - 0.162460, 0.262866, 0.951056 ], [ 0.000000, 0.000000, 1.000000 ], - [ 0.000000, 0.850651, 0.525731 ], [ - 0.147621, 0.716567, 0.681718 ], - [ 0.147621, 0.716567, 0.681718 ], [ 0.000000, 0.525731, 0.850651 ], - [ 0.309017, 0.500000, 0.809017 ], [ 0.525731, 0.000000, 0.850651 ], - [ 0.295242, 0.000000, 0.955423 ], [ 0.442863, 0.238856, 0.864188 ], - [ 0.162460, 0.262866, 0.951056 ], [ - 0.681718, 0.147621, 0.716567 ], - [ - 0.809017, 0.309017, 0.500000 ], [ - 0.587785, 0.425325, 0.688191 ], - [ - 0.850651, 0.525731, 0.000000 ], [ - 0.864188, 0.442863, 0.238856 ], - [ - 0.716567, 0.681718, 0.147621 ], [ - 0.688191, 0.587785, 0.425325 ], - [ - 0.500000, 0.809017, 0.309017 ], [ - 0.238856, 0.864188, 0.442863 ], - [ - 0.425325, 0.688191, 0.587785 ], [ - 0.716567, 0.681718, - 0.147621 ], - [ - 0.500000, 0.809017, - 0.309017 ], [ - 0.525731, 0.850651, 0.000000 ], - [ 0.000000, 0.850651, - 0.525731 ], [ - 0.238856, 0.864188, - 0.442863 ], - [ 0.000000, 0.955423, - 0.295242 ], [ - 0.262866, 0.951056, - 0.162460 ], - [ 0.000000, 1.000000, 0.000000 ], [ 0.000000, 0.955423, 0.295242 ], - [ - 0.262866, 0.951056, 0.162460 ], [ 0.238856, 0.864188, 0.442863 ], - [ 0.262866, 0.951056, 0.162460 ], [ 0.500000, 0.809017, 0.309017 ], - [ 0.238856, 0.864188, - 0.442863 ], [ 0.262866, 0.951056, - 0.162460 ], - [ 0.500000, 0.809017, - 0.309017 ], [ 0.850651, 0.525731, 0.000000 ], - [ 0.716567, 0.681718, 0.147621 ], [ 0.716567, 0.681718, - 0.147621 ], - [ 0.525731, 0.850651, 0.000000 ], [ 0.425325, 0.688191, 0.587785 ], - [ 0.864188, 0.442863, 0.238856 ], [ 0.688191, 0.587785, 0.425325 ], - [ 0.809017, 0.309017, 0.500000 ], [ 0.681718, 0.147621, 0.716567 ], - [ 0.587785, 0.425325, 0.688191 ], [ 0.955423, 0.295242, 0.000000 ], - [ 1.000000, 0.000000, 0.000000 ], [ 0.951056, 0.162460, 0.262866 ], - [ 0.850651, - 0.525731, 0.000000 ], [ 0.955423, - 0.295242, 0.000000 ], - [ 0.864188, - 0.442863, 0.238856 ], [ 0.951056, - 0.162460, 0.262866 ], - [ 0.809017, - 0.309017, 0.500000 ], [ 0.681718, - 0.147621, 0.716567 ], - [ 0.850651, 0.000000, 0.525731 ], [ 0.864188, 0.442863, - 0.238856 ], - [ 0.809017, 0.309017, - 0.500000 ], [ 0.951056, 0.162460, - 0.262866 ], - [ 0.525731, 0.000000, - 0.850651 ], [ 0.681718, 0.147621, - 0.716567 ], - [ 0.681718, - 0.147621, - 0.716567 ], [ 0.850651, 0.000000, - 0.525731 ], - [ 0.809017, - 0.309017, - 0.500000 ], [ 0.864188, - 0.442863, - 0.238856 ], - [ 0.951056, - 0.162460, - 0.262866 ], [ 0.147621, 0.716567, - 0.681718 ], - [ 0.309017, 0.500000, - 0.809017 ], [ 0.425325, 0.688191, - 0.587785 ], - [ 0.442863, 0.238856, - 0.864188 ], [ 0.587785, 0.425325, - 0.688191 ], - [ 0.688191, 0.587785, - 0.425325 ], [ - 0.147621, 0.716567, - 0.681718 ], - [ - 0.309017, 0.500000, - 0.809017 ], [ 0.000000, 0.525731, - 0.850651 ], - [ - 0.525731, 0.000000, - 0.850651 ], [ - 0.442863, 0.238856, - 0.864188 ], - [ - 0.295242, 0.000000, - 0.955423 ], [ - 0.162460, 0.262866, - 0.951056 ], - [ 0.000000, 0.000000, - 1.000000 ], [ 0.295242, 0.000000, - 0.955423 ], - [ 0.162460, 0.262866, - 0.951056 ], [ - 0.442863, - 0.238856, - 0.864188 ], - [ - 0.309017, - 0.500000, - 0.809017 ], [ - 0.162460, - 0.262866, - 0.951056 ], - [ 0.000000, - 0.850651, - 0.525731 ], [ - 0.147621, - 0.716567, - 0.681718 ], - [ 0.147621, - 0.716567, - 0.681718 ], [ 0.000000, - 0.525731, - 0.850651 ], - [ 0.309017, - 0.500000, - 0.809017 ], [ 0.442863, - 0.238856, - 0.864188 ], - [ 0.162460, - 0.262866, - 0.951056 ], [ 0.238856, - 0.864188, - 0.442863 ], - [ 0.500000, - 0.809017, - 0.309017 ], [ 0.425325, - 0.688191, - 0.587785 ], - [ 0.716567, - 0.681718, - 0.147621 ], [ 0.688191, - 0.587785, - 0.425325 ], - [ 0.587785, - 0.425325, - 0.688191 ], [ 0.000000, - 0.955423, - 0.295242 ], - [ 0.000000, - 1.000000, 0.000000 ], [ 0.262866, - 0.951056, - 0.162460 ], - [ 0.000000, - 0.850651, 0.525731 ], [ 0.000000, - 0.955423, 0.295242 ], - [ 0.238856, - 0.864188, 0.442863 ], [ 0.262866, - 0.951056, 0.162460 ], - [ 0.500000, - 0.809017, 0.309017 ], [ 0.716567, - 0.681718, 0.147621 ], - [ 0.525731, - 0.850651, 0.000000 ], [ - 0.238856, - 0.864188, - 0.442863 ], - [ - 0.500000, - 0.809017, - 0.309017 ], [ - 0.262866, - 0.951056, - 0.162460 ], - [ - 0.850651, - 0.525731, 0.000000 ], [ - 0.716567, - 0.681718, - 0.147621 ], - [ - 0.716567, - 0.681718, 0.147621 ], [ - 0.525731, - 0.850651, 0.000000 ], - [ - 0.500000, - 0.809017, 0.309017 ], [ - 0.238856, - 0.864188, 0.442863 ], - [ - 0.262866, - 0.951056, 0.162460 ], [ - 0.864188, - 0.442863, 0.238856 ], - [ - 0.809017, - 0.309017, 0.500000 ], [ - 0.688191, - 0.587785, 0.425325 ], - [ - 0.681718, - 0.147621, 0.716567 ], [ - 0.442863, - 0.238856, 0.864188 ], - [ - 0.587785, - 0.425325, 0.688191 ], [ - 0.309017, - 0.500000, 0.809017 ], - [ - 0.147621, - 0.716567, 0.681718 ], [ - 0.425325, - 0.688191, 0.587785 ], - [ - 0.162460, - 0.262866, 0.951056 ], [ 0.442863, - 0.238856, 0.864188 ], - [ 0.162460, - 0.262866, 0.951056 ], [ 0.309017, - 0.500000, 0.809017 ], - [ 0.147621, - 0.716567, 0.681718 ], [ 0.000000, - 0.525731, 0.850651 ], - [ 0.425325, - 0.688191, 0.587785 ], [ 0.587785, - 0.425325, 0.688191 ], - [ 0.688191, - 0.587785, 0.425325 ], [ - 0.955423, 0.295242, 0.000000 ], - [ - 0.951056, 0.162460, 0.262866 ], [ - 1.000000, 0.000000, 0.000000 ], - [ - 0.850651, 0.000000, 0.525731 ], [ - 0.955423, - 0.295242, 0.000000 ], - [ - 0.951056, - 0.162460, 0.262866 ], [ - 0.864188, 0.442863, - 0.238856 ], - [ - 0.951056, 0.162460, - 0.262866 ], [ - 0.809017, 0.309017, - 0.500000 ], - [ - 0.864188, - 0.442863, - 0.238856 ], [ - 0.951056, - 0.162460, - 0.262866 ], - [ - 0.809017, - 0.309017, - 0.500000 ], [ - 0.681718, 0.147621, - 0.716567 ], - [ - 0.681718, - 0.147621, - 0.716567 ], [ - 0.850651, 0.000000, - 0.525731 ], - [ - 0.688191, 0.587785, - 0.425325 ], [ - 0.587785, 0.425325, - 0.688191 ], - [ - 0.425325, 0.688191, - 0.587785 ], [ - 0.425325, - 0.688191, - 0.587785 ], - [ - 0.587785, - 0.425325, - 0.688191 ], [ - 0.688191, - 0.587785, - 0.425325 ] - ]; + } - return function ( buffer ) { + parse( buffer ) { - var data = new DataView( buffer ); + const data = new DataView( buffer ); - // http://tfc.duke.free.fr/coding/md2-specs-en.html + // http://tfc.duke.free.fr/coding/md2-specs-en.html - var header = {}; - var headerNames = [ - 'ident', 'version', - 'skinwidth', 'skinheight', - 'framesize', - 'num_skins', 'num_vertices', 'num_st', 'num_tris', 'num_glcmds', 'num_frames', - 'offset_skins', 'offset_st', 'offset_tris', 'offset_frames', 'offset_glcmds', 'offset_end' - ]; + const header = {}; + const headerNames = [ + 'ident', 'version', + 'skinwidth', 'skinheight', + 'framesize', + 'num_skins', 'num_vertices', 'num_st', 'num_tris', 'num_glcmds', 'num_frames', + 'offset_skins', 'offset_st', 'offset_tris', 'offset_frames', 'offset_glcmds', 'offset_end' + ]; - for ( var i = 0; i < headerNames.length; i ++ ) { + for ( let i = 0; i < headerNames.length; i ++ ) { - header[ headerNames[ i ] ] = data.getInt32( i * 4, true ); + header[ headerNames[ i ] ] = data.getInt32( i * 4, true ); - } + } - if ( header.ident !== 844121161 || header.version !== 8 ) { + if ( header.ident !== 844121161 || header.version !== 8 ) { - console.error( 'Not a valid MD2 file' ); - return; + console.error( 'Not a valid MD2 file' ); + return; - } + } - if ( header.offset_end !== data.byteLength ) { - - console.error( 'Corrupted MD2 file' ); - return; - - } + if ( header.offset_end !== data.byteLength ) { - // + console.error( 'Corrupted MD2 file' ); + return; - var geometry = new BufferGeometry(); + } - // uvs + // - var uvsTemp = []; - var offset = header.offset_st; + const geometry = new BufferGeometry(); - for ( var i = 0, l = header.num_st; i < l; i ++ ) { + // uvs - var u = data.getInt16( offset + 0, true ); - var v = data.getInt16( offset + 2, true ); + const uvsTemp = []; + let offset = header.offset_st; - uvsTemp.push( u / header.skinwidth, 1 - ( v / header.skinheight ) ); + for ( let i = 0, l = header.num_st; i < l; i ++ ) { - offset += 4; + const u = data.getInt16( offset + 0, true ); + const v = data.getInt16( offset + 2, true ); - } + uvsTemp.push( u / header.skinwidth, 1 - ( v / header.skinheight ) ); - // triangles + offset += 4; - offset = header.offset_tris; + } - var vertexIndices = []; - var uvIndices = []; + // triangles - for ( var i = 0, l = header.num_tris; i < l; i ++ ) { + offset = header.offset_tris; - vertexIndices.push( - data.getUint16( offset + 0, true ), - data.getUint16( offset + 2, true ), - data.getUint16( offset + 4, true ) - ); + const vertexIndices = []; + const uvIndices = []; - uvIndices.push( - data.getUint16( offset + 6, true ), - data.getUint16( offset + 8, true ), - data.getUint16( offset + 10, true ) - ); + for ( let i = 0, l = header.num_tris; i < l; i ++ ) { - offset += 12; + vertexIndices.push( + data.getUint16( offset + 0, true ), + data.getUint16( offset + 2, true ), + data.getUint16( offset + 4, true ) + ); - } + uvIndices.push( + data.getUint16( offset + 6, true ), + data.getUint16( offset + 8, true ), + data.getUint16( offset + 10, true ) + ); - // frames + offset += 12; - var translation = new Vector3(); - var scale = new Vector3(); - var string = []; + } - var frames = []; + // frames - offset = header.offset_frames; + const translation = new Vector3(); + const scale = new Vector3(); + const string = []; - for ( var i = 0, l = header.num_frames; i < l; i ++ ) { + const frames = []; - scale.set( - data.getFloat32( offset + 0, true ), - data.getFloat32( offset + 4, true ), - data.getFloat32( offset + 8, true ) - ); + offset = header.offset_frames; - translation.set( - data.getFloat32( offset + 12, true ), - data.getFloat32( offset + 16, true ), - data.getFloat32( offset + 20, true ) - ); + for ( let i = 0, l = header.num_frames; i < l; i ++ ) { - offset += 24; + scale.set( + data.getFloat32( offset + 0, true ), + data.getFloat32( offset + 4, true ), + data.getFloat32( offset + 8, true ) + ); - for ( var j = 0; j < 16; j ++ ) { + translation.set( + data.getFloat32( offset + 12, true ), + data.getFloat32( offset + 16, true ), + data.getFloat32( offset + 20, true ) + ); - var character = data.getUint8( offset + j, true ); - if ( character === 0 ) break; + offset += 24; - string[ j ] = character; + for ( let j = 0; j < 16; j ++ ) { - } + const character = data.getUint8( offset + j, true ); + if ( character === 0 ) break; - var frame = { - name: String.fromCharCode.apply( null, string ), - vertices: [], - normals: [] - }; + string[ j ] = character; - offset += 16; + } - for ( var j = 0; j < header.num_vertices; j ++ ) { + const frame = { + name: String.fromCharCode.apply( null, string ), + vertices: [], + normals: [] + }; - var x = data.getUint8( offset ++, true ); - var y = data.getUint8( offset ++, true ); - var z = data.getUint8( offset ++, true ); - var n = normalData[ data.getUint8( offset ++, true ) ]; + offset += 16; - x = x * scale.x + translation.x; - y = y * scale.y + translation.y; - z = z * scale.z + translation.z; + for ( let j = 0; j < header.num_vertices; j ++ ) { - frame.vertices.push( x, z, y ); // convert to Y-up - frame.normals.push( n[ 0 ], n[ 2 ], n[ 1 ] ); // convert to Y-up + let x = data.getUint8( offset ++, true ); + let y = data.getUint8( offset ++, true ); + let z = data.getUint8( offset ++, true ); + const n = _normalData[ data.getUint8( offset ++, true ) ]; - } + x = x * scale.x + translation.x; + y = y * scale.y + translation.y; + z = z * scale.z + translation.z; - frames.push( frame ); + frame.vertices.push( x, z, y ); // convert to Y-up + frame.normals.push( n[ 0 ], n[ 2 ], n[ 1 ] ); // convert to Y-up } - // static - - var positions = []; - var normals = []; - var uvs = []; + frames.push( frame ); - var verticesTemp = frames[ 0 ].vertices; - var normalsTemp = frames[ 0 ].normals; + } - for ( var i = 0, l = vertexIndices.length; i < l; i ++ ) { + // static - var vertexIndex = vertexIndices[ i ]; - var stride = vertexIndex * 3; + const positions = []; + const normals = []; + const uvs = []; - // + const verticesTemp = frames[ 0 ].vertices; + const normalsTemp = frames[ 0 ].normals; - var x = verticesTemp[ stride ]; - var y = verticesTemp[ stride + 1 ]; - var z = verticesTemp[ stride + 2 ]; + for ( let i = 0, l = vertexIndices.length; i < l; i ++ ) { - positions.push( x, y, z ); + const vertexIndex = vertexIndices[ i ]; + let stride = vertexIndex * 3; - // + // - var nx = normalsTemp[ stride ]; - var ny = normalsTemp[ stride + 1 ]; - var nz = normalsTemp[ stride + 2 ]; + const x = verticesTemp[ stride ]; + const y = verticesTemp[ stride + 1 ]; + const z = verticesTemp[ stride + 2 ]; - normals.push( nx, ny, nz ); + positions.push( x, y, z ); - // + // - var uvIndex = uvIndices[ i ]; - stride = uvIndex * 2; + const nx = normalsTemp[ stride ]; + const ny = normalsTemp[ stride + 1 ]; + const nz = normalsTemp[ stride + 2 ]; - var u = uvsTemp[ stride ]; - var v = uvsTemp[ stride + 1 ]; + normals.push( nx, ny, nz ); - uvs.push( u, v ); + // - } + const uvIndex = uvIndices[ i ]; + stride = uvIndex * 2; - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); - geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - geometry.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + const u = uvsTemp[ stride ]; + const v = uvsTemp[ stride + 1 ]; - // animation + uvs.push( u, v ); - var morphPositions = []; - var morphNormals = []; + } - for ( var i = 0, l = frames.length; i < l; i ++ ) { + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + geometry.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - var frame = frames[ i ]; - var attributeName = frame.name; + // animation - if ( frame.vertices.length > 0 ) { + const morphPositions = []; + const morphNormals = []; - var positions = []; + for ( let i = 0, l = frames.length; i < l; i ++ ) { - for ( var j = 0, jl = vertexIndices.length; j < jl; j ++ ) { + const frame = frames[ i ]; + const attributeName = frame.name; - var vertexIndex = vertexIndices[ j ]; - var stride = vertexIndex * 3; + if ( frame.vertices.length > 0 ) { - var x = frame.vertices[ stride ]; - var y = frame.vertices[ stride + 1 ]; - var z = frame.vertices[ stride + 2 ]; + const positions = []; - positions.push( x, y, z ); + for ( let j = 0, jl = vertexIndices.length; j < jl; j ++ ) { - } + const vertexIndex = vertexIndices[ j ]; + const stride = vertexIndex * 3; - var positionAttribute = new Float32BufferAttribute( positions, 3 ); - positionAttribute.name = attributeName; + const x = frame.vertices[ stride ]; + const y = frame.vertices[ stride + 1 ]; + const z = frame.vertices[ stride + 2 ]; - morphPositions.push( positionAttribute ); + positions.push( x, y, z ); } - if ( frame.normals.length > 0 ) { + const positionAttribute = new Float32BufferAttribute( positions, 3 ); + positionAttribute.name = attributeName; - var normals = []; + morphPositions.push( positionAttribute ); - for ( var j = 0, jl = vertexIndices.length; j < jl; j ++ ) { + } - var vertexIndex = vertexIndices[ j ]; - var stride = vertexIndex * 3; + if ( frame.normals.length > 0 ) { - var nx = frame.normals[ stride ]; - var ny = frame.normals[ stride + 1 ]; - var nz = frame.normals[ stride + 2 ]; + const normals = []; - normals.push( nx, ny, nz ); + for ( let j = 0, jl = vertexIndices.length; j < jl; j ++ ) { - } + const vertexIndex = vertexIndices[ j ]; + const stride = vertexIndex * 3; - var normalAttribute = new Float32BufferAttribute( normals, 3 ); - normalAttribute.name = attributeName; + const nx = frame.normals[ stride ]; + const ny = frame.normals[ stride + 1 ]; + const nz = frame.normals[ stride + 2 ]; - morphNormals.push( normalAttribute ); + normals.push( nx, ny, nz ); } + const normalAttribute = new Float32BufferAttribute( normals, 3 ); + normalAttribute.name = attributeName; + + morphNormals.push( normalAttribute ); + } - geometry.morphAttributes.position = morphPositions; - geometry.morphAttributes.normal = morphNormals; - geometry.morphTargetsRelative = false; + } - geometry.animations = AnimationClip.CreateClipsFromMorphTargetSequences( frames, 10 ); + geometry.morphAttributes.position = morphPositions; + geometry.morphAttributes.normal = morphNormals; + geometry.morphTargetsRelative = false; - return geometry; + geometry.animations = AnimationClip.CreateClipsFromMorphTargetSequences( frames, 10 ); - }; + return geometry; - } )() + } -} ); +} export { MD2Loader }; diff --git a/examples/jsm/loaders/MDDLoader.js b/examples/jsm/loaders/MDDLoader.js index b38b7e6d1a9c53..1f1007fbc43d84 100644 --- a/examples/jsm/loaders/MDDLoader.js +++ b/examples/jsm/loaders/MDDLoader.js @@ -18,21 +18,19 @@ import { NumberKeyframeTrack } from '../../../build/three.module.js'; -var MDDLoader = function ( manager ) { +class MDDLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { -}; + super( manager ); -MDDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: MDDLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var loader = new FileLoader( this.manager ); + const loader = new FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.load( url, function ( data ) { @@ -41,43 +39,43 @@ MDDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } - parse: function ( data ) { + parse( data ) { - var view = new DataView( data ); + const view = new DataView( data ); - var totalFrames = view.getUint32( 0 ); - var totalPoints = view.getUint32( 4 ); + const totalFrames = view.getUint32( 0 ); + const totalPoints = view.getUint32( 4 ); - var offset = 8; + let offset = 8; // animation clip - var times = new Float32Array( totalFrames ); - var values = new Float32Array( totalFrames * totalFrames ).fill( 0 ); + const times = new Float32Array( totalFrames ); + const values = new Float32Array( totalFrames * totalFrames ).fill( 0 ); - for ( var i = 0; i < totalFrames; i ++ ) { + for ( let i = 0; i < totalFrames; i ++ ) { times[ i ] = view.getFloat32( offset ); offset += 4; values[ ( totalFrames * i ) + i ] = 1; } - var track = new NumberKeyframeTrack( '.morphTargetInfluences', times, values ); - var clip = new AnimationClip( 'default', times[ times.length - 1 ], [ track ] ); + const track = new NumberKeyframeTrack( '.morphTargetInfluences', times, values ); + const clip = new AnimationClip( 'default', times[ times.length - 1 ], [ track ] ); // morph targets - var morphTargets = []; + const morphTargets = []; - for ( var i = 0; i < totalFrames; i ++ ) { + for ( let i = 0; i < totalFrames; i ++ ) { - var morphTarget = new Float32Array( totalPoints * 3 ); + const morphTarget = new Float32Array( totalPoints * 3 ); - for ( var j = 0; j < totalPoints; j ++ ) { + for ( let j = 0; j < totalPoints; j ++ ) { - var stride = ( j * 3 ); + const stride = ( j * 3 ); morphTarget[ stride + 0 ] = view.getFloat32( offset ); offset += 4; // x morphTarget[ stride + 1 ] = view.getFloat32( offset ); offset += 4; // y @@ -85,7 +83,7 @@ MDDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var attribute = new BufferAttribute( morphTarget, 3 ); + const attribute = new BufferAttribute( morphTarget, 3 ); attribute.name = 'morph_' + i; morphTargets.push( attribute ); @@ -99,6 +97,6 @@ MDDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } -} ); +} export { MDDLoader }; diff --git a/examples/jsm/loaders/PCDLoader.js b/examples/jsm/loaders/PCDLoader.js index 1fbb1265c2cbb1..dd48c091ddb549 100644 --- a/examples/jsm/loaders/PCDLoader.js +++ b/examples/jsm/loaders/PCDLoader.js @@ -8,24 +8,21 @@ import { PointsMaterial } from '../../../build/three.module.js'; -var PCDLoader = function ( manager ) { +class PCDLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { - this.littleEndian = true; + super( manager ); -}; + this.littleEndian = true; + } -PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: PCDLoader, - - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var loader = new FileLoader( scope.manager ); + const loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( scope.requestHeader ); @@ -54,21 +51,21 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } - parse: function ( data, url ) { + parse( data, url ) { // from https://gitlab.com/taketwo/three-pcd-loader/blob/master/decompress-lzf.js function decompressLZF( inData, outLength ) { - var inLength = inData.length; - var outData = new Uint8Array( outLength ); - var inPtr = 0; - var outPtr = 0; - var ctrl; - var len; - var ref; + const inLength = inData.length; + const outData = new Uint8Array( outLength ); + let inPtr = 0; + let outPtr = 0; + let ctrl; + let len; + let ref; do { ctrl = inData[ inPtr ++ ]; @@ -115,9 +112,9 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseHeader( data ) { - var PCDheader = {}; - var result1 = data.search( /[\r\n]DATA\s(\S*)\s/i ); - var result2 = /[\r\n]DATA\s(\S*)\s/i.exec( data.substr( result1 - 1 ) ); + const PCDheader = {}; + const result1 = data.search( /[\r\n]DATA\s(\S*)\s/i ); + const result2 = /[\r\n]DATA\s(\S*)\s/i.exec( data.substr( result1 - 1 ) ); PCDheader.data = result2[ 1 ]; PCDheader.headerLen = result2[ 0 ].length + result1; @@ -187,7 +184,7 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { PCDheader.count = []; - for ( var i = 0, l = PCDheader.fields.length; i < l; i ++ ) { + for ( let i = 0, l = PCDheader.fields.length; i < l; i ++ ) { PCDheader.count.push( 1 ); @@ -197,9 +194,9 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { PCDheader.offset = {}; - var sizeSum = 0; + let sizeSum = 0; - for ( var i = 0, l = PCDheader.fields.length; i < l; i ++ ) { + for ( let i = 0, l = PCDheader.fields.length; i < l; i ++ ) { if ( PCDheader.data === 'ascii' ) { @@ -222,31 +219,31 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var textData = LoaderUtils.decodeText( new Uint8Array( data ) ); + const textData = LoaderUtils.decodeText( new Uint8Array( data ) ); // parse header (always ascii format) - var PCDheader = parseHeader( textData ); + const PCDheader = parseHeader( textData ); // parse data - var position = []; - var normal = []; - var color = []; + const position = []; + const normal = []; + const color = []; // ascii if ( PCDheader.data === 'ascii' ) { - var offset = PCDheader.offset; - var pcdData = textData.substr( PCDheader.headerLen ); - var lines = pcdData.split( '\n' ); + const offset = PCDheader.offset; + const pcdData = textData.substr( PCDheader.headerLen ); + const lines = pcdData.split( '\n' ); - for ( var i = 0, l = lines.length; i < l; i ++ ) { + for ( let i = 0, l = lines.length; i < l; i ++ ) { if ( lines[ i ] === '' ) continue; - var line = lines[ i ].split( ' ' ); + const line = lines[ i ].split( ' ' ); if ( offset.x !== undefined ) { @@ -258,10 +255,10 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( offset.rgb !== undefined ) { - var rgb = parseFloat( line[ offset.rgb ] ); - var r = ( rgb >> 16 ) & 0x0000ff; - var g = ( rgb >> 8 ) & 0x0000ff; - var b = ( rgb >> 0 ) & 0x0000ff; + const rgb = parseFloat( line[ offset.rgb ] ); + const r = ( rgb >> 16 ) & 0x0000ff; + const g = ( rgb >> 8 ) & 0x0000ff; + const b = ( rgb >> 0 ) & 0x0000ff; color.push( r / 255, g / 255, b / 255 ); } @@ -286,15 +283,15 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( PCDheader.data === 'binary_compressed' ) { - var sizes = new Uint32Array( data.slice( PCDheader.headerLen, PCDheader.headerLen + 8 ) ); - var compressedSize = sizes[ 0 ]; - var decompressedSize = sizes[ 1 ]; - var decompressed = decompressLZF( new Uint8Array( data, PCDheader.headerLen + 8, compressedSize ), decompressedSize ); - var dataview = new DataView( decompressed.buffer ); + const sizes = new Uint32Array( data.slice( PCDheader.headerLen, PCDheader.headerLen + 8 ) ); + const compressedSize = sizes[ 0 ]; + const decompressedSize = sizes[ 1 ]; + const decompressed = decompressLZF( new Uint8Array( data, PCDheader.headerLen + 8, compressedSize ), decompressedSize ); + const dataview = new DataView( decompressed.buffer ); - var offset = PCDheader.offset; + const offset = PCDheader.offset; - for ( var i = 0; i < PCDheader.points; i ++ ) { + for ( let i = 0; i < PCDheader.points; i ++ ) { if ( offset.x !== undefined ) { @@ -328,10 +325,10 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( PCDheader.data === 'binary' ) { - var dataview = new DataView( data, PCDheader.headerLen ); - var offset = PCDheader.offset; + const dataview = new DataView( data, PCDheader.headerLen ); + const offset = PCDheader.offset; - for ( var i = 0, row = 0; i < PCDheader.points; i ++, row += PCDheader.rowSize ) { + for ( let i = 0, row = 0; i < PCDheader.points; i ++, row += PCDheader.rowSize ) { if ( offset.x !== undefined ) { @@ -363,7 +360,7 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // build geometry - var geometry = new BufferGeometry(); + const geometry = new BufferGeometry(); if ( position.length > 0 ) geometry.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) ); if ( normal.length > 0 ) geometry.setAttribute( 'normal', new Float32BufferAttribute( normal, 3 ) ); @@ -373,7 +370,7 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // build material - var material = new PointsMaterial( { size: 0.005 } ); + const material = new PointsMaterial( { size: 0.005 } ); if ( color.length > 0 ) { @@ -387,8 +384,8 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // build point cloud - var mesh = new Points( geometry, material ); - var name = url.split( '' ).reverse().join( '' ); + const mesh = new Points( geometry, material ); + let name = url.split( '' ).reverse().join( '' ); name = /([^\/]*)/.exec( name ); name = name[ 1 ].split( '' ).reverse().join( '' ); mesh.name = name; @@ -397,6 +394,6 @@ PCDLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } -} ); +} export { PCDLoader }; diff --git a/examples/jsm/loaders/PDBLoader.js b/examples/jsm/loaders/PDBLoader.js index e92bd1e1247ebd..2477969e61f034 100644 --- a/examples/jsm/loaders/PDBLoader.js +++ b/examples/jsm/loaders/PDBLoader.js @@ -5,21 +5,19 @@ import { Loader } from '../../../build/three.module.js'; -var PDBLoader = function ( manager ) { +class PDBLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { -}; + super( manager ); -PDBLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: PDBLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var loader = new FileLoader( scope.manager ); + const loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setRequestHeader( scope.requestHeader ); loader.setWithCredentials( scope.withCredentials ); @@ -47,11 +45,11 @@ PDBLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } // Based on CanvasMol PDB parser - parse: function ( text ) { + parse( text ) { function trim( text ) { @@ -71,13 +69,13 @@ PDBLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - function parseBond( start, length ) { + function parseBond( start, length, satom, i ) { - var eatom = parseInt( lines[ i ].substr( start, length ) ); + const eatom = parseInt( lines[ i ].substr( start, length ) ); if ( eatom ) { - var h = hash( satom, eatom ); + const h = hash( satom, eatom ); if ( _bhash[ h ] === undefined ) { @@ -99,7 +97,7 @@ PDBLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function buildGeometry() { - var build = { + const build = { geometryAtoms: new BufferGeometry(), geometryBonds: new BufferGeometry(), json: { @@ -107,31 +105,28 @@ PDBLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } }; - var geometryAtoms = build.geometryAtoms; - var geometryBonds = build.geometryBonds; + const geometryAtoms = build.geometryAtoms; + const geometryBonds = build.geometryBonds; - var i, l; - var x, y, z; - - var verticesAtoms = []; - var colorsAtoms = []; - var verticesBonds = []; + const verticesAtoms = []; + const colorsAtoms = []; + const verticesBonds = []; // atoms - for ( i = 0, l = atoms.length; i < l; i ++ ) { + for ( let i = 0, l = atoms.length; i < l; i ++ ) { - var atom = atoms[ i ]; + const atom = atoms[ i ]; - x = atom[ 0 ]; - y = atom[ 1 ]; - z = atom[ 2 ]; + const x = atom[ 0 ]; + const y = atom[ 1 ]; + const z = atom[ 2 ]; verticesAtoms.push( x, y, z ); - var r = atom[ 3 ][ 0 ] / 255; - var g = atom[ 3 ][ 1 ] / 255; - var b = atom[ 3 ][ 2 ] / 255; + const r = atom[ 3 ][ 0 ] / 255; + const g = atom[ 3 ][ 1 ] / 255; + const b = atom[ 3 ][ 2 ] / 255; colorsAtoms.push( r, g, b ); @@ -139,19 +134,19 @@ PDBLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // bonds - for ( i = 0, l = _bonds.length; i < l; i ++ ) { + for ( let i = 0, l = _bonds.length; i < l; i ++ ) { - var bond = _bonds[ i ]; + const bond = _bonds[ i ]; - var start = bond[ 0 ]; - var end = bond[ 1 ]; + const start = bond[ 0 ]; + const end = bond[ 1 ]; - var startAtom = _atomMap[ start ]; - var endAtom = _atomMap[ end ]; + const startAtom = _atomMap[ start ]; + const endAtom = _atomMap[ end ]; - x = startAtom[ 0 ]; - y = startAtom[ 1 ]; - z = startAtom[ 2 ]; + let x = startAtom[ 0 ]; + let y = startAtom[ 1 ]; + let z = startAtom[ 2 ]; verticesBonds.push( x, y, z ); @@ -174,30 +169,28 @@ PDBLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var CPK = { h: [ 255, 255, 255 ], he: [ 217, 255, 255 ], li: [ 204, 128, 255 ], be: [ 194, 255, 0 ], b: [ 255, 181, 181 ], c: [ 144, 144, 144 ], n: [ 48, 80, 248 ], o: [ 255, 13, 13 ], f: [ 144, 224, 80 ], ne: [ 179, 227, 245 ], na: [ 171, 92, 242 ], mg: [ 138, 255, 0 ], al: [ 191, 166, 166 ], si: [ 240, 200, 160 ], p: [ 255, 128, 0 ], s: [ 255, 255, 48 ], cl: [ 31, 240, 31 ], ar: [ 128, 209, 227 ], k: [ 143, 64, 212 ], ca: [ 61, 255, 0 ], sc: [ 230, 230, 230 ], ti: [ 191, 194, 199 ], v: [ 166, 166, 171 ], cr: [ 138, 153, 199 ], mn: [ 156, 122, 199 ], fe: [ 224, 102, 51 ], co: [ 240, 144, 160 ], ni: [ 80, 208, 80 ], cu: [ 200, 128, 51 ], zn: [ 125, 128, 176 ], ga: [ 194, 143, 143 ], ge: [ 102, 143, 143 ], as: [ 189, 128, 227 ], se: [ 255, 161, 0 ], br: [ 166, 41, 41 ], kr: [ 92, 184, 209 ], rb: [ 112, 46, 176 ], sr: [ 0, 255, 0 ], y: [ 148, 255, 255 ], zr: [ 148, 224, 224 ], nb: [ 115, 194, 201 ], mo: [ 84, 181, 181 ], tc: [ 59, 158, 158 ], ru: [ 36, 143, 143 ], rh: [ 10, 125, 140 ], pd: [ 0, 105, 133 ], ag: [ 192, 192, 192 ], cd: [ 255, 217, 143 ], in: [ 166, 117, 115 ], sn: [ 102, 128, 128 ], sb: [ 158, 99, 181 ], te: [ 212, 122, 0 ], i: [ 148, 0, 148 ], xe: [ 66, 158, 176 ], cs: [ 87, 23, 143 ], ba: [ 0, 201, 0 ], la: [ 112, 212, 255 ], ce: [ 255, 255, 199 ], pr: [ 217, 255, 199 ], nd: [ 199, 255, 199 ], pm: [ 163, 255, 199 ], sm: [ 143, 255, 199 ], eu: [ 97, 255, 199 ], gd: [ 69, 255, 199 ], tb: [ 48, 255, 199 ], dy: [ 31, 255, 199 ], ho: [ 0, 255, 156 ], er: [ 0, 230, 117 ], tm: [ 0, 212, 82 ], yb: [ 0, 191, 56 ], lu: [ 0, 171, 36 ], hf: [ 77, 194, 255 ], ta: [ 77, 166, 255 ], w: [ 33, 148, 214 ], re: [ 38, 125, 171 ], os: [ 38, 102, 150 ], ir: [ 23, 84, 135 ], pt: [ 208, 208, 224 ], au: [ 255, 209, 35 ], hg: [ 184, 184, 208 ], tl: [ 166, 84, 77 ], pb: [ 87, 89, 97 ], bi: [ 158, 79, 181 ], po: [ 171, 92, 0 ], at: [ 117, 79, 69 ], rn: [ 66, 130, 150 ], fr: [ 66, 0, 102 ], ra: [ 0, 125, 0 ], ac: [ 112, 171, 250 ], th: [ 0, 186, 255 ], pa: [ 0, 161, 255 ], u: [ 0, 143, 255 ], np: [ 0, 128, 255 ], pu: [ 0, 107, 255 ], am: [ 84, 92, 242 ], cm: [ 120, 92, 227 ], bk: [ 138, 79, 227 ], cf: [ 161, 54, 212 ], es: [ 179, 31, 212 ], fm: [ 179, 31, 186 ], md: [ 179, 13, 166 ], no: [ 189, 13, 135 ], lr: [ 199, 0, 102 ], rf: [ 204, 0, 89 ], db: [ 209, 0, 79 ], sg: [ 217, 0, 69 ], bh: [ 224, 0, 56 ], hs: [ 230, 0, 46 ], mt: [ 235, 0, 38 ], ds: [ 235, 0, 38 ], rg: [ 235, 0, 38 ], cn: [ 235, 0, 38 ], uut: [ 235, 0, 38 ], uuq: [ 235, 0, 38 ], uup: [ 235, 0, 38 ], uuh: [ 235, 0, 38 ], uus: [ 235, 0, 38 ], uuo: [ 235, 0, 38 ] }; - - var atoms = []; + const CPK = { h: [ 255, 255, 255 ], he: [ 217, 255, 255 ], li: [ 204, 128, 255 ], be: [ 194, 255, 0 ], b: [ 255, 181, 181 ], c: [ 144, 144, 144 ], n: [ 48, 80, 248 ], o: [ 255, 13, 13 ], f: [ 144, 224, 80 ], ne: [ 179, 227, 245 ], na: [ 171, 92, 242 ], mg: [ 138, 255, 0 ], al: [ 191, 166, 166 ], si: [ 240, 200, 160 ], p: [ 255, 128, 0 ], s: [ 255, 255, 48 ], cl: [ 31, 240, 31 ], ar: [ 128, 209, 227 ], k: [ 143, 64, 212 ], ca: [ 61, 255, 0 ], sc: [ 230, 230, 230 ], ti: [ 191, 194, 199 ], v: [ 166, 166, 171 ], cr: [ 138, 153, 199 ], mn: [ 156, 122, 199 ], fe: [ 224, 102, 51 ], co: [ 240, 144, 160 ], ni: [ 80, 208, 80 ], cu: [ 200, 128, 51 ], zn: [ 125, 128, 176 ], ga: [ 194, 143, 143 ], ge: [ 102, 143, 143 ], as: [ 189, 128, 227 ], se: [ 255, 161, 0 ], br: [ 166, 41, 41 ], kr: [ 92, 184, 209 ], rb: [ 112, 46, 176 ], sr: [ 0, 255, 0 ], y: [ 148, 255, 255 ], zr: [ 148, 224, 224 ], nb: [ 115, 194, 201 ], mo: [ 84, 181, 181 ], tc: [ 59, 158, 158 ], ru: [ 36, 143, 143 ], rh: [ 10, 125, 140 ], pd: [ 0, 105, 133 ], ag: [ 192, 192, 192 ], cd: [ 255, 217, 143 ], in: [ 166, 117, 115 ], sn: [ 102, 128, 128 ], sb: [ 158, 99, 181 ], te: [ 212, 122, 0 ], i: [ 148, 0, 148 ], xe: [ 66, 158, 176 ], cs: [ 87, 23, 143 ], ba: [ 0, 201, 0 ], la: [ 112, 212, 255 ], ce: [ 255, 255, 199 ], pr: [ 217, 255, 199 ], nd: [ 199, 255, 199 ], pm: [ 163, 255, 199 ], sm: [ 143, 255, 199 ], eu: [ 97, 255, 199 ], gd: [ 69, 255, 199 ], tb: [ 48, 255, 199 ], dy: [ 31, 255, 199 ], ho: [ 0, 255, 156 ], er: [ 0, 230, 117 ], tm: [ 0, 212, 82 ], yb: [ 0, 191, 56 ], lu: [ 0, 171, 36 ], hf: [ 77, 194, 255 ], ta: [ 77, 166, 255 ], w: [ 33, 148, 214 ], re: [ 38, 125, 171 ], os: [ 38, 102, 150 ], ir: [ 23, 84, 135 ], pt: [ 208, 208, 224 ], au: [ 255, 209, 35 ], hg: [ 184, 184, 208 ], tl: [ 166, 84, 77 ], pb: [ 87, 89, 97 ], bi: [ 158, 79, 181 ], po: [ 171, 92, 0 ], at: [ 117, 79, 69 ], rn: [ 66, 130, 150 ], fr: [ 66, 0, 102 ], ra: [ 0, 125, 0 ], ac: [ 112, 171, 250 ], th: [ 0, 186, 255 ], pa: [ 0, 161, 255 ], u: [ 0, 143, 255 ], np: [ 0, 128, 255 ], pu: [ 0, 107, 255 ], am: [ 84, 92, 242 ], cm: [ 120, 92, 227 ], bk: [ 138, 79, 227 ], cf: [ 161, 54, 212 ], es: [ 179, 31, 212 ], fm: [ 179, 31, 186 ], md: [ 179, 13, 166 ], no: [ 189, 13, 135 ], lr: [ 199, 0, 102 ], rf: [ 204, 0, 89 ], db: [ 209, 0, 79 ], sg: [ 217, 0, 69 ], bh: [ 224, 0, 56 ], hs: [ 230, 0, 46 ], mt: [ 235, 0, 38 ], ds: [ 235, 0, 38 ], rg: [ 235, 0, 38 ], cn: [ 235, 0, 38 ], uut: [ 235, 0, 38 ], uuq: [ 235, 0, 38 ], uup: [ 235, 0, 38 ], uuh: [ 235, 0, 38 ], uus: [ 235, 0, 38 ], uuo: [ 235, 0, 38 ] }; - var _bonds = []; - var _bhash = {}; - var _atomMap = {}; + const atoms = []; - var x, y, z, index, e; + const _bonds = []; + const _bhash = {}; + const _atomMap = {}; // parse - var lines = text.split( '\n' ); + const lines = text.split( '\n' ); - for ( var i = 0, l = lines.length; i < l; i ++ ) { + for ( let i = 0, l = lines.length; i < l; i ++ ) { if ( lines[ i ].substr( 0, 4 ) === 'ATOM' || lines[ i ].substr( 0, 6 ) === 'HETATM' ) { - x = parseFloat( lines[ i ].substr( 30, 7 ) ); - y = parseFloat( lines[ i ].substr( 38, 7 ) ); - z = parseFloat( lines[ i ].substr( 46, 7 ) ); - index = parseInt( lines[ i ].substr( 6, 5 ) ) - 1; + const x = parseFloat( lines[ i ].substr( 30, 7 ) ); + const y = parseFloat( lines[ i ].substr( 38, 7 ) ); + const z = parseFloat( lines[ i ].substr( 46, 7 ) ); + const index = parseInt( lines[ i ].substr( 6, 5 ) ) - 1; - e = trim( lines[ i ].substr( 76, 2 ) ).toLowerCase(); + let e = trim( lines[ i ].substr( 76, 2 ) ).toLowerCase(); if ( e === '' ) { @@ -205,19 +198,19 @@ PDBLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var atomData = [ x, y, z, CPK[ e ], capitalize( e ) ]; + const atomData = [ x, y, z, CPK[ e ], capitalize( e ) ]; atoms.push( atomData ); _atomMap[ index ] = atomData; } else if ( lines[ i ].substr( 0, 6 ) === 'CONECT' ) { - var satom = parseInt( lines[ i ].substr( 6, 5 ) ); + const satom = parseInt( lines[ i ].substr( 6, 5 ) ); - parseBond( 11, 5 ); - parseBond( 16, 5 ); - parseBond( 21, 5 ); - parseBond( 26, 5 ); + parseBond( 11, 5, satom, i ); + parseBond( 16, 5, satom, i ); + parseBond( 21, 5, satom, i ); + parseBond( 26, 5, satom, i ); } @@ -229,6 +222,6 @@ PDBLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } -} ); +} export { PDBLoader }; diff --git a/examples/jsm/loaders/PLYLoader.js b/examples/jsm/loaders/PLYLoader.js index ea51b74e920098..1c1e0283980499 100644 --- a/examples/jsm/loaders/PLYLoader.js +++ b/examples/jsm/loaders/PLYLoader.js @@ -13,7 +13,7 @@ import { * Limitations: ASCII decoding assumes file is UTF-8. * * Usage: - * var loader = new PLYLoader(); + * const loader = new PLYLoader(); * loader.load('./models/ply/ascii/dolphins.ply', function (geometry) { * * scene.add( new THREE.Mesh( geometry ) ); @@ -33,23 +33,21 @@ import { */ -var PLYLoader = function ( manager ) { +class PLYLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { - this.propertyNameMapping = {}; + super( manager ); -}; + this.propertyNameMapping = {}; -PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: PLYLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var loader = new FileLoader( this.manager ); + const loader = new FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( this.requestHeader ); @@ -78,22 +76,22 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } - setPropertyNameMapping: function ( mapping ) { + setPropertyNameMapping( mapping ) { this.propertyNameMapping = mapping; - }, + } - parse: function ( data ) { + parse( data ) { function parseHeader( data ) { - var patternHeader = /ply([\s\S]*)end_header\r?\n/; - var headerText = ''; - var headerLength = 0; - var result = patternHeader.exec( data ); + const patternHeader = /ply([\s\S]*)end_header\r?\n/; + let headerText = ''; + let headerLength = 0; + const result = patternHeader.exec( data ); if ( result !== null ) { @@ -102,20 +100,19 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var header = { + const header = { comments: [], elements: [], headerLength: headerLength, objInfo: '' }; - var lines = headerText.split( '\n' ); - var currentElement; - var lineType, lineValues; + const lines = headerText.split( '\n' ); + let currentElement; function make_ply_element_property( propertValues, propertyNameMapping ) { - var property = { type: propertValues[ 0 ] }; + const property = { type: propertValues[ 0 ] }; if ( property.type === 'list' ) { @@ -139,15 +136,15 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - for ( var i = 0; i < lines.length; i ++ ) { + for ( let i = 0; i < lines.length; i ++ ) { - var line = lines[ i ]; + let line = lines[ i ]; line = line.trim(); if ( line === '' ) continue; - lineValues = line.split( /\s+/ ); - lineType = lineValues.shift(); + const lineValues = line.split( /\s+/ ); + const lineType = lineValues.shift(); line = lineValues.join( ' ' ); switch ( lineType ) { @@ -230,18 +227,18 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseASCIIElement( properties, line ) { - var values = line.split( /\s+/ ); + const values = line.split( /\s+/ ); - var element = {}; + const element = {}; - for ( var i = 0; i < properties.length; i ++ ) { + for ( let i = 0; i < properties.length; i ++ ) { if ( properties[ i ].type === 'list' ) { - var list = []; - var n = parseASCIINumber( values.shift(), properties[ i ].countType ); + const list = []; + const n = parseASCIINumber( values.shift(), properties[ i ].countType ); - for ( var j = 0; j < n; j ++ ) { + for ( let j = 0; j < n; j ++ ) { list.push( parseASCIINumber( values.shift(), properties[ i ].itemType ) ); @@ -265,7 +262,7 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format) - var buffer = { + const buffer = { indices: [], vertices: [], normals: [], @@ -274,23 +271,23 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { colors: [] }; - var result; + let result; - var patternBody = /end_header\s([\s\S]*)$/; - var body = ''; + const patternBody = /end_header\s([\s\S]*)$/; + let body = ''; if ( ( result = patternBody.exec( data ) ) !== null ) { body = result[ 1 ]; } - var lines = body.split( '\n' ); - var currentElement = 0; - var currentElementCount = 0; + const lines = body.split( '\n' ); + let currentElement = 0; + let currentElementCount = 0; - for ( var i = 0; i < lines.length; i ++ ) { + for ( let i = 0; i < lines.length; i ++ ) { - var line = lines[ i ]; + let line = lines[ i ]; line = line.trim(); if ( line === '' ) { @@ -305,7 +302,7 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var element = parseASCIIElement( header.elements[ currentElement ].properties, line ); + const element = parseASCIIElement( header.elements[ currentElement ].properties, line ); handleElement( buffer, header.elements[ currentElement ].name, element ); @@ -319,7 +316,7 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function postProcess( buffer ) { - var geometry = new BufferGeometry(); + let geometry = new BufferGeometry(); // mandatory buffer data @@ -390,8 +387,8 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else if ( elementName === 'face' ) { - var vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338 - var texcoord = element.texcoord; + const vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338 + const texcoord = element.texcoord; if ( vertex_indices.length === 3 ) { @@ -436,20 +433,20 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function binaryReadElement( dataview, at, properties, little_endian ) { - var element = {}; - var result, read = 0; + const element = {}; + let result, read = 0; - for ( var i = 0; i < properties.length; i ++ ) { + for ( let i = 0; i < properties.length; i ++ ) { if ( properties[ i ].type === 'list' ) { - var list = []; + const list = []; result = binaryRead( dataview, at + read, properties[ i ].countType, little_endian ); - var n = result[ 0 ]; + const n = result[ 0 ]; read += result[ 1 ]; - for ( var j = 0; j < n; j ++ ) { + for ( let j = 0; j < n; j ++ ) { result = binaryRead( dataview, at + read, properties[ i ].itemType, little_endian ); list.push( result[ 0 ] ); @@ -475,7 +472,7 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseBinary( data, header ) { - var buffer = { + const buffer = { indices: [], vertices: [], normals: [], @@ -484,17 +481,17 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { colors: [] }; - var little_endian = ( header.format === 'binary_little_endian' ); - var body = new DataView( data, header.headerLength ); - var result, loc = 0; + const little_endian = ( header.format === 'binary_little_endian' ); + const body = new DataView( data, header.headerLength ); + let result, loc = 0; - for ( var currentElement = 0; currentElement < header.elements.length; currentElement ++ ) { + for ( let currentElement = 0; currentElement < header.elements.length; currentElement ++ ) { - for ( var currentElementCount = 0; currentElementCount < header.elements[ currentElement ].count; currentElementCount ++ ) { + for ( let currentElementCount = 0; currentElementCount < header.elements[ currentElement ].count; currentElementCount ++ ) { result = binaryReadElement( body, loc, header.elements[ currentElement ].properties, little_endian ); loc += result[ 1 ]; - var element = result[ 0 ]; + const element = result[ 0 ]; handleElement( buffer, header.elements[ currentElement ].name, element ); @@ -508,13 +505,13 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // - var geometry; - var scope = this; + let geometry; + const scope = this; if ( data instanceof ArrayBuffer ) { - var text = LoaderUtils.decodeText( new Uint8Array( data ) ); - var header = parseHeader( text ); + const text = LoaderUtils.decodeText( new Uint8Array( data ) ); + const header = parseHeader( text ); geometry = header.format === 'ascii' ? parseASCII( text, header ) : parseBinary( data, header ); @@ -528,6 +525,6 @@ PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } -} ); +} export { PLYLoader }; diff --git a/examples/jsm/loaders/PVRLoader.js b/examples/jsm/loaders/PVRLoader.js index 662554fc42612e..553c1e5148a1e8 100644 --- a/examples/jsm/loaders/PVRLoader.js +++ b/examples/jsm/loaders/PVRLoader.js @@ -12,22 +12,20 @@ import { * TODO : implement loadMipmaps option */ -var PVRLoader = function ( manager ) { +class PVRLoader extends CompressedTextureLoader { - CompressedTextureLoader.call( this, manager ); + constructor( manager ) { -}; + super( manager ); -PVRLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prototype ), { - - constructor: PVRLoader, + } - parse: function ( buffer, loadMipmaps ) { + parse( buffer, loadMipmaps ) { - var headerLengthInt = 13; - var header = new Uint32Array( buffer, 0, headerLengthInt ); + const headerLengthInt = 13; + const header = new Uint32Array( buffer, 0, headerLengthInt ); - var pvrDatas = { + const pvrDatas = { buffer: buffer, header: header, loadMipmaps: loadMipmaps @@ -37,13 +35,13 @@ PVRLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prot // PVR v3 - return PVRLoader._parseV3( pvrDatas ); + return _parseV3( pvrDatas ); } else if ( header[ 11 ] === 0x21525650 ) { // PVR v2 - return PVRLoader._parseV2( pvrDatas ); + return _parseV2( pvrDatas ); } else { @@ -53,15 +51,15 @@ PVRLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prot } -} ); +} -PVRLoader._parseV3 = function ( pvrDatas ) { +function _parseV3( pvrDatas ) { - var header = pvrDatas.header; - var bpp, format; + const header = pvrDatas.header; + let bpp, format; - var metaLen = header[ 12 ], + const metaLen = header[ 12 ], pixelFormat = header[ 2 ], height = header[ 6 ], width = header[ 7 ], @@ -105,15 +103,15 @@ PVRLoader._parseV3 = function ( pvrDatas ) { pvrDatas.numMipmaps = numMipmaps; pvrDatas.isCubemap = ( numFaces === 6 ); - return PVRLoader._extract( pvrDatas ); + return _extract( pvrDatas ); -}; +} -PVRLoader._parseV2 = function ( pvrDatas ) { +function _parseV2( pvrDatas ) { - var header = pvrDatas.header; + const header = pvrDatas.header; - var headerLength = header[ 0 ], + const headerLength = header[ 0 ], height = header[ 1 ], width = header[ 2 ], numMipmaps = header[ 3 ], @@ -128,14 +126,14 @@ PVRLoader._parseV2 = function ( pvrDatas ) { numSurfs = header[ 12 ]; - var TYPE_MASK = 0xff; - var PVRTC_2 = 24, + const TYPE_MASK = 0xff; + const PVRTC_2 = 24, PVRTC_4 = 25; - var formatFlags = flags & TYPE_MASK; + const formatFlags = flags & TYPE_MASK; - var bpp, format; - var _hasAlpha = bitmaskAlpha > 0; + let bpp, format; + const _hasAlpha = bitmaskAlpha > 0; if ( formatFlags === PVRTC_4 ) { @@ -165,14 +163,14 @@ PVRLoader._parseV2 = function ( pvrDatas ) { // it juste a pvr containing 6 surface (no explicit cubemap type) pvrDatas.isCubemap = ( numSurfs === 6 ); - return PVRLoader._extract( pvrDatas ); + return _extract( pvrDatas ); -}; +} -PVRLoader._extract = function ( pvrDatas ) { +function _extract( pvrDatas ) { - var pvr = { + const pvr = { mipmaps: [], width: pvrDatas.width, height: pvrDatas.height, @@ -181,11 +179,9 @@ PVRLoader._extract = function ( pvrDatas ) { isCubemap: pvrDatas.isCubemap }; - var buffer = pvrDatas.buffer; + const buffer = pvrDatas.buffer; - var dataOffset = pvrDatas.dataPtr, - bpp = pvrDatas.bpp, - numSurfs = pvrDatas.numSurfaces, + let dataOffset = pvrDatas.dataPtr, dataSize = 0, blockSize = 0, blockWidth = 0, @@ -193,6 +189,9 @@ PVRLoader._extract = function ( pvrDatas ) { widthBlocks = 0, heightBlocks = 0; + const bpp = pvrDatas.bpp, + numSurfs = pvrDatas.numSurfaces; + if ( bpp === 2 ) { blockWidth = 8; @@ -209,11 +208,11 @@ PVRLoader._extract = function ( pvrDatas ) { pvr.mipmaps.length = pvrDatas.numMipmaps * numSurfs; - var mipLevel = 0; + let mipLevel = 0; while ( mipLevel < pvrDatas.numMipmaps ) { - var sWidth = pvrDatas.width >> mipLevel, + const sWidth = pvrDatas.width >> mipLevel, sHeight = pvrDatas.height >> mipLevel; widthBlocks = sWidth / blockWidth; @@ -225,11 +224,11 @@ PVRLoader._extract = function ( pvrDatas ) { dataSize = widthBlocks * heightBlocks * blockSize; - for ( var surfIndex = 0; surfIndex < numSurfs; surfIndex ++ ) { + for ( let surfIndex = 0; surfIndex < numSurfs; surfIndex ++ ) { - var byteArray = new Uint8Array( buffer, dataOffset, dataSize ); + const byteArray = new Uint8Array( buffer, dataOffset, dataSize ); - var mipmap = { + const mipmap = { data: byteArray, width: sWidth, height: sHeight @@ -247,6 +246,6 @@ PVRLoader._extract = function ( pvrDatas ) { return pvr; -}; +} export { PVRLoader }; diff --git a/examples/jsm/loaders/RGBELoader.js b/examples/jsm/loaders/RGBELoader.js index 9bfd6aa4ff3db9..0daadeff2aa2fa 100644 --- a/examples/jsm/loaders/RGBELoader.js +++ b/examples/jsm/loaders/RGBELoader.js @@ -15,23 +15,21 @@ import { // https://github.com/mrdoob/three.js/issues/5552 // http://en.wikipedia.org/wiki/RGBE_image_format -var RGBELoader = function ( manager ) { +class RGBELoader extends DataTextureLoader { - DataTextureLoader.call( this, manager ); + constructor( manager ) { - this.type = UnsignedByteType; + super( manager ); -}; + this.type = UnsignedByteType; -RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype ), { - - constructor: RGBELoader, + } // adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html - parse: function ( buffer ) { + parse( buffer ) { - var + const /* return codes for rgbe routines */ //RGBE_RETURN_SUCCESS = 0, RGBE_RETURN_FAILURE = - 1, @@ -77,11 +75,13 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype fgets = function ( buffer, lineLimit, consume ) { + const chunkSize = 128; + lineLimit = ! lineLimit ? 1024 : lineLimit; - var p = buffer.pos, - i = - 1, len = 0, s = '', chunkSize = 128, - chunk = String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) ) - ; + let p = buffer.pos, + i = - 1, len = 0, s = '', + chunk = String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) ); + while ( ( 0 > ( i = chunk.indexOf( NEWLINE ) ) ) && ( len < lineLimit ) && ( p < buffer.byteLength ) ) { s += chunk; len += chunk.length; @@ -110,10 +110,9 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype /* minimal header reading. modify if you want to parse more information */ RGBE_ReadHeader = function ( buffer ) { - var line, match, - // regexes to parse header info fields - magic_token_re = /^#\?(\S+)/, + // regexes to parse header info fields + const magic_token_re = /^#\?(\S+)/, gamma_re = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/, exposure_re = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/, format_re = /^\s*FORMAT=(\S+)\s*$/, @@ -140,6 +139,8 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype }; + let line, match; + if ( buffer.pos >= buffer.byteLength || ! ( line = fgets( buffer ) ) ) { return rgbe_error( rgbe_read_error, 'no header found' ); @@ -219,10 +220,7 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype RGBE_ReadPixels_RLE = function ( buffer, w, h ) { - var data_rgba, offset, pos, count, byteValue, - scanline_buffer, ptr, ptr_end, i, l, off, isEncodedRun, - scanline_width = w, num_scanlines = h, rgbeStart - ; + const scanline_width = w; if ( // run length encoding is not allowed so read flat @@ -242,7 +240,7 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype } - data_rgba = new Uint8Array( 4 * w * h ); + const data_rgba = new Uint8Array( 4 * w * h ); if ( ! data_rgba.length ) { @@ -250,9 +248,12 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype } - offset = 0; pos = 0; ptr_end = 4 * scanline_width; - rgbeStart = new Uint8Array( 4 ); - scanline_buffer = new Uint8Array( ptr_end ); + let offset = 0, pos = 0; + + const ptr_end = 4 * scanline_width; + const rgbeStart = new Uint8Array( 4 ); + const scanline_buffer = new Uint8Array( ptr_end ); + let num_scanlines = h; // read in each successive scanline while ( ( num_scanlines > 0 ) && ( pos < buffer.byteLength ) ) { @@ -276,11 +277,12 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype // read each of the four channels for the scanline into the buffer // first red, then green, then blue, then exponent - ptr = 0; + let ptr = 0, count; + while ( ( ptr < ptr_end ) && ( pos < buffer.byteLength ) ) { count = buffer[ pos ++ ]; - isEncodedRun = count > 128; + const isEncodedRun = count > 128; if ( isEncodedRun ) count -= 128; if ( ( 0 === count ) || ( ptr + count > ptr_end ) ) { @@ -292,8 +294,8 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype if ( isEncodedRun ) { // a (encoded) run of the same value - byteValue = buffer[ pos ++ ]; - for ( i = 0; i < count; i ++ ) { + const byteValue = buffer[ pos ++ ]; + for ( let i = 0; i < count; i ++ ) { scanline_buffer[ ptr ++ ] = byteValue; @@ -313,10 +315,10 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype // now convert data from buffer into rgba // first red, then green, then blue, then exponent (alpha) - l = scanline_width; //scanline_buffer.byteLength; - for ( i = 0; i < l; i ++ ) { + const l = scanline_width; //scanline_buffer.byteLength; + for ( let i = 0; i < l; i ++ ) { - off = 0; + let off = 0; data_rgba[ offset ] = scanline_buffer[ i + off ]; off += scanline_width; //1; data_rgba[ offset + 1 ] = scanline_buffer[ i + off ]; @@ -336,10 +338,10 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype }; - var RGBEByteToRGBFloat = function ( sourceArray, sourceOffset, destArray, destOffset ) { + const RGBEByteToRGBFloat = function ( sourceArray, sourceOffset, destArray, destOffset ) { - var e = sourceArray[ sourceOffset + 3 ]; - var scale = Math.pow( 2.0, e - 128.0 ) / 255.0; + const e = sourceArray[ sourceOffset + 3 ]; + const scale = Math.pow( 2.0, e - 128.0 ) / 255.0; destArray[ destOffset + 0 ] = sourceArray[ sourceOffset + 0 ] * scale; destArray[ destOffset + 1 ] = sourceArray[ sourceOffset + 1 ] * scale; @@ -347,10 +349,10 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype }; - var RGBEByteToRGBHalf = function ( sourceArray, sourceOffset, destArray, destOffset ) { + const RGBEByteToRGBHalf = function ( sourceArray, sourceOffset, destArray, destOffset ) { - var e = sourceArray[ sourceOffset + 3 ]; - var scale = Math.pow( 2.0, e - 128.0 ) / 255.0; + const e = sourceArray[ sourceOffset + 3 ]; + const scale = Math.pow( 2.0, e - 128.0 ) / 255.0; destArray[ destOffset + 0 ] = DataUtils.toHalfFloat( sourceArray[ sourceOffset + 0 ] * scale ); destArray[ destOffset + 1 ] = DataUtils.toHalfFloat( sourceArray[ sourceOffset + 1 ] * scale ); @@ -358,57 +360,60 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype }; - var byteArray = new Uint8Array( buffer ); + const byteArray = new Uint8Array( buffer ); byteArray.pos = 0; - var rgbe_header_info = RGBE_ReadHeader( byteArray ); + const rgbe_header_info = RGBE_ReadHeader( byteArray ); if ( RGBE_RETURN_FAILURE !== rgbe_header_info ) { - var w = rgbe_header_info.width, + const w = rgbe_header_info.width, h = rgbe_header_info.height, image_rgba_data = RGBE_ReadPixels_RLE( byteArray.subarray( byteArray.pos ), w, h ); if ( RGBE_RETURN_FAILURE !== image_rgba_data ) { + let data, format, type; + let numElements; + switch ( this.type ) { case UnsignedByteType: - var data = image_rgba_data; - var format = RGBEFormat; // handled as THREE.RGBAFormat in shaders - var type = UnsignedByteType; + data = image_rgba_data; + format = RGBEFormat; // handled as THREE.RGBAFormat in shaders + type = UnsignedByteType; break; case FloatType: - var numElements = ( image_rgba_data.length / 4 ) * 3; - var floatArray = new Float32Array( numElements ); + numElements = ( image_rgba_data.length / 4 ) * 3; + const floatArray = new Float32Array( numElements ); - for ( var j = 0; j < numElements; j ++ ) { + for ( let j = 0; j < numElements; j ++ ) { RGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 3 ); } - var data = floatArray; - var format = RGBFormat; - var type = FloatType; + data = floatArray; + format = RGBFormat; + type = FloatType; break; case HalfFloatType: - var numElements = ( image_rgba_data.length / 4 ) * 3; - var halfArray = new Uint16Array( numElements ); + numElements = ( image_rgba_data.length / 4 ) * 3; + const halfArray = new Uint16Array( numElements ); - for ( var j = 0; j < numElements; j ++ ) { + for ( let j = 0; j < numElements; j ++ ) { RGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 3 ); } - var data = halfArray; - var format = RGBFormat; - var type = HalfFloatType; + data = halfArray; + format = RGBFormat; + type = HalfFloatType; break; default: @@ -434,16 +439,16 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype return null; - }, + } - setDataType: function ( value ) { + setDataType( value ) { this.type = value; return this; - }, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { function onLoadCallback( texture, texData ) { @@ -482,10 +487,10 @@ RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype } - return DataTextureLoader.prototype.load.call( this, url, onLoadCallback, onProgress, onError ); + return super.load( url, onLoadCallback, onProgress, onError ); } -} ); +} export { RGBELoader }; diff --git a/examples/jsm/loaders/STLLoader.js b/examples/jsm/loaders/STLLoader.js index e00c68bce524a6..00d91d313f3612 100644 --- a/examples/jsm/loaders/STLLoader.js +++ b/examples/jsm/loaders/STLLoader.js @@ -21,7 +21,7 @@ import { * ASCII decoding assumes file is UTF-8. * * Usage: - * var loader = new STLLoader(); + * const loader = new STLLoader(); * loader.load( './models/stl/slotted_disk.stl', function ( geometry ) { * scene.add( new THREE.Mesh( geometry ) ); * }); @@ -31,24 +31,24 @@ import { * if (geometry.hasColors) { * material = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: true }); * } else { .... } - * var mesh = new THREE.Mesh( geometry, material ); + * const mesh = new THREE.Mesh( geometry, material ); * * For ASCII STLs containing multiple solids, each solid is assigned to a different group. * Groups can be used to assign a different color by defining an array of materials with the same length of * geometry.groups and passing it to the Mesh constructor: * - * var mesh = new THREE.Mesh( geometry, material ); + * const mesh = new THREE.Mesh( geometry, material ); * * For example: * - * var materials = []; - * var nGeometryGroups = geometry.groups.length; + * const materials = []; + * const nGeometryGroups = geometry.groups.length; * - * var colorMap = ...; // Some logic to index colors. + * const colorMap = ...; // Some logic to index colors. * - * for (var i = 0; i < nGeometryGroups; i++) { + * for (let i = 0; i < nGeometryGroups; i++) { * - * var material = new THREE.MeshPhongMaterial({ + * const material = new THREE.MeshPhongMaterial({ * color: colorMap[i], * wireframe: false * }); @@ -56,25 +56,23 @@ import { * } * * materials.push(material); - * var mesh = new THREE.Mesh(geometry, materials); + * const mesh = new THREE.Mesh(geometry, materials); */ -var STLLoader = function ( manager ) { +class STLLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { -}; + super( manager ); -STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: STLLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var loader = new FileLoader( this.manager ); + const loader = new FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( this.requestHeader ); @@ -104,17 +102,16 @@ STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } - parse: function ( data ) { + parse( data ) { function isBinary( data ) { - var expect, face_size, n_faces, reader; - reader = new DataView( data ); - face_size = ( 32 / 8 * 3 ) + ( ( 32 / 8 * 3 ) * 3 ) + ( 16 / 8 ); - n_faces = reader.getUint32( 80, true ); - expect = 80 + ( 32 / 8 ) + ( n_faces * face_size ); + const reader = new DataView( data ); + const face_size = ( 32 / 8 * 3 ) + ( ( 32 / 8 * 3 ) * 3 ) + ( 16 / 8 ); + const n_faces = reader.getUint32( 80, true ); + const expect = 80 + ( 32 / 8 ) + ( n_faces * face_size ); if ( expect === reader.byteLength ) { @@ -132,9 +129,9 @@ STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // US-ASCII ordinal values for 's', 'o', 'l', 'i', 'd' - var solid = [ 115, 111, 108, 105, 100 ]; + const solid = [ 115, 111, 108, 105, 100 ]; - for ( var off = 0; off < 5; off ++ ) { + for ( let off = 0; off < 5; off ++ ) { // If "solid" text is matched to the current offset, declare it to be an ASCII STL. @@ -152,7 +149,7 @@ STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // Check if each byte in query matches the corresponding byte from the current offset - for ( var i = 0, il = query.length; i < il; i ++ ) { + for ( let i = 0, il = query.length; i < il; i ++ ) { if ( query[ i ] !== reader.getUint8( offset + i, false ) ) return false; @@ -164,16 +161,16 @@ STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseBinary( data ) { - var reader = new DataView( data ); - var faces = reader.getUint32( 80, true ); + const reader = new DataView( data ); + const faces = reader.getUint32( 80, true ); - var r, g, b, hasColors = false, colors; - var defaultR, defaultG, defaultB, alpha; + let r, g, b, hasColors = false, colors; + let defaultR, defaultG, defaultB, alpha; // process STL header // check for default color in header ("COLOR=rgba" sequence). - for ( var index = 0; index < 80 - 10; index ++ ) { + for ( let index = 0; index < 80 - 10; index ++ ) { if ( ( reader.getUint32( index, false ) == 0x434F4C4F /*COLO*/ ) && ( reader.getUint8( index + 4 ) == 0x52 /*'R'*/ ) && @@ -191,24 +188,24 @@ STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var dataOffset = 84; - var faceLength = 12 * 4 + 2; + const dataOffset = 84; + const faceLength = 12 * 4 + 2; - var geometry = new BufferGeometry(); + const geometry = new BufferGeometry(); - var vertices = new Float32Array( faces * 3 * 3 ); - var normals = new Float32Array( faces * 3 * 3 ); + const vertices = new Float32Array( faces * 3 * 3 ); + const normals = new Float32Array( faces * 3 * 3 ); - for ( var face = 0; face < faces; face ++ ) { + for ( let face = 0; face < faces; face ++ ) { - var start = dataOffset + face * faceLength; - var normalX = reader.getFloat32( start, true ); - var normalY = reader.getFloat32( start + 4, true ); - var normalZ = reader.getFloat32( start + 8, true ); + const start = dataOffset + face * faceLength; + const normalX = reader.getFloat32( start, true ); + const normalY = reader.getFloat32( start + 4, true ); + const normalZ = reader.getFloat32( start + 8, true ); if ( hasColors ) { - var packedColor = reader.getUint16( start + 48, true ); + const packedColor = reader.getUint16( start + 48, true ); if ( ( packedColor & 0x8000 ) === 0 ) { @@ -228,10 +225,10 @@ STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - for ( var i = 1; i <= 3; i ++ ) { + for ( let i = 1; i <= 3; i ++ ) { - var vertexstart = start + i * 12; - var componentIdx = ( face * 3 * 3 ) + ( ( i - 1 ) * 3 ); + const vertexstart = start + i * 12; + const componentIdx = ( face * 3 * 3 ) + ( ( i - 1 ) * 3 ); vertices[ componentIdx ] = reader.getFloat32( vertexstart, true ); vertices[ componentIdx + 1 ] = reader.getFloat32( vertexstart + 4, true ); @@ -270,38 +267,38 @@ STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function parseASCII( data ) { - var geometry = new BufferGeometry(); - var patternSolid = /solid([\s\S]*?)endsolid/g; - var patternFace = /facet([\s\S]*?)endfacet/g; - var faceCounter = 0; + const geometry = new BufferGeometry(); + const patternSolid = /solid([\s\S]*?)endsolid/g; + const patternFace = /facet([\s\S]*?)endfacet/g; + let faceCounter = 0; - var patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source; - var patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' ); - var patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' ); + const patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source; + const patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' ); + const patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' ); - var vertices = []; - var normals = []; + const vertices = []; + const normals = []; - var normal = new Vector3(); + const normal = new Vector3(); - var result; + let result; - var groupCount = 0; - var startVertex = 0; - var endVertex = 0; + let groupCount = 0; + let startVertex = 0; + let endVertex = 0; while ( ( result = patternSolid.exec( data ) ) !== null ) { startVertex = endVertex; - var solid = result[ 0 ]; + const solid = result[ 0 ]; while ( ( result = patternFace.exec( solid ) ) !== null ) { - var vertexCountPerFace = 0; - var normalCountPerFace = 0; + let vertexCountPerFace = 0; + let normalCountPerFace = 0; - var text = result[ 0 ]; + const text = result[ 0 ]; while ( ( result = patternNormal.exec( text ) ) !== null ) { @@ -341,8 +338,8 @@ STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - var start = startVertex; - var count = endVertex - startVertex; + const start = startVertex; + const count = endVertex - startVertex; geometry.addGroup( start, count, groupCount ); groupCount ++; @@ -372,8 +369,8 @@ STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { if ( typeof buffer === 'string' ) { - var array_buffer = new Uint8Array( buffer.length ); - for ( var i = 0; i < buffer.length; i ++ ) { + const array_buffer = new Uint8Array( buffer.length ); + for ( let i = 0; i < buffer.length; i ++ ) { array_buffer[ i ] = buffer.charCodeAt( i ) & 0xff; // implicitly assumes little-endian @@ -391,12 +388,12 @@ STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { // start - var binData = ensureBinary( data ); + const binData = ensureBinary( data ); return isBinary( binData ) ? parseBinary( binData ) : parseASCII( ensureString( data ) ); } -} ); +} export { STLLoader }; diff --git a/examples/jsm/loaders/TDSLoader.js b/examples/jsm/loaders/TDSLoader.js index 1d75df4be011a5..65eb3515e11d57 100644 --- a/examples/jsm/loaders/TDSLoader.js +++ b/examples/jsm/loaders/TDSLoader.js @@ -23,23 +23,21 @@ import { * @constructor */ -var TDSLoader = function ( manager ) { +class TDSLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { - this.debug = false; + super( manager ); - this.group = null; - this.position = 0; + this.debug = false; - this.materials = []; - this.meshes = []; - -}; + this.group = null; + this.position = 0; -TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + this.materials = []; + this.meshes = []; - constructor: TDSLoader, + } /** * Load 3ds file from url. @@ -50,13 +48,13 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {Function} onProgress onProgress callback. * @param {Function} onError onError callback. */ - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; - var loader = new FileLoader( this.manager ); + const loader = new FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( this.requestHeader ); @@ -86,7 +84,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } /** * Parse arraybuffer data and load 3ds file. @@ -96,7 +94,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {String} path Path for external resources. * @return {Group} Group loaded from 3ds file. */ - parse: function ( arraybuffer, path ) { + parse( arraybuffer, path ) { this.group = new Group(); this.position = 0; @@ -105,7 +103,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { this.readFile( arraybuffer, path ); - for ( var i = 0; i < this.meshes.length; i ++ ) { + for ( let i = 0; i < this.meshes.length; i ++ ) { this.group.add( this.meshes[ i ] ); @@ -113,7 +111,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { return this.group; - }, + } /** * Decode file content to read 3ds data. @@ -122,20 +120,20 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {ArrayBuffer} arraybuffer Arraybuffer data to be loaded. * @param {String} path Path for external resources. */ - readFile: function ( arraybuffer, path ) { + readFile( arraybuffer, path ) { - var data = new DataView( arraybuffer ); - var chunk = this.readChunk( data ); + const data = new DataView( arraybuffer ); + const chunk = this.readChunk( data ); if ( chunk.id === MLIBMAGIC || chunk.id === CMAGIC || chunk.id === M3DMAGIC ) { - var next = this.nextChunk( data, chunk ); + let next = this.nextChunk( data, chunk ); while ( next !== 0 ) { if ( next === M3D_VERSION ) { - var version = this.readDWord( data ); + const version = this.readDWord( data ); this.debugMessage( '3DS file version: ' + version ); } else if ( next === MDATA ) { @@ -157,7 +155,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { this.debugMessage( 'Parsed ' + this.meshes.length + ' meshes' ); - }, + } /** * Read mesh data chunk. @@ -166,21 +164,21 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {Dataview} data Dataview in use. * @param {String} path Path for external resources. */ - readMeshData: function ( data, path ) { + readMeshData( data, path ) { - var chunk = this.readChunk( data ); - var next = this.nextChunk( data, chunk ); + const chunk = this.readChunk( data ); + let next = this.nextChunk( data, chunk ); while ( next !== 0 ) { if ( next === MESH_VERSION ) { - var version = + this.readDWord( data ); + const version = + this.readDWord( data ); this.debugMessage( 'Mesh Version: ' + version ); } else if ( next === MASTER_SCALE ) { - var scale = this.readFloat( data ); + const scale = this.readFloat( data ); this.debugMessage( 'Master scale: ' + scale ); this.group.scale.set( scale, scale, scale ); @@ -206,7 +204,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - }, + } /** * Read named object chunk. @@ -214,19 +212,19 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @method readNamedObject * @param {Dataview} data Dataview in use. */ - readNamedObject: function ( data ) { + readNamedObject( data ) { - var chunk = this.readChunk( data ); - var name = this.readString( data, 64 ); + const chunk = this.readChunk( data ); + const name = this.readString( data, 64 ); chunk.cur = this.position; - var next = this.nextChunk( data, chunk ); + let next = this.nextChunk( data, chunk ); while ( next !== 0 ) { if ( next === N_TRI_OBJECT ) { this.resetPosition( data ); - var mesh = this.readMesh( data ); + const mesh = this.readMesh( data ); mesh.name = name; this.meshes.push( mesh ); @@ -242,7 +240,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { this.endChunk( chunk ); - }, + } /** * Read material data chunk and add it to the material list. @@ -251,11 +249,11 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {Dataview} data Dataview in use. * @param {String} path Path for external resources. */ - readMaterialEntry: function ( data, path ) { + readMaterialEntry( data, path ) { - var chunk = this.readChunk( data ); - var next = this.nextChunk( data, chunk ); - var material = new MeshPhongMaterial(); + const chunk = this.readChunk( data ); + let next = this.nextChunk( data, chunk ); + const material = new MeshPhongMaterial(); while ( next !== 0 ) { @@ -271,7 +269,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else if ( next === MAT_WIRE_SIZE ) { - var value = this.readByte( data ); + const value = this.readByte( data ); material.wireframeLinewidth = value; this.debugMessage( ' Wireframe Thickness: ' + value ); @@ -302,13 +300,13 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else if ( next === MAT_SHININESS ) { - var shininess = this.readPercentage( data ); + const shininess = this.readPercentage( data ); material.shininess = shininess * 100; this.debugMessage( ' Shininess : ' + shininess ); } else if ( next === MAT_TRANSPARENCY ) { - var transparency = this.readPercentage( data ); + const transparency = this.readPercentage( data ); material.opacity = 1 - transparency; this.debugMessage( ' Transparency : ' + transparency ); material.transparent = material.opacity < 1 ? true : false; @@ -351,7 +349,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { this.materials[ material.name ] = material; - }, + } /** * Read mesh data chunk. @@ -360,31 +358,30 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {Dataview} data Dataview in use. * @return {Mesh} The parsed mesh. */ - readMesh: function ( data ) { + readMesh( data ) { - var chunk = this.readChunk( data ); - var next = this.nextChunk( data, chunk ); + const chunk = this.readChunk( data ); + let next = this.nextChunk( data, chunk ); - var geometry = new BufferGeometry(); - var uvs = []; + const geometry = new BufferGeometry(); - var material = new MeshPhongMaterial(); - var mesh = new Mesh( geometry, material ); + const material = new MeshPhongMaterial(); + const mesh = new Mesh( geometry, material ); mesh.name = 'mesh'; while ( next !== 0 ) { if ( next === POINT_ARRAY ) { - var points = this.readWord( data ); + const points = this.readWord( data ); this.debugMessage( ' Vertex: ' + points ); //BufferGeometry - var vertices = []; + const vertices = []; - for ( var i = 0; i < points; i ++ ) { + for ( let i = 0; i < points; i ++ ) { vertices.push( this.readFloat( data ) ); vertices.push( this.readFloat( data ) ); @@ -401,15 +398,15 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else if ( next === TEX_VERTS ) { - var texels = this.readWord( data ); + const texels = this.readWord( data ); this.debugMessage( ' UV: ' + texels ); //BufferGeometry - var uvs = []; + const uvs = []; - for ( var i = 0; i < texels; i ++ ) { + for ( let i = 0; i < texels; i ++ ) { uvs.push( this.readFloat( data ) ); uvs.push( this.readFloat( data ) ); @@ -423,14 +420,14 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { this.debugMessage( ' Tranformation Matrix (TODO)' ); - var values = []; - for ( var i = 0; i < 12; i ++ ) { + const values = []; + for ( let i = 0; i < 12; i ++ ) { values[ i ] = this.readFloat( data ); } - var matrix = new Matrix4(); + const matrix = new Matrix4(); //X Line matrix.elements[ 0 ] = values[ 0 ]; @@ -458,7 +455,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { matrix.transpose(); - var inverse = new Matrix4(); + const inverse = new Matrix4(); inverse.copy( matrix ).invert(); geometry.applyMatrix4( inverse ); @@ -480,7 +477,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { return mesh; - }, + } /** * Read face array data chunk. @@ -489,16 +486,16 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {Dataview} data Dataview in use. * @param {Mesh} mesh Mesh to be filled with the data read. */ - readFaceArray: function ( data, mesh ) { + readFaceArray( data, mesh ) { - var chunk = this.readChunk( data ); - var faces = this.readWord( data ); + const chunk = this.readChunk( data ); + const faces = this.readWord( data ); this.debugMessage( ' Faces: ' + faces ); - var index = []; + const index = []; - for ( var i = 0; i < faces; ++ i ) { + for ( let i = 0; i < faces; ++ i ) { index.push( this.readWord( data ), this.readWord( data ), this.readWord( data ) ); @@ -510,12 +507,12 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { //The rest of the FACE_ARRAY chunk is subchunks - var materialIndex = 0; - var start = 0; + let materialIndex = 0; + let start = 0; while ( this.position < chunk.end ) { - var subchunk = this.readChunk( data ); + const subchunk = this.readChunk( data ); if ( subchunk.id === MSH_MAT_GROUP ) { @@ -523,15 +520,15 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { this.resetPosition( data ); - var group = this.readMaterialGroup( data ); - var count = group.index.length * 3; // assuming successive indices + const group = this.readMaterialGroup( data ); + const count = group.index.length * 3; // assuming successive indices mesh.geometry.addGroup( start, count, materialIndex ); start += count; materialIndex ++; - var material = this.materials[ group.name ]; + const material = this.materials[ group.name ]; if ( Array.isArray( mesh.material ) === false ) mesh.material = []; @@ -555,7 +552,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { this.endChunk( chunk ); - }, + } /** * Read texture map data chunk. @@ -565,20 +562,20 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {String} path Path for external resources. * @return {Texture} Texture read from this data chunk. */ - readMap: function ( data, path ) { + readMap( data, path ) { - var chunk = this.readChunk( data ); - var next = this.nextChunk( data, chunk ); - var texture = {}; + const chunk = this.readChunk( data ); + let next = this.nextChunk( data, chunk ); + let texture = {}; - var loader = new TextureLoader( this.manager ); + const loader = new TextureLoader( this.manager ); loader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin ); while ( next !== 0 ) { if ( next === MAT_MAPNAME ) { - var name = this.readString( data, 128 ); + const name = this.readString( data, 128 ); texture = loader.load( name ); this.debugMessage( ' File: ' + path + name ); @@ -617,7 +614,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { return texture; - }, + } /** * Read material group data chunk. @@ -626,17 +623,17 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {Dataview} data Dataview in use. * @return {Object} Object with name and index of the object. */ - readMaterialGroup: function ( data ) { + readMaterialGroup( data ) { this.readChunk( data ); - var name = this.readString( data, 64 ); - var numFaces = this.readWord( data ); + const name = this.readString( data, 64 ); + const numFaces = this.readWord( data ); this.debugMessage( ' Name: ' + name ); this.debugMessage( ' Faces: ' + numFaces ); - var index = []; - for ( var i = 0; i < numFaces; ++ i ) { + const index = []; + for ( let i = 0; i < numFaces; ++ i ) { index.push( this.readWord( data ) ); @@ -644,7 +641,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { return { name: name, index: index }; - }, + } /** * Read a color value. @@ -653,16 +650,16 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {DataView} data Dataview. * @return {Color} Color value read.. */ - readColor: function ( data ) { + readColor( data ) { - var chunk = this.readChunk( data ); - var color = new Color(); + const chunk = this.readChunk( data ); + const color = new Color(); if ( chunk.id === COLOR_24 || chunk.id === LIN_COLOR_24 ) { - var r = this.readByte( data ); - var g = this.readByte( data ); - var b = this.readByte( data ); + const r = this.readByte( data ); + const g = this.readByte( data ); + const b = this.readByte( data ); color.setRGB( r / 255, g / 255, b / 255 ); @@ -670,9 +667,9 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } else if ( chunk.id === COLOR_F || chunk.id === LIN_COLOR_F ) { - var r = this.readFloat( data ); - var g = this.readFloat( data ); - var b = this.readFloat( data ); + const r = this.readFloat( data ); + const g = this.readFloat( data ); + const b = this.readFloat( data ); color.setRGB( r, g, b ); @@ -687,7 +684,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { this.endChunk( chunk ); return color; - }, + } /** * Read next chunk of data. @@ -696,9 +693,9 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {DataView} data Dataview. * @return {Object} Chunk of data read. */ - readChunk: function ( data ) { + readChunk( data ) { - var chunk = {}; + const chunk = {}; chunk.cur = this.position; chunk.id = this.readWord( data ); @@ -708,7 +705,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { return chunk; - }, + } /** * Set position to the end of the current chunk of data. @@ -716,11 +713,11 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @method endChunk * @param {Object} chunk Data chunk. */ - endChunk: function ( chunk ) { + endChunk( chunk ) { this.position = chunk.end; - }, + } /** * Move to the next data chunk. @@ -729,7 +726,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {DataView} data Dataview. * @param {Object} chunk Data chunk. */ - nextChunk: function ( data, chunk ) { + nextChunk( data, chunk ) { if ( chunk.cur >= chunk.end ) { @@ -741,7 +738,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { try { - var next = this.readChunk( data ); + const next = this.readChunk( data ); chunk.cur += next.size; return next.id; @@ -752,18 +749,18 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - }, + } /** * Reset dataview position. * * @method resetPosition */ - resetPosition: function () { + resetPosition() { this.position -= 6; - }, + } /** * Read byte value. @@ -772,13 +769,13 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readByte: function ( data ) { + readByte( data ) { - var v = data.getUint8( this.position, true ); + const v = data.getUint8( this.position, true ); this.position += 1; return v; - }, + } /** * Read 32 bit float value. @@ -787,11 +784,11 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readFloat: function ( data ) { + readFloat( data ) { try { - var v = data.getFloat32( this.position, true ); + const v = data.getFloat32( this.position, true ); this.position += 4; return v; @@ -801,7 +798,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } - }, + } /** * Read 32 bit signed integer value. @@ -810,13 +807,13 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readInt: function ( data ) { + readInt( data ) { - var v = data.getInt32( this.position, true ); + const v = data.getInt32( this.position, true ); this.position += 4; return v; - }, + } /** * Read 16 bit signed integer value. @@ -825,13 +822,13 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readShort: function ( data ) { + readShort( data ) { - var v = data.getInt16( this.position, true ); + const v = data.getInt16( this.position, true ); this.position += 2; return v; - }, + } /** * Read 64 bit unsigned integer value. @@ -840,13 +837,13 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readDWord: function ( data ) { + readDWord( data ) { - var v = data.getUint32( this.position, true ); + const v = data.getUint32( this.position, true ); this.position += 4; return v; - }, + } /** * Read 32 bit unsigned integer value. @@ -855,13 +852,13 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readWord: function ( data ) { + readWord( data ) { - var v = data.getUint16( this.position, true ); + const v = data.getUint16( this.position, true ); this.position += 2; return v; - }, + } /** * Read string value. @@ -871,13 +868,13 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {Number} maxLength Max size of the string to be read. * @return {String} Data read from the dataview. */ - readString: function ( data, maxLength ) { + readString( data, maxLength ) { - var s = ''; + let s = ''; - for ( var i = 0; i < maxLength; i ++ ) { + for ( let i = 0; i < maxLength; i ++ ) { - var c = this.readByte( data ); + const c = this.readByte( data ); if ( ! c ) { break; @@ -890,7 +887,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { return s; - }, + } /** * Read percentage value. @@ -899,10 +896,10 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ - readPercentage: function ( data ) { + readPercentage( data ) { - var chunk = this.readChunk( data ); - var value; + const chunk = this.readChunk( data ); + let value; switch ( chunk.id ) { @@ -923,7 +920,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { return value; - }, + } /** * Print debug message to the console. @@ -933,7 +930,7 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { * @method debugMessage * @param {Object} message Debug message to print to the console. */ - debugMessage: function ( message ) { + debugMessage( message ) { if ( this.debug ) { @@ -943,224 +940,224 @@ TDSLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } -} ); - -// var NULL_CHUNK = 0x0000; -var M3DMAGIC = 0x4D4D; -// var SMAGIC = 0x2D2D; -// var LMAGIC = 0x2D3D; -var MLIBMAGIC = 0x3DAA; -// var MATMAGIC = 0x3DFF; -var CMAGIC = 0xC23D; -var M3D_VERSION = 0x0002; -// var M3D_KFVERSION = 0x0005; -var COLOR_F = 0x0010; -var COLOR_24 = 0x0011; -var LIN_COLOR_24 = 0x0012; -var LIN_COLOR_F = 0x0013; -var INT_PERCENTAGE = 0x0030; -var FLOAT_PERCENTAGE = 0x0031; -var MDATA = 0x3D3D; -var MESH_VERSION = 0x3D3E; -var MASTER_SCALE = 0x0100; -// var LO_SHADOW_BIAS = 0x1400; -// var HI_SHADOW_BIAS = 0x1410; -// var SHADOW_MAP_SIZE = 0x1420; -// var SHADOW_SAMPLES = 0x1430; -// var SHADOW_RANGE = 0x1440; -// var SHADOW_FILTER = 0x1450; -// var RAY_BIAS = 0x1460; -// var O_CONSTS = 0x1500; -// var AMBIENT_LIGHT = 0x2100; -// var BIT_MAP = 0x1100; -// var SOLID_BGND = 0x1200; -// var V_GRADIENT = 0x1300; -// var USE_BIT_MAP = 0x1101; -// var USE_SOLID_BGND = 0x1201; -// var USE_V_GRADIENT = 0x1301; -// var FOG = 0x2200; -// var FOG_BGND = 0x2210; -// var LAYER_FOG = 0x2302; -// var DISTANCE_CUE = 0x2300; -// var DCUE_BGND = 0x2310; -// var USE_FOG = 0x2201; -// var USE_LAYER_FOG = 0x2303; -// var USE_DISTANCE_CUE = 0x2301; -var MAT_ENTRY = 0xAFFF; -var MAT_NAME = 0xA000; -var MAT_AMBIENT = 0xA010; -var MAT_DIFFUSE = 0xA020; -var MAT_SPECULAR = 0xA030; -var MAT_SHININESS = 0xA040; -// var MAT_SHIN2PCT = 0xA041; -var MAT_TRANSPARENCY = 0xA050; -// var MAT_XPFALL = 0xA052; -// var MAT_USE_XPFALL = 0xA240; -// var MAT_REFBLUR = 0xA053; -// var MAT_SHADING = 0xA100; -// var MAT_USE_REFBLUR = 0xA250; -// var MAT_SELF_ILLUM = 0xA084; -var MAT_TWO_SIDE = 0xA081; -// var MAT_DECAL = 0xA082; -var MAT_ADDITIVE = 0xA083; -var MAT_WIRE = 0xA085; -// var MAT_FACEMAP = 0xA088; -// var MAT_TRANSFALLOFF_IN = 0xA08A; -// var MAT_PHONGSOFT = 0xA08C; -// var MAT_WIREABS = 0xA08E; -var MAT_WIRE_SIZE = 0xA087; -var MAT_TEXMAP = 0xA200; -// var MAT_SXP_TEXT_DATA = 0xA320; -// var MAT_TEXMASK = 0xA33E; -// var MAT_SXP_TEXTMASK_DATA = 0xA32A; -// var MAT_TEX2MAP = 0xA33A; -// var MAT_SXP_TEXT2_DATA = 0xA321; -// var MAT_TEX2MASK = 0xA340; -// var MAT_SXP_TEXT2MASK_DATA = 0xA32C; -var MAT_OPACMAP = 0xA210; -// var MAT_SXP_OPAC_DATA = 0xA322; -// var MAT_OPACMASK = 0xA342; -// var MAT_SXP_OPACMASK_DATA = 0xA32E; -var MAT_BUMPMAP = 0xA230; -// var MAT_SXP_BUMP_DATA = 0xA324; -// var MAT_BUMPMASK = 0xA344; -// var MAT_SXP_BUMPMASK_DATA = 0xA330; -var MAT_SPECMAP = 0xA204; -// var MAT_SXP_SPEC_DATA = 0xA325; -// var MAT_SPECMASK = 0xA348; -// var MAT_SXP_SPECMASK_DATA = 0xA332; -// var MAT_SHINMAP = 0xA33C; -// var MAT_SXP_SHIN_DATA = 0xA326; -// var MAT_SHINMASK = 0xA346; -// var MAT_SXP_SHINMASK_DATA = 0xA334; -// var MAT_SELFIMAP = 0xA33D; -// var MAT_SXP_SELFI_DATA = 0xA328; -// var MAT_SELFIMASK = 0xA34A; -// var MAT_SXP_SELFIMASK_DATA = 0xA336; -// var MAT_REFLMAP = 0xA220; -// var MAT_REFLMASK = 0xA34C; -// var MAT_SXP_REFLMASK_DATA = 0xA338; -// var MAT_ACUBIC = 0xA310; -var MAT_MAPNAME = 0xA300; -// var MAT_MAP_TILING = 0xA351; -// var MAT_MAP_TEXBLUR = 0xA353; -var MAT_MAP_USCALE = 0xA354; -var MAT_MAP_VSCALE = 0xA356; -var MAT_MAP_UOFFSET = 0xA358; -var MAT_MAP_VOFFSET = 0xA35A; -// var MAT_MAP_ANG = 0xA35C; -// var MAT_MAP_COL1 = 0xA360; -// var MAT_MAP_COL2 = 0xA362; -// var MAT_MAP_RCOL = 0xA364; -// var MAT_MAP_GCOL = 0xA366; -// var MAT_MAP_BCOL = 0xA368; -var NAMED_OBJECT = 0x4000; -// var N_DIRECT_LIGHT = 0x4600; -// var DL_OFF = 0x4620; -// var DL_OUTER_RANGE = 0x465A; -// var DL_INNER_RANGE = 0x4659; -// var DL_MULTIPLIER = 0x465B; -// var DL_EXCLUDE = 0x4654; -// var DL_ATTENUATE = 0x4625; -// var DL_SPOTLIGHT = 0x4610; -// var DL_SPOT_ROLL = 0x4656; -// var DL_SHADOWED = 0x4630; -// var DL_LOCAL_SHADOW2 = 0x4641; -// var DL_SEE_CONE = 0x4650; -// var DL_SPOT_RECTANGULAR = 0x4651; -// var DL_SPOT_ASPECT = 0x4657; -// var DL_SPOT_PROJECTOR = 0x4653; -// var DL_SPOT_OVERSHOOT = 0x4652; -// var DL_RAY_BIAS = 0x4658; -// var DL_RAYSHAD = 0x4627; -// var N_CAMERA = 0x4700; -// var CAM_SEE_CONE = 0x4710; -// var CAM_RANGES = 0x4720; -// var OBJ_HIDDEN = 0x4010; -// var OBJ_VIS_LOFTER = 0x4011; -// var OBJ_DOESNT_CAST = 0x4012; -// var OBJ_DONT_RECVSHADOW = 0x4017; -// var OBJ_MATTE = 0x4013; -// var OBJ_FAST = 0x4014; -// var OBJ_PROCEDURAL = 0x4015; -// var OBJ_FROZEN = 0x4016; -var N_TRI_OBJECT = 0x4100; -var POINT_ARRAY = 0x4110; -// var POINT_FLAG_ARRAY = 0x4111; -var FACE_ARRAY = 0x4120; -var MSH_MAT_GROUP = 0x4130; -// var SMOOTH_GROUP = 0x4150; -// var MSH_BOXMAP = 0x4190; -var TEX_VERTS = 0x4140; -var MESH_MATRIX = 0x4160; -// var MESH_COLOR = 0x4165; -// var MESH_TEXTURE_INFO = 0x4170; -// var KFDATA = 0xB000; -// var KFHDR = 0xB00A; -// var KFSEG = 0xB008; -// var KFCURTIME = 0xB009; -// var AMBIENT_NODE_TAG = 0xB001; -// var OBJECT_NODE_TAG = 0xB002; -// var CAMERA_NODE_TAG = 0xB003; -// var TARGET_NODE_TAG = 0xB004; -// var LIGHT_NODE_TAG = 0xB005; -// var L_TARGET_NODE_TAG = 0xB006; -// var SPOTLIGHT_NODE_TAG = 0xB007; -// var NODE_ID = 0xB030; -// var NODE_HDR = 0xB010; -// var PIVOT = 0xB013; -// var INSTANCE_NAME = 0xB011; -// var MORPH_SMOOTH = 0xB015; -// var BOUNDBOX = 0xB014; -// var POS_TRACK_TAG = 0xB020; -// var COL_TRACK_TAG = 0xB025; -// var ROT_TRACK_TAG = 0xB021; -// var SCL_TRACK_TAG = 0xB022; -// var MORPH_TRACK_TAG = 0xB026; -// var FOV_TRACK_TAG = 0xB023; -// var ROLL_TRACK_TAG = 0xB024; -// var HOT_TRACK_TAG = 0xB027; -// var FALL_TRACK_TAG = 0xB028; -// var HIDE_TRACK_TAG = 0xB029; -// var POLY_2D = 0x5000; -// var SHAPE_OK = 0x5010; -// var SHAPE_NOT_OK = 0x5011; -// var SHAPE_HOOK = 0x5020; -// var PATH_3D = 0x6000; -// var PATH_MATRIX = 0x6005; -// var SHAPE_2D = 0x6010; -// var M_SCALE = 0x6020; -// var M_TWIST = 0x6030; -// var M_TEETER = 0x6040; -// var M_FIT = 0x6050; -// var M_BEVEL = 0x6060; -// var XZ_CURVE = 0x6070; -// var YZ_CURVE = 0x6080; -// var INTERPCT = 0x6090; -// var DEFORM_LIMIT = 0x60A0; -// var USE_CONTOUR = 0x6100; -// var USE_TWEEN = 0x6110; -// var USE_SCALE = 0x6120; -// var USE_TWIST = 0x6130; -// var USE_TEETER = 0x6140; -// var USE_FIT = 0x6150; -// var USE_BEVEL = 0x6160; -// var DEFAULT_VIEW = 0x3000; -// var VIEW_TOP = 0x3010; -// var VIEW_BOTTOM = 0x3020; -// var VIEW_LEFT = 0x3030; -// var VIEW_RIGHT = 0x3040; -// var VIEW_FRONT = 0x3050; -// var VIEW_BACK = 0x3060; -// var VIEW_USER = 0x3070; -// var VIEW_CAMERA = 0x3080; -// var VIEW_WINDOW = 0x3090; -// var VIEWPORT_LAYOUT_OLD = 0x7000; -// var VIEWPORT_DATA_OLD = 0x7010; -// var VIEWPORT_LAYOUT = 0x7001; -// var VIEWPORT_DATA = 0x7011; -// var VIEWPORT_DATA_3 = 0x7012; -// var VIEWPORT_SIZE = 0x7020; -// var NETWORK_VIEW = 0x7030; +} + +// const NULL_CHUNK = 0x0000; +const M3DMAGIC = 0x4D4D; +// const SMAGIC = 0x2D2D; +// const LMAGIC = 0x2D3D; +const MLIBMAGIC = 0x3DAA; +// const MATMAGIC = 0x3DFF; +const CMAGIC = 0xC23D; +const M3D_VERSION = 0x0002; +// const M3D_KFVERSION = 0x0005; +const COLOR_F = 0x0010; +const COLOR_24 = 0x0011; +const LIN_COLOR_24 = 0x0012; +const LIN_COLOR_F = 0x0013; +const INT_PERCENTAGE = 0x0030; +const FLOAT_PERCENTAGE = 0x0031; +const MDATA = 0x3D3D; +const MESH_VERSION = 0x3D3E; +const MASTER_SCALE = 0x0100; +// const LO_SHADOW_BIAS = 0x1400; +// const HI_SHADOW_BIAS = 0x1410; +// const SHADOW_MAP_SIZE = 0x1420; +// const SHADOW_SAMPLES = 0x1430; +// const SHADOW_RANGE = 0x1440; +// const SHADOW_FILTER = 0x1450; +// const RAY_BIAS = 0x1460; +// const O_CONSTS = 0x1500; +// const AMBIENT_LIGHT = 0x2100; +// const BIT_MAP = 0x1100; +// const SOLID_BGND = 0x1200; +// const V_GRADIENT = 0x1300; +// const USE_BIT_MAP = 0x1101; +// const USE_SOLID_BGND = 0x1201; +// const USE_V_GRADIENT = 0x1301; +// const FOG = 0x2200; +// const FOG_BGND = 0x2210; +// const LAYER_FOG = 0x2302; +// const DISTANCE_CUE = 0x2300; +// const DCUE_BGND = 0x2310; +// const USE_FOG = 0x2201; +// const USE_LAYER_FOG = 0x2303; +// const USE_DISTANCE_CUE = 0x2301; +const MAT_ENTRY = 0xAFFF; +const MAT_NAME = 0xA000; +const MAT_AMBIENT = 0xA010; +const MAT_DIFFUSE = 0xA020; +const MAT_SPECULAR = 0xA030; +const MAT_SHININESS = 0xA040; +// const MAT_SHIN2PCT = 0xA041; +const MAT_TRANSPARENCY = 0xA050; +// const MAT_XPFALL = 0xA052; +// const MAT_USE_XPFALL = 0xA240; +// const MAT_REFBLUR = 0xA053; +// const MAT_SHADING = 0xA100; +// const MAT_USE_REFBLUR = 0xA250; +// const MAT_SELF_ILLUM = 0xA084; +const MAT_TWO_SIDE = 0xA081; +// const MAT_DECAL = 0xA082; +const MAT_ADDITIVE = 0xA083; +const MAT_WIRE = 0xA085; +// const MAT_FACEMAP = 0xA088; +// const MAT_TRANSFALLOFF_IN = 0xA08A; +// const MAT_PHONGSOFT = 0xA08C; +// const MAT_WIREABS = 0xA08E; +const MAT_WIRE_SIZE = 0xA087; +const MAT_TEXMAP = 0xA200; +// const MAT_SXP_TEXT_DATA = 0xA320; +// const MAT_TEXMASK = 0xA33E; +// const MAT_SXP_TEXTMASK_DATA = 0xA32A; +// const MAT_TEX2MAP = 0xA33A; +// const MAT_SXP_TEXT2_DATA = 0xA321; +// const MAT_TEX2MASK = 0xA340; +// const MAT_SXP_TEXT2MASK_DATA = 0xA32C; +const MAT_OPACMAP = 0xA210; +// const MAT_SXP_OPAC_DATA = 0xA322; +// const MAT_OPACMASK = 0xA342; +// const MAT_SXP_OPACMASK_DATA = 0xA32E; +const MAT_BUMPMAP = 0xA230; +// const MAT_SXP_BUMP_DATA = 0xA324; +// const MAT_BUMPMASK = 0xA344; +// const MAT_SXP_BUMPMASK_DATA = 0xA330; +const MAT_SPECMAP = 0xA204; +// const MAT_SXP_SPEC_DATA = 0xA325; +// const MAT_SPECMASK = 0xA348; +// const MAT_SXP_SPECMASK_DATA = 0xA332; +// const MAT_SHINMAP = 0xA33C; +// const MAT_SXP_SHIN_DATA = 0xA326; +// const MAT_SHINMASK = 0xA346; +// const MAT_SXP_SHINMASK_DATA = 0xA334; +// const MAT_SELFIMAP = 0xA33D; +// const MAT_SXP_SELFI_DATA = 0xA328; +// const MAT_SELFIMASK = 0xA34A; +// const MAT_SXP_SELFIMASK_DATA = 0xA336; +// const MAT_REFLMAP = 0xA220; +// const MAT_REFLMASK = 0xA34C; +// const MAT_SXP_REFLMASK_DATA = 0xA338; +// const MAT_ACUBIC = 0xA310; +const MAT_MAPNAME = 0xA300; +// const MAT_MAP_TILING = 0xA351; +// const MAT_MAP_TEXBLUR = 0xA353; +const MAT_MAP_USCALE = 0xA354; +const MAT_MAP_VSCALE = 0xA356; +const MAT_MAP_UOFFSET = 0xA358; +const MAT_MAP_VOFFSET = 0xA35A; +// const MAT_MAP_ANG = 0xA35C; +// const MAT_MAP_COL1 = 0xA360; +// const MAT_MAP_COL2 = 0xA362; +// const MAT_MAP_RCOL = 0xA364; +// const MAT_MAP_GCOL = 0xA366; +// const MAT_MAP_BCOL = 0xA368; +const NAMED_OBJECT = 0x4000; +// const N_DIRECT_LIGHT = 0x4600; +// const DL_OFF = 0x4620; +// const DL_OUTER_RANGE = 0x465A; +// const DL_INNER_RANGE = 0x4659; +// const DL_MULTIPLIER = 0x465B; +// const DL_EXCLUDE = 0x4654; +// const DL_ATTENUATE = 0x4625; +// const DL_SPOTLIGHT = 0x4610; +// const DL_SPOT_ROLL = 0x4656; +// const DL_SHADOWED = 0x4630; +// const DL_LOCAL_SHADOW2 = 0x4641; +// const DL_SEE_CONE = 0x4650; +// const DL_SPOT_RECTANGULAR = 0x4651; +// const DL_SPOT_ASPECT = 0x4657; +// const DL_SPOT_PROJECTOR = 0x4653; +// const DL_SPOT_OVERSHOOT = 0x4652; +// const DL_RAY_BIAS = 0x4658; +// const DL_RAYSHAD = 0x4627; +// const N_CAMERA = 0x4700; +// const CAM_SEE_CONE = 0x4710; +// const CAM_RANGES = 0x4720; +// const OBJ_HIDDEN = 0x4010; +// const OBJ_VIS_LOFTER = 0x4011; +// const OBJ_DOESNT_CAST = 0x4012; +// const OBJ_DONT_RECVSHADOW = 0x4017; +// const OBJ_MATTE = 0x4013; +// const OBJ_FAST = 0x4014; +// const OBJ_PROCEDURAL = 0x4015; +// const OBJ_FROZEN = 0x4016; +const N_TRI_OBJECT = 0x4100; +const POINT_ARRAY = 0x4110; +// const POINT_FLAG_ARRAY = 0x4111; +const FACE_ARRAY = 0x4120; +const MSH_MAT_GROUP = 0x4130; +// const SMOOTH_GROUP = 0x4150; +// const MSH_BOXMAP = 0x4190; +const TEX_VERTS = 0x4140; +const MESH_MATRIX = 0x4160; +// const MESH_COLOR = 0x4165; +// const MESH_TEXTURE_INFO = 0x4170; +// const KFDATA = 0xB000; +// const KFHDR = 0xB00A; +// const KFSEG = 0xB008; +// const KFCURTIME = 0xB009; +// const AMBIENT_NODE_TAG = 0xB001; +// const OBJECT_NODE_TAG = 0xB002; +// const CAMERA_NODE_TAG = 0xB003; +// const TARGET_NODE_TAG = 0xB004; +// const LIGHT_NODE_TAG = 0xB005; +// const L_TARGET_NODE_TAG = 0xB006; +// const SPOTLIGHT_NODE_TAG = 0xB007; +// const NODE_ID = 0xB030; +// const NODE_HDR = 0xB010; +// const PIVOT = 0xB013; +// const INSTANCE_NAME = 0xB011; +// const MORPH_SMOOTH = 0xB015; +// const BOUNDBOX = 0xB014; +// const POS_TRACK_TAG = 0xB020; +// const COL_TRACK_TAG = 0xB025; +// const ROT_TRACK_TAG = 0xB021; +// const SCL_TRACK_TAG = 0xB022; +// const MORPH_TRACK_TAG = 0xB026; +// const FOV_TRACK_TAG = 0xB023; +// const ROLL_TRACK_TAG = 0xB024; +// const HOT_TRACK_TAG = 0xB027; +// const FALL_TRACK_TAG = 0xB028; +// const HIDE_TRACK_TAG = 0xB029; +// const POLY_2D = 0x5000; +// const SHAPE_OK = 0x5010; +// const SHAPE_NOT_OK = 0x5011; +// const SHAPE_HOOK = 0x5020; +// const PATH_3D = 0x6000; +// const PATH_MATRIX = 0x6005; +// const SHAPE_2D = 0x6010; +// const M_SCALE = 0x6020; +// const M_TWIST = 0x6030; +// const M_TEETER = 0x6040; +// const M_FIT = 0x6050; +// const M_BEVEL = 0x6060; +// const XZ_CURVE = 0x6070; +// const YZ_CURVE = 0x6080; +// const INTERPCT = 0x6090; +// const DEFORM_LIMIT = 0x60A0; +// const USE_CONTOUR = 0x6100; +// const USE_TWEEN = 0x6110; +// const USE_SCALE = 0x6120; +// const USE_TWIST = 0x6130; +// const USE_TEETER = 0x6140; +// const USE_FIT = 0x6150; +// const USE_BEVEL = 0x6160; +// const DEFAULT_VIEW = 0x3000; +// const VIEW_TOP = 0x3010; +// const VIEW_BOTTOM = 0x3020; +// const VIEW_LEFT = 0x3030; +// const VIEW_RIGHT = 0x3040; +// const VIEW_FRONT = 0x3050; +// const VIEW_BACK = 0x3060; +// const VIEW_USER = 0x3070; +// const VIEW_CAMERA = 0x3080; +// const VIEW_WINDOW = 0x3090; +// const VIEWPORT_LAYOUT_OLD = 0x7000; +// const VIEWPORT_DATA_OLD = 0x7010; +// const VIEWPORT_LAYOUT = 0x7001; +// const VIEWPORT_DATA = 0x7011; +// const VIEWPORT_DATA_3 = 0x7012; +// const VIEWPORT_SIZE = 0x7020; +// const NETWORK_VIEW = 0x7030; export { TDSLoader }; diff --git a/examples/jsm/loaders/TGALoader.js b/examples/jsm/loaders/TGALoader.js index 3b96a4223b2fc4..99066fc6fe4687 100644 --- a/examples/jsm/loaders/TGALoader.js +++ b/examples/jsm/loaders/TGALoader.js @@ -3,17 +3,15 @@ import { LinearMipmapLinearFilter } from '../../../build/three.module.js'; -var TGALoader = function ( manager ) { +class TGALoader extends DataTextureLoader { - DataTextureLoader.call( this, manager ); + constructor( manager ) { -}; + super( manager ); -TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype ), { - - constructor: TGALoader, + } - parse: function ( buffer ) { + parse( buffer ) { // reference from vthibault, https://github.com/vthibault/roBrowser/blob/master/src/Loaders/Targa.js @@ -82,13 +80,11 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype function tgaParse( use_rle, use_pal, header, offset, data ) { - var pixel_data, - pixel_size, - pixel_total, + let pixel_data, palettes; - pixel_size = header.pixel_size >> 3; - pixel_total = header.width * header.height * pixel_size; + const pixel_size = header.pixel_size >> 3; + const pixel_total = header.width * header.height * pixel_size; // read palettes @@ -104,9 +100,9 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype pixel_data = new Uint8Array( pixel_total ); - var c, count, i; - var shift = 0; - var pixels = new Uint8Array( pixel_size ); + let c, count, i; + let shift = 0; + const pixels = new Uint8Array( pixel_size ); while ( shift < pixel_total ) { @@ -172,9 +168,9 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype function tgaGetImageData8bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image, palettes ) { - var colormap = palettes; - var color, i = 0, x, y; - var width = header.width; + const colormap = palettes; + let color, i = 0, x, y; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -196,8 +192,8 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype function tgaGetImageData16bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { - var color, i = 0, x, y; - var width = header.width; + let color, i = 0, x, y; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -219,8 +215,8 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype function tgaGetImageData24bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { - var i = 0, x, y; - var width = header.width; + let i = 0, x, y; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -241,8 +237,8 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype function tgaGetImageData32bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { - var i = 0, x, y; - var width = header.width; + let i = 0, x, y; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -263,8 +259,8 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype function tgaGetImageDataGrey8bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { - var color, i = 0, x, y; - var width = header.width; + let color, i = 0, x, y; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -286,8 +282,8 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype function tgaGetImageDataGrey16bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { - var i = 0, x, y; - var width = header.width; + let i = 0, x, y; + const width = header.width; for ( y = y_start; y !== y_end; y += y_step ) { @@ -308,7 +304,7 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype function getTgaRGBA( data, width, height, image, palette ) { - var x_start, + let x_start, y_start, x_step, y_step, @@ -403,7 +399,7 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype } // Load image data according to specific method - // var func = 'tgaGetImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits'; + // let func = 'tgaGetImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits'; // func(data, y_start, y_step, y_end, x_start, x_step, x_end, width, image, palette ); return data; @@ -411,7 +407,7 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype // TGA constants - var TGA_TYPE_NO_DATA = 0, + const TGA_TYPE_NO_DATA = 0, TGA_TYPE_INDEXED = 1, TGA_TYPE_RGB = 2, TGA_TYPE_GREY = 3, @@ -428,8 +424,9 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype if ( buffer.length < 19 ) console.error( 'THREE.TGALoader: Not enough data to contain header.' ); - var content = new Uint8Array( buffer ), - offset = 0, + let offset = 0; + + const content = new Uint8Array( buffer ), header = { id_length: content[ offset ++ ], colormap_type: content[ offset ++ ], @@ -463,7 +460,7 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype // get targa information about RLE compression and palette - var use_rle = false, + let use_rle = false, use_pal = false, use_grey = false; @@ -498,8 +495,8 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype // - var imageData = new Uint8Array( header.width * header.height * 4 ); - var result = tgaParse( use_rle, use_pal, header, offset, content ); + const imageData = new Uint8Array( header.width * header.height * 4 ); + const result = tgaParse( use_rle, use_pal, header, offset, content ); getTgaRGBA( imageData, header.width, header.height, result.pixel_data, result.palettes ); return { @@ -515,6 +512,6 @@ TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype } -} ); +} export { TGALoader }; diff --git a/examples/jsm/loaders/TTFLoader.js b/examples/jsm/loaders/TTFLoader.js index c720018a334eeb..42d33ab64b8eec 100644 --- a/examples/jsm/loaders/TTFLoader.js +++ b/examples/jsm/loaders/TTFLoader.js @@ -10,24 +10,21 @@ import { opentype } from '../libs/opentype.module.min.js'; * to create THREE.Font objects. */ -var TTFLoader = function ( manager ) { +class TTFLoader extends Loader { - Loader.call( this, manager ); + constructor( manager ) { - this.reversed = false; + super( manager ); -}; + this.reversed = false; + } -TTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: TTFLoader, - - load: function ( url, onLoad, onProgress, onError ) { + load( url, onLoad, onProgress, onError ) { - var scope = this; + const scope = this; - var loader = new FileLoader( this.manager ); + const loader = new FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.setRequestHeader( this.requestHeader ); @@ -56,28 +53,28 @@ TTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { }, onProgress, onError ); - }, + } - parse: function ( arraybuffer ) { + parse( arraybuffer ) { function convert( font, reversed ) { - var round = Math.round; + const round = Math.round; - var glyphs = {}; - var scale = ( 100000 ) / ( ( font.unitsPerEm || 2048 ) * 72 ); + const glyphs = {}; + const scale = ( 100000 ) / ( ( font.unitsPerEm || 2048 ) * 72 ); - var glyphIndexMap = font.encoding.cmap.glyphIndexMap; - var unicodes = Object.keys( glyphIndexMap ); + const glyphIndexMap = font.encoding.cmap.glyphIndexMap; + const unicodes = Object.keys( glyphIndexMap ); - for ( var i = 0; i < unicodes.length; i ++ ) { + for ( let i = 0; i < unicodes.length; i ++ ) { - var unicode = unicodes[ i ]; - var glyph = font.glyphs.glyphs[ glyphIndexMap[ unicode ] ]; + const unicode = unicodes[ i ]; + const glyph = font.glyphs.glyphs[ glyphIndexMap[ unicode ] ]; if ( unicode !== undefined ) { - var token = { + const token = { ha: round( glyph.advanceWidth * scale ), x_min: round( glyph.xMin * scale ), x_max: round( glyph.xMax * scale ), @@ -147,8 +144,8 @@ TTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { function reverseCommands( commands ) { - var paths = []; - var path; + const paths = []; + let path; commands.forEach( function ( c ) { @@ -165,11 +162,11 @@ TTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } ); - var reversed = []; + const reversed = []; paths.forEach( function ( p ) { - var result = { + const result = { type: 'm', x: p[ p.length - 1 ].x, y: p[ p.length - 1 ].y @@ -177,10 +174,10 @@ TTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { reversed.push( result ); - for ( var i = p.length - 1; i > 0; i -- ) { + for ( let i = p.length - 1; i > 0; i -- ) { - var command = p[ i ]; - var result = { type: command.type }; + const command = p[ i ]; + const result = { type: command.type }; if ( command.x2 !== undefined && command.y2 !== undefined ) { @@ -219,6 +216,6 @@ TTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { } -} ); +} export { TTFLoader }; diff --git a/examples/jsm/loaders/VRMLLoader.js b/examples/jsm/loaders/VRMLLoader.js index 44ea131bfb2b98..023aed181be2ab 100644 --- a/examples/jsm/loaders/VRMLLoader.js +++ b/examples/jsm/loaders/VRMLLoader.js @@ -36,2645 +36,2638 @@ import { } from '../../../build/three.module.js'; import { chevrotain } from '../libs/chevrotain.module.min.js'; -var VRMLLoader = ( function () { - // dependency check +class VRMLLoader extends Loader { - if ( typeof chevrotain === 'undefined' ) { // eslint-disable-line no-undef + constructor( manager ) { - throw Error( 'THREE.VRMLLoader: External library chevrotain.min.js required.' ); + super( manager ); - } + // dependency check - // class definitions + if ( typeof chevrotain === 'undefined' ) { // eslint-disable-line no-undef - function VRMLLoader( manager ) { + throw Error( 'THREE.VRMLLoader: External library chevrotain.min.js required.' ); - Loader.call( this, manager ); + } } - VRMLLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + load( url, onLoad, onProgress, onError ) { - constructor: VRMLLoader, + const scope = this; - load: function ( url, onLoad, onProgress, onError ) { + const path = ( scope.path === '' ) ? LoaderUtils.extractUrlBase( url ) : scope.path; - var scope = this; + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { - var path = ( scope.path === '' ) ? LoaderUtils.extractUrlBase( url ) : scope.path; + try { - var loader = new FileLoader( scope.manager ); - loader.setPath( scope.path ); - loader.setRequestHeader( scope.requestHeader ); - loader.setWithCredentials( scope.withCredentials ); - loader.load( url, function ( text ) { + onLoad( scope.parse( text, path ) ); - try { + } catch ( e ) { - onLoad( scope.parse( text, path ) ); + if ( onError ) { - } catch ( e ) { + onError( e ); - if ( onError ) { + } else { - onError( e ); + console.error( e ); - } else { + } - console.error( e ); + scope.manager.itemError( url ); - } + } - scope.manager.itemError( url ); + }, onProgress, onError ); - } + } - }, onProgress, onError ); + parse( data, path ) { - }, + const nodeMap = {}; - parse: function ( data, path ) { + function generateVRMLTree( data ) { - var nodeMap = {}; + // create lexer, parser and visitor - function generateVRMLTree( data ) { + const tokenData = createTokens(); - // create lexer, parser and visitor + const lexer = new VRMLLexer( tokenData.tokens ); + const parser = new VRMLParser( tokenData.tokenVocabulary ); + const visitor = createVisitor( parser.getBaseCstVisitorConstructor() ); - var tokenData = createTokens(); + // lexing - var lexer = new VRMLLexer( tokenData.tokens ); - var parser = new VRMLParser( tokenData.tokenVocabulary ); - var visitor = createVisitor( parser.getBaseCstVisitorConstructor() ); + const lexingResult = lexer.lex( data ); + parser.input = lexingResult.tokens; - // lexing + // parsing - var lexingResult = lexer.lex( data ); - parser.input = lexingResult.tokens; + const cstOutput = parser.vrml(); - // parsing + if ( parser.errors.length > 0 ) { - var cstOutput = parser.vrml(); + console.error( parser.errors ); - if ( parser.errors.length > 0 ) { + throw Error( 'THREE.VRMLLoader: Parsing errors detected.' ); - console.error( parser.errors ); + } - throw Error( 'THREE.VRMLLoader: Parsing errors detected.' ); + // actions - } + const ast = visitor.visit( cstOutput ); - // actions - - var ast = visitor.visit( cstOutput ); - - return ast; - - } - - function createTokens() { - - var createToken = chevrotain.createToken; // eslint-disable-line no-undef - - // from http://gun.teipir.gr/VRML-amgem/spec/part1/concepts.html#SyntaxBasics - - var RouteIdentifier = createToken( { name: 'RouteIdentifier', pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*[\.][^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/ } ); - var Identifier = createToken( { name: 'Identifier', pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/, longer_alt: RouteIdentifier } ); - - // from http://gun.teipir.gr/VRML-amgem/spec/part1/nodesRef.html - - var nodeTypes = [ - 'Anchor', 'Billboard', 'Collision', 'Group', 'Transform', // grouping nodes - 'Inline', 'LOD', 'Switch', // special groups - 'AudioClip', 'DirectionalLight', 'PointLight', 'Script', 'Shape', 'Sound', 'SpotLight', 'WorldInfo', // common nodes - 'CylinderSensor', 'PlaneSensor', 'ProximitySensor', 'SphereSensor', 'TimeSensor', 'TouchSensor', 'VisibilitySensor', // sensors - 'Box', 'Cone', 'Cylinder', 'ElevationGrid', 'Extrusion', 'IndexedFaceSet', 'IndexedLineSet', 'PointSet', 'Sphere', // geometries - 'Color', 'Coordinate', 'Normal', 'TextureCoordinate', // geometric properties - 'Appearance', 'FontStyle', 'ImageTexture', 'Material', 'MovieTexture', 'PixelTexture', 'TextureTransform', // appearance - 'ColorInterpolator', 'CoordinateInterpolator', 'NormalInterpolator', 'OrientationInterpolator', 'PositionInterpolator', 'ScalarInterpolator', // interpolators - 'Background', 'Fog', 'NavigationInfo', 'Viewpoint', // bindable nodes - 'Text' // Text must be placed at the end of the regex so there are no matches for TextureTransform and TextureCoordinate - ]; - - // - - var Version = createToken( { - name: 'Version', - pattern: /#VRML.*/, - longer_alt: Identifier - } ); - - var NodeName = createToken( { - name: 'NodeName', - pattern: new RegExp( nodeTypes.join( '|' ) ), - longer_alt: Identifier - } ); - - var DEF = createToken( { - name: 'DEF', - pattern: /DEF/, - longer_alt: Identifier - } ); - - var USE = createToken( { - name: 'USE', - pattern: /USE/, - longer_alt: Identifier - } ); - - var ROUTE = createToken( { - name: 'ROUTE', - pattern: /ROUTE/, - longer_alt: Identifier - } ); - - var TO = createToken( { - name: 'TO', - pattern: /TO/, - longer_alt: Identifier - } ); - - // - - var StringLiteral = createToken( { name: 'StringLiteral', pattern: /"(:?[^\\"\n\r]+|\\(:?[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*"/ } ); - var HexLiteral = createToken( { name: 'HexLiteral', pattern: /0[xX][0-9a-fA-F]+/ } ); - var NumberLiteral = createToken( { name: 'NumberLiteral', pattern: /[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/ } ); - var TrueLiteral = createToken( { name: 'TrueLiteral', pattern: /TRUE/ } ); - var FalseLiteral = createToken( { name: 'FalseLiteral', pattern: /FALSE/ } ); - var NullLiteral = createToken( { name: 'NullLiteral', pattern: /NULL/ } ); - var LSquare = createToken( { name: 'LSquare', pattern: /\[/ } ); - var RSquare = createToken( { name: 'RSquare', pattern: /]/ } ); - var LCurly = createToken( { name: 'LCurly', pattern: /{/ } ); - var RCurly = createToken( { name: 'RCurly', pattern: /}/ } ); - var Comment = createToken( { - name: 'Comment', - pattern: /#.*/, - group: chevrotain.Lexer.SKIPPED // eslint-disable-line no-undef - } ); - - // commas, blanks, tabs, newlines and carriage returns are whitespace characters wherever they appear outside of string fields - - var WhiteSpace = createToken( { - name: 'WhiteSpace', - pattern: /[ ,\s]/, - group: chevrotain.Lexer.SKIPPED // eslint-disable-line no-undef - } ); - - var tokens = [ - WhiteSpace, - // keywords appear before the Identifier - NodeName, - DEF, - USE, - ROUTE, - TO, - TrueLiteral, - FalseLiteral, - NullLiteral, - // the Identifier must appear after the keywords because all keywords are valid identifiers - Version, - Identifier, - RouteIdentifier, - StringLiteral, - HexLiteral, - NumberLiteral, - LSquare, - RSquare, - LCurly, - RCurly, - Comment - ]; - - var tokenVocabulary = {}; - - for ( var i = 0, l = tokens.length; i < l; i ++ ) { - - var token = tokens[ i ]; - - tokenVocabulary[ token.name ] = token; + return ast; - } + } - return { tokens: tokens, tokenVocabulary: tokenVocabulary }; + function createTokens() { - } + const createToken = chevrotain.createToken; // eslint-disable-line no-undef + // from http://gun.teipir.gr/VRML-amgem/spec/part1/concepts.html#SyntaxBasics - function createVisitor( BaseVRMLVisitor ) { + const RouteIdentifier = createToken( { name: 'RouteIdentifier', pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*[\.][^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/ } ); + const Identifier = createToken( { name: 'Identifier', pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/, longer_alt: RouteIdentifier } ); - // the visitor is created dynmaically based on the given base class + // from http://gun.teipir.gr/VRML-amgem/spec/part1/nodesRef.html - function VRMLToASTVisitor() { + const nodeTypes = [ + 'Anchor', 'Billboard', 'Collision', 'Group', 'Transform', // grouping nodes + 'Inline', 'LOD', 'Switch', // special groups + 'AudioClip', 'DirectionalLight', 'PointLight', 'Script', 'Shape', 'Sound', 'SpotLight', 'WorldInfo', // common nodes + 'CylinderSensor', 'PlaneSensor', 'ProximitySensor', 'SphereSensor', 'TimeSensor', 'TouchSensor', 'VisibilitySensor', // sensors + 'Box', 'Cone', 'Cylinder', 'ElevationGrid', 'Extrusion', 'IndexedFaceSet', 'IndexedLineSet', 'PointSet', 'Sphere', // geometries + 'Color', 'Coordinate', 'Normal', 'TextureCoordinate', // geometric properties + 'Appearance', 'FontStyle', 'ImageTexture', 'Material', 'MovieTexture', 'PixelTexture', 'TextureTransform', // appearance + 'ColorInterpolator', 'CoordinateInterpolator', 'NormalInterpolator', 'OrientationInterpolator', 'PositionInterpolator', 'ScalarInterpolator', // interpolators + 'Background', 'Fog', 'NavigationInfo', 'Viewpoint', // bindable nodes + 'Text' // Text must be placed at the end of the regex so there are no matches for TextureTransform and TextureCoordinate + ]; - BaseVRMLVisitor.call( this ); + // - this.validateVisitor(); + const Version = createToken( { + name: 'Version', + pattern: /#VRML.*/, + longer_alt: Identifier + } ); - } + const NodeName = createToken( { + name: 'NodeName', + pattern: new RegExp( nodeTypes.join( '|' ) ), + longer_alt: Identifier + } ); - VRMLToASTVisitor.prototype = Object.assign( Object.create( BaseVRMLVisitor.prototype ), { + const DEF = createToken( { + name: 'DEF', + pattern: /DEF/, + longer_alt: Identifier + } ); - constructor: VRMLToASTVisitor, + const USE = createToken( { + name: 'USE', + pattern: /USE/, + longer_alt: Identifier + } ); - vrml: function ( ctx ) { + const ROUTE = createToken( { + name: 'ROUTE', + pattern: /ROUTE/, + longer_alt: Identifier + } ); - var data = { - version: this.visit( ctx.version ), - nodes: [], - routes: [] - }; + const TO = createToken( { + name: 'TO', + pattern: /TO/, + longer_alt: Identifier + } ); - for ( var i = 0, l = ctx.node.length; i < l; i ++ ) { + // - var node = ctx.node[ i ]; + const StringLiteral = createToken( { name: 'StringLiteral', pattern: /"(:?[^\\"\n\r]+|\\(:?[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*"/ } ); + const HexLiteral = createToken( { name: 'HexLiteral', pattern: /0[xX][0-9a-fA-F]+/ } ); + const NumberLiteral = createToken( { name: 'NumberLiteral', pattern: /[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/ } ); + const TrueLiteral = createToken( { name: 'TrueLiteral', pattern: /TRUE/ } ); + const FalseLiteral = createToken( { name: 'FalseLiteral', pattern: /FALSE/ } ); + const NullLiteral = createToken( { name: 'NullLiteral', pattern: /NULL/ } ); + const LSquare = createToken( { name: 'LSquare', pattern: /\[/ } ); + const RSquare = createToken( { name: 'RSquare', pattern: /]/ } ); + const LCurly = createToken( { name: 'LCurly', pattern: /{/ } ); + const RCurly = createToken( { name: 'RCurly', pattern: /}/ } ); + const Comment = createToken( { + name: 'Comment', + pattern: /#.*/, + group: chevrotain.Lexer.SKIPPED // eslint-disable-line no-undef + } ); - data.nodes.push( this.visit( node ) ); + // commas, blanks, tabs, newlines and carriage returns are whitespace characters wherever they appear outside of string fields - } + const WhiteSpace = createToken( { + name: 'WhiteSpace', + pattern: /[ ,\s]/, + group: chevrotain.Lexer.SKIPPED // eslint-disable-line no-undef + } ); - if ( ctx.route ) { + const tokens = [ + WhiteSpace, + // keywords appear before the Identifier + NodeName, + DEF, + USE, + ROUTE, + TO, + TrueLiteral, + FalseLiteral, + NullLiteral, + // the Identifier must appear after the keywords because all keywords are valid identifiers + Version, + Identifier, + RouteIdentifier, + StringLiteral, + HexLiteral, + NumberLiteral, + LSquare, + RSquare, + LCurly, + RCurly, + Comment + ]; + + const tokenVocabulary = {}; + + for ( let i = 0, l = tokens.length; i < l; i ++ ) { + + const token = tokens[ i ]; + + tokenVocabulary[ token.name ] = token; - for ( var i = 0, l = ctx.route.length; i < l; i ++ ) { + } - var route = ctx.route[ i ]; + return { tokens: tokens, tokenVocabulary: tokenVocabulary }; - data.routes.push( this.visit( route ) ); + } - } - } + function createVisitor( BaseVRMLVisitor ) { - return data; + // the visitor is created dynmaically based on the given base class - }, + function VRMLToASTVisitor() { - version: function ( ctx ) { + BaseVRMLVisitor.call( this ); - return ctx.Version[ 0 ].image; + this.validateVisitor(); - }, + } - node: function ( ctx ) { + VRMLToASTVisitor.prototype = Object.assign( Object.create( BaseVRMLVisitor.prototype ), { - var data = { - name: ctx.NodeName[ 0 ].image, - fields: [] - }; + constructor: VRMLToASTVisitor, - if ( ctx.field ) { + vrml: function ( ctx ) { - for ( var i = 0, l = ctx.field.length; i < l; i ++ ) { + const data = { + version: this.visit( ctx.version ), + nodes: [], + routes: [] + }; - var field = ctx.field[ i ]; + for ( let i = 0, l = ctx.node.length; i < l; i ++ ) { - data.fields.push( this.visit( field ) ); + const node = ctx.node[ i ]; - } + data.nodes.push( this.visit( node ) ); - } + } + + if ( ctx.route ) { - // DEF + for ( let i = 0, l = ctx.route.length; i < l; i ++ ) { - if ( ctx.def ) { + const route = ctx.route[ i ]; - data.DEF = this.visit( ctx.def[ 0 ] ); + data.routes.push( this.visit( route ) ); } - return data; + } - }, + return data; - field: function ( ctx ) { + }, - var data = { - name: ctx.Identifier[ 0 ].image, - type: null, - values: null - }; + version: function ( ctx ) { - var result; + return ctx.Version[ 0 ].image; - // SFValue + }, - if ( ctx.singleFieldValue ) { + node: function ( ctx ) { - result = this.visit( ctx.singleFieldValue[ 0 ] ); + const data = { + name: ctx.NodeName[ 0 ].image, + fields: [] + }; - } + if ( ctx.field ) { - // MFValue + for ( let i = 0, l = ctx.field.length; i < l; i ++ ) { - if ( ctx.multiFieldValue ) { + const field = ctx.field[ i ]; - result = this.visit( ctx.multiFieldValue[ 0 ] ); + data.fields.push( this.visit( field ) ); } - data.type = result.type; - data.values = result.values; - - return data; + } - }, + // DEF - def: function ( ctx ) { + if ( ctx.def ) { - return ( ctx.Identifier || ctx.NodeName )[ 0 ].image; + data.DEF = this.visit( ctx.def[ 0 ] ); - }, + } - use: function ( ctx ) { + return data; - return { USE: ( ctx.Identifier || ctx.NodeName )[ 0 ].image }; + }, - }, + field: function ( ctx ) { - singleFieldValue: function ( ctx ) { + const data = { + name: ctx.Identifier[ 0 ].image, + type: null, + values: null + }; - return processField( this, ctx ); + let result; - }, + // SFValue - multiFieldValue: function ( ctx ) { + if ( ctx.singleFieldValue ) { - return processField( this, ctx ); + result = this.visit( ctx.singleFieldValue[ 0 ] ); - }, + } - route: function ( ctx ) { + // MFValue - var data = { - FROM: ctx.RouteIdentifier[ 0 ].image, - TO: ctx.RouteIdentifier[ 1 ].image - }; + if ( ctx.multiFieldValue ) { - return data; + result = this.visit( ctx.multiFieldValue[ 0 ] ); } - } ); + data.type = result.type; + data.values = result.values; - function processField( scope, ctx ) { + return data; - var field = { - type: null, - values: [] - }; + }, - if ( ctx.node ) { + def: function ( ctx ) { - field.type = 'node'; + return ( ctx.Identifier || ctx.NodeName )[ 0 ].image; - for ( var i = 0, l = ctx.node.length; i < l; i ++ ) { + }, - var node = ctx.node[ i ]; + use: function ( ctx ) { - field.values.push( scope.visit( node ) ); + return { USE: ( ctx.Identifier || ctx.NodeName )[ 0 ].image }; - } + }, - } + singleFieldValue: function ( ctx ) { - if ( ctx.use ) { + return processField( this, ctx ); - field.type = 'use'; + }, - for ( var i = 0, l = ctx.use.length; i < l; i ++ ) { + multiFieldValue: function ( ctx ) { - var use = ctx.use[ i ]; + return processField( this, ctx ); - field.values.push( scope.visit( use ) ); + }, - } + route: function ( ctx ) { - } + const data = { + FROM: ctx.RouteIdentifier[ 0 ].image, + TO: ctx.RouteIdentifier[ 1 ].image + }; - if ( ctx.StringLiteral ) { + return data; - field.type = 'string'; + } - for ( var i = 0, l = ctx.StringLiteral.length; i < l; i ++ ) { + } ); + + function processField( scope, ctx ) { - var stringLiteral = ctx.StringLiteral[ i ]; + const field = { + type: null, + values: [] + }; - field.values.push( stringLiteral.image.replace( /'|"/g, '' ) ); + if ( ctx.node ) { - } + field.type = 'node'; + + for ( let i = 0, l = ctx.node.length; i < l; i ++ ) { + + const node = ctx.node[ i ]; + + field.values.push( scope.visit( node ) ); } - if ( ctx.NumberLiteral ) { + } - field.type = 'number'; + if ( ctx.use ) { - for ( var i = 0, l = ctx.NumberLiteral.length; i < l; i ++ ) { + field.type = 'use'; - var numberLiteral = ctx.NumberLiteral[ i ]; + for ( let i = 0, l = ctx.use.length; i < l; i ++ ) { - field.values.push( parseFloat( numberLiteral.image ) ); + const use = ctx.use[ i ]; - } + field.values.push( scope.visit( use ) ); } - if ( ctx.HexLiteral ) { + } - field.type = 'hex'; + if ( ctx.StringLiteral ) { - for ( var i = 0, l = ctx.HexLiteral.length; i < l; i ++ ) { + field.type = 'string'; - var hexLiteral = ctx.HexLiteral[ i ]; + for ( let i = 0, l = ctx.StringLiteral.length; i < l; i ++ ) { - field.values.push( hexLiteral.image ); + const stringLiteral = ctx.StringLiteral[ i ]; - } + field.values.push( stringLiteral.image.replace( /'|"/g, '' ) ); } - if ( ctx.TrueLiteral ) { + } - field.type = 'boolean'; + if ( ctx.NumberLiteral ) { - for ( var i = 0, l = ctx.TrueLiteral.length; i < l; i ++ ) { + field.type = 'number'; - var trueLiteral = ctx.TrueLiteral[ i ]; + for ( let i = 0, l = ctx.NumberLiteral.length; i < l; i ++ ) { - if ( trueLiteral.image === 'TRUE' ) field.values.push( true ); + const numberLiteral = ctx.NumberLiteral[ i ]; - } + field.values.push( parseFloat( numberLiteral.image ) ); } - if ( ctx.FalseLiteral ) { + } - field.type = 'boolean'; + if ( ctx.HexLiteral ) { - for ( var i = 0, l = ctx.FalseLiteral.length; i < l; i ++ ) { + field.type = 'hex'; - var falseLiteral = ctx.FalseLiteral[ i ]; + for ( let i = 0, l = ctx.HexLiteral.length; i < l; i ++ ) { - if ( falseLiteral.image === 'FALSE' ) field.values.push( false ); + const hexLiteral = ctx.HexLiteral[ i ]; - } + field.values.push( hexLiteral.image ); } - if ( ctx.NullLiteral ) { + } - field.type = 'null'; + if ( ctx.TrueLiteral ) { - ctx.NullLiteral.forEach( function () { + field.type = 'boolean'; - field.values.push( null ); + for ( let i = 0, l = ctx.TrueLiteral.length; i < l; i ++ ) { - } ); + const trueLiteral = ctx.TrueLiteral[ i ]; - } + if ( trueLiteral.image === 'TRUE' ) field.values.push( true ); - return field; + } } - return new VRMLToASTVisitor(); + if ( ctx.FalseLiteral ) { - } + field.type = 'boolean'; + + for ( let i = 0, l = ctx.FalseLiteral.length; i < l; i ++ ) { + + const falseLiteral = ctx.FalseLiteral[ i ]; + + if ( falseLiteral.image === 'FALSE' ) field.values.push( false ); - function parseTree( tree ) { + } - // console.log( JSON.stringify( tree, null, 2 ) ); + } - var nodes = tree.nodes; - var scene = new Scene(); + if ( ctx.NullLiteral ) { - // first iteration: build nodemap based on DEF statements + field.type = 'null'; - for ( var i = 0, l = nodes.length; i < l; i ++ ) { + ctx.NullLiteral.forEach( function () { - var node = nodes[ i ]; + field.values.push( null ); - buildNodeMap( node ); + } ); } - // second iteration: build nodes + return field; - for ( var i = 0, l = nodes.length; i < l; i ++ ) { + } - var node = nodes[ i ]; - var object = getNode( node ); + return new VRMLToASTVisitor(); - if ( object instanceof Object3D ) scene.add( object ); + } - if ( node.name === 'WorldInfo' ) scene.userData.worldInfo = object; + function parseTree( tree ) { - } + // console.log( JSON.stringify( tree, null, 2 ) ); - return scene; + const nodes = tree.nodes; + const scene = new Scene(); - } + // first iteration: build nodemap based on DEF statements - function buildNodeMap( node ) { + for ( let i = 0, l = nodes.length; i < l; i ++ ) { - if ( node.DEF ) { + const node = nodes[ i ]; - nodeMap[ node.DEF ] = node; + buildNodeMap( node ); - } + } - var fields = node.fields; + // second iteration: build nodes - for ( var i = 0, l = fields.length; i < l; i ++ ) { + for ( let i = 0, l = nodes.length; i < l; i ++ ) { - var field = fields[ i ]; + const node = nodes[ i ]; + const object = getNode( node ); - if ( field.type === 'node' ) { + if ( object instanceof Object3D ) scene.add( object ); - var fieldValues = field.values; + if ( node.name === 'WorldInfo' ) scene.userData.worldInfo = object; - for ( var j = 0, jl = fieldValues.length; j < jl; j ++ ) { + } - buildNodeMap( fieldValues[ j ] ); + return scene; - } + } - } + function buildNodeMap( node ) { + if ( node.DEF ) { - } + nodeMap[ node.DEF ] = node; } + const fields = node.fields; - function getNode( node ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - // handle case where a node refers to a different one + const field = fields[ i ]; - if ( node.USE ) { + if ( field.type === 'node' ) { - return resolveUSE( node.USE ); + const fieldValues = field.values; - } + for ( let j = 0, jl = fieldValues.length; j < jl; j ++ ) { - if ( node.build !== undefined ) return node.build; + buildNodeMap( fieldValues[ j ] ); - node.build = buildNode( node ); + } + + } - return node.build; } - // node builder + } - function buildNode( node ) { - var nodeName = node.name; - var build; + function getNode( node ) { - switch ( nodeName ) { + // handle case where a node refers to a different one - case 'Group': - case 'Transform': - case 'Collision': - build = buildGroupingNode( node ); - break; + if ( node.USE ) { - case 'Background': - build = buildBackgroundNode( node ); - break; + return resolveUSE( node.USE ); - case 'Shape': - build = buildShapeNode( node ); - break; + } - case 'Appearance': - build = buildAppearanceNode( node ); - break; + if ( node.build !== undefined ) return node.build; - case 'Material': - build = buildMaterialNode( node ); - break; + node.build = buildNode( node ); - case 'ImageTexture': - build = buildImageTextureNode( node ); - break; + return node.build; - case 'PixelTexture': - build = buildPixelTextureNode( node ); - break; + } - case 'TextureTransform': - build = buildTextureTransformNode( node ); - break; + // node builder - case 'IndexedFaceSet': - build = buildIndexedFaceSetNode( node ); - break; + function buildNode( node ) { - case 'IndexedLineSet': - build = buildIndexedLineSetNode( node ); - break; + const nodeName = node.name; + let build; - case 'PointSet': - build = buildPointSetNode( node ); - break; + switch ( nodeName ) { - case 'Box': - build = buildBoxNode( node ); - break; + case 'Group': + case 'Transform': + case 'Collision': + build = buildGroupingNode( node ); + break; - case 'Cone': - build = buildConeNode( node ); - break; + case 'Background': + build = buildBackgroundNode( node ); + break; - case 'Cylinder': - build = buildCylinderNode( node ); - break; + case 'Shape': + build = buildShapeNode( node ); + break; + + case 'Appearance': + build = buildAppearanceNode( node ); + break; + + case 'Material': + build = buildMaterialNode( node ); + break; + + case 'ImageTexture': + build = buildImageTextureNode( node ); + break; - case 'Sphere': - build = buildSphereNode( node ); - break; + case 'PixelTexture': + build = buildPixelTextureNode( node ); + break; - case 'ElevationGrid': - build = buildElevationGridNode( node ); - break; + case 'TextureTransform': + build = buildTextureTransformNode( node ); + break; - case 'Extrusion': - build = buildExtrusionNode( node ); - break; + case 'IndexedFaceSet': + build = buildIndexedFaceSetNode( node ); + break; - case 'Color': - case 'Coordinate': - case 'Normal': - case 'TextureCoordinate': - build = buildGeometricNode( node ); - break; + case 'IndexedLineSet': + build = buildIndexedLineSetNode( node ); + break; - case 'WorldInfo': - build = buildWorldInfoNode( node ); - break; + case 'PointSet': + build = buildPointSetNode( node ); + break; - case 'Anchor': - case 'Billboard': + case 'Box': + build = buildBoxNode( node ); + break; - case 'Inline': - case 'LOD': - case 'Switch': + case 'Cone': + build = buildConeNode( node ); + break; - case 'AudioClip': - case 'DirectionalLight': - case 'PointLight': - case 'Script': - case 'Sound': - case 'SpotLight': + case 'Cylinder': + build = buildCylinderNode( node ); + break; - case 'CylinderSensor': - case 'PlaneSensor': - case 'ProximitySensor': - case 'SphereSensor': - case 'TimeSensor': - case 'TouchSensor': - case 'VisibilitySensor': + case 'Sphere': + build = buildSphereNode( node ); + break; - case 'Text': + case 'ElevationGrid': + build = buildElevationGridNode( node ); + break; - case 'FontStyle': - case 'MovieTexture': + case 'Extrusion': + build = buildExtrusionNode( node ); + break; - case 'ColorInterpolator': - case 'CoordinateInterpolator': - case 'NormalInterpolator': - case 'OrientationInterpolator': - case 'PositionInterpolator': - case 'ScalarInterpolator': + case 'Color': + case 'Coordinate': + case 'Normal': + case 'TextureCoordinate': + build = buildGeometricNode( node ); + break; - case 'Fog': - case 'NavigationInfo': - case 'Viewpoint': - // node not supported yet - break; + case 'WorldInfo': + build = buildWorldInfoNode( node ); + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown node:', nodeName ); - break; + case 'Anchor': + case 'Billboard': - } + case 'Inline': + case 'LOD': + case 'Switch': - if ( build !== undefined && node.DEF !== undefined && build.hasOwnProperty( 'name' ) === true ) { + case 'AudioClip': + case 'DirectionalLight': + case 'PointLight': + case 'Script': + case 'Sound': + case 'SpotLight': + + case 'CylinderSensor': + case 'PlaneSensor': + case 'ProximitySensor': + case 'SphereSensor': + case 'TimeSensor': + case 'TouchSensor': + case 'VisibilitySensor': + + case 'Text': + + case 'FontStyle': + case 'MovieTexture': + + case 'ColorInterpolator': + case 'CoordinateInterpolator': + case 'NormalInterpolator': + case 'OrientationInterpolator': + case 'PositionInterpolator': + case 'ScalarInterpolator': + + case 'Fog': + case 'NavigationInfo': + case 'Viewpoint': + // node not supported yet + break; + + default: + console.warn( 'THREE.VRMLLoader: Unknown node:', nodeName ); + break; - build.name = node.DEF; + } - } + if ( build !== undefined && node.DEF !== undefined && build.hasOwnProperty( 'name' ) === true ) { - return build; + build.name = node.DEF; } - function buildGroupingNode( node ) { + return build; - var object = new Group(); + } - // + function buildGroupingNode( node ) { - var fields = node.fields; + const object = new Group(); - for ( var i = 0, l = fields.length; i < l; i ++ ) { + // - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'bboxCenter': - // field not supported - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'bboxSize': - // field not supported - break; + switch ( fieldName ) { - case 'center': - // field not supported - break; + case 'bboxCenter': + // field not supported + break; - case 'children': - parseFieldChildren( fieldValues, object ); - break; + case 'bboxSize': + // field not supported + break; - case 'collide': - // field not supported - break; + case 'center': + // field not supported + break; - case 'rotation': - var axis = new Vector3( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - var angle = fieldValues[ 3 ]; - object.quaternion.setFromAxisAngle( axis, angle ); - break; + case 'children': + parseFieldChildren( fieldValues, object ); + break; - case 'scale': - object.scale.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - break; + case 'collide': + // field not supported + break; - case 'scaleOrientation': - // field not supported - break; + case 'rotation': + const axis = new Vector3( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); + const angle = fieldValues[ 3 ]; + object.quaternion.setFromAxisAngle( axis, angle ); + break; - case 'translation': - object.position.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - break; + case 'scale': + object.scale.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); + break; - case 'proxy': - // field not supported - break; + case 'scaleOrientation': + // field not supported + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'translation': + object.position.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); + break; - } + case 'proxy': + // field not supported + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - return object; + } } - function buildBackgroundNode( node ) { + return object; - var group = new Group(); + } - var groundAngle, groundColor; - var skyAngle, skyColor; + function buildBackgroundNode( node ) { - var fields = node.fields; + const group = new Group(); - for ( var i = 0, l = fields.length; i < l; i ++ ) { + let groundAngle, groundColor; + let skyAngle, skyColor; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'groundAngle': - groundAngle = fieldValues; - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'groundColor': - groundColor = fieldValues; - break; + switch ( fieldName ) { - case 'backUrl': - // field not supported - break; + case 'groundAngle': + groundAngle = fieldValues; + break; - case 'bottomUrl': - // field not supported - break; + case 'groundColor': + groundColor = fieldValues; + break; - case 'frontUrl': - // field not supported - break; + case 'backUrl': + // field not supported + break; - case 'leftUrl': - // field not supported - break; + case 'bottomUrl': + // field not supported + break; - case 'rightUrl': - // field not supported - break; + case 'frontUrl': + // field not supported + break; - case 'topUrl': - // field not supported - break; + case 'leftUrl': + // field not supported + break; - case 'skyAngle': - skyAngle = fieldValues; - break; + case 'rightUrl': + // field not supported + break; - case 'skyColor': - skyColor = fieldValues; - break; + case 'topUrl': + // field not supported + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'skyAngle': + skyAngle = fieldValues; + break; - } + case 'skyColor': + skyColor = fieldValues; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - var radius = 10000; + } - // sky + } - if ( skyColor ) { + const radius = 10000; - var skyGeometry = new SphereGeometry( radius, 32, 16 ); - var skyMaterial = new MeshBasicMaterial( { fog: false, side: BackSide, depthWrite: false, depthTest: false } ); + // sky - if ( skyColor.length > 3 ) { + if ( skyColor ) { - paintFaces( skyGeometry, radius, skyAngle, toColorArray( skyColor ), true ); - skyMaterial.vertexColors = true; + const skyGeometry = new SphereGeometry( radius, 32, 16 ); + const skyMaterial = new MeshBasicMaterial( { fog: false, side: BackSide, depthWrite: false, depthTest: false } ); - } else { + if ( skyColor.length > 3 ) { - skyMaterial.color.setRGB( skyColor[ 0 ], skyColor[ 1 ], skyColor[ 2 ] ); + paintFaces( skyGeometry, radius, skyAngle, toColorArray( skyColor ), true ); + skyMaterial.vertexColors = true; - } + } else { - var sky = new Mesh( skyGeometry, skyMaterial ); - group.add( sky ); + skyMaterial.color.setRGB( skyColor[ 0 ], skyColor[ 1 ], skyColor[ 2 ] ); } - // ground + const sky = new Mesh( skyGeometry, skyMaterial ); + group.add( sky ); - if ( groundColor ) { + } - if ( groundColor.length > 0 ) { + // ground - var groundGeometry = new SphereGeometry( radius, 32, 16, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI ); - var groundMaterial = new MeshBasicMaterial( { fog: false, side: BackSide, vertexColors: true, depthWrite: false, depthTest: false } ); + if ( groundColor ) { - paintFaces( groundGeometry, radius, groundAngle, toColorArray( groundColor ), false ); + if ( groundColor.length > 0 ) { - var ground = new Mesh( groundGeometry, groundMaterial ); - group.add( ground ); + const groundGeometry = new SphereGeometry( radius, 32, 16, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI ); + const groundMaterial = new MeshBasicMaterial( { fog: false, side: BackSide, vertexColors: true, depthWrite: false, depthTest: false } ); - } + paintFaces( groundGeometry, radius, groundAngle, toColorArray( groundColor ), false ); + + const ground = new Mesh( groundGeometry, groundMaterial ); + group.add( ground ); } - // render background group first + } - group.renderOrder = - Infinity; + // render background group first - return group; + group.renderOrder = - Infinity; - } + return group; - function buildShapeNode( node ) { + } - var fields = node.fields; + function buildShapeNode( node ) { - // if the appearance field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0) + const fields = node.fields; - var material = new MeshBasicMaterial( { color: 0x000000 } ); - var geometry; + // if the appearance field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0) - for ( var i = 0, l = fields.length; i < l; i ++ ) { + let material = new MeshBasicMaterial( { color: 0x000000 } ); + let geometry; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'appearance': - if ( fieldValues[ 0 ] !== null ) { + switch ( fieldName ) { - material = getNode( fieldValues[ 0 ] ); + case 'appearance': + if ( fieldValues[ 0 ] !== null ) { - } + material = getNode( fieldValues[ 0 ] ); - break; + } - case 'geometry': - if ( fieldValues[ 0 ] !== null ) { + break; - geometry = getNode( fieldValues[ 0 ] ); + case 'geometry': + if ( fieldValues[ 0 ] !== null ) { - } + geometry = getNode( fieldValues[ 0 ] ); - break; + } - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - // build 3D object + } - var object; + // build 3D object - if ( geometry && geometry.attributes.position ) { + let object; - var type = geometry._type; + if ( geometry && geometry.attributes.position ) { - if ( type === 'points' ) { // points + const type = geometry._type; - var pointsMaterial = new PointsMaterial( { color: 0xffffff } ); + if ( type === 'points' ) { // points - if ( geometry.attributes.color !== undefined ) { + const pointsMaterial = new PointsMaterial( { color: 0xffffff } ); - pointsMaterial.vertexColors = true; + if ( geometry.attributes.color !== undefined ) { - } else { + pointsMaterial.vertexColors = true; - // if the color field is NULL and there is a material defined for the appearance affecting this PointSet, then use the emissiveColor of the material to draw the points + } else { - if ( material.isMeshPhongMaterial ) { + // if the color field is NULL and there is a material defined for the appearance affecting this PointSet, then use the emissiveColor of the material to draw the points - pointsMaterial.color.copy( material.emissive ); + if ( material.isMeshPhongMaterial ) { - } + pointsMaterial.color.copy( material.emissive ); } - object = new Points( geometry, pointsMaterial ); + } - } else if ( type === 'line' ) { // lines + object = new Points( geometry, pointsMaterial ); - var lineMaterial = new LineBasicMaterial( { color: 0xffffff } ); + } else if ( type === 'line' ) { // lines - if ( geometry.attributes.color !== undefined ) { + const lineMaterial = new LineBasicMaterial( { color: 0xffffff } ); - lineMaterial.vertexColors = true; + if ( geometry.attributes.color !== undefined ) { - } else { + lineMaterial.vertexColors = true; - // if the color field is NULL and there is a material defined for the appearance affecting this IndexedLineSet, then use the emissiveColor of the material to draw the lines + } else { - if ( material.isMeshPhongMaterial ) { + // if the color field is NULL and there is a material defined for the appearance affecting this IndexedLineSet, then use the emissiveColor of the material to draw the lines - lineMaterial.color.copy( material.emissive ); + if ( material.isMeshPhongMaterial ) { - } + lineMaterial.color.copy( material.emissive ); } - object = new LineSegments( geometry, lineMaterial ); - - } else { // consider meshes + } - // check "solid" hint (it's placed in the geometry but affects the material) + object = new LineSegments( geometry, lineMaterial ); - if ( geometry._solid !== undefined ) { + } else { // consider meshes - material.side = ( geometry._solid ) ? FrontSide : DoubleSide; + // check "solid" hint (it's placed in the geometry but affects the material) - } + if ( geometry._solid !== undefined ) { - // check for vertex colors + material.side = ( geometry._solid ) ? FrontSide : DoubleSide; - if ( geometry.attributes.color !== undefined ) { + } - material.vertexColors = true; + // check for vertex colors - } + if ( geometry.attributes.color !== undefined ) { - object = new Mesh( geometry, material ); + material.vertexColors = true; } - } else { + object = new Mesh( geometry, material ); - object = new Object3D(); + } - // if the geometry field is NULL or no vertices are defined the object is not drawn + } else { - object.visible = false; + object = new Object3D(); - } + // if the geometry field is NULL or no vertices are defined the object is not drawn - return object; + object.visible = false; } - function buildAppearanceNode( node ) { + return object; - var material = new MeshPhongMaterial(); - var transformData; + } - var fields = node.fields; + function buildAppearanceNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + let material = new MeshPhongMaterial(); + let transformData; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'material': - if ( fieldValues[ 0 ] !== null ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - var materialData = getNode( fieldValues[ 0 ] ); + switch ( fieldName ) { - if ( materialData.diffuseColor ) material.color.copy( materialData.diffuseColor ); - if ( materialData.emissiveColor ) material.emissive.copy( materialData.emissiveColor ); - if ( materialData.shininess ) material.shininess = materialData.shininess; - if ( materialData.specularColor ) material.specular.copy( materialData.specularColor ); - if ( materialData.transparency ) material.opacity = 1 - materialData.transparency; - if ( materialData.transparency > 0 ) material.transparent = true; + case 'material': + if ( fieldValues[ 0 ] !== null ) { - } else { + const materialData = getNode( fieldValues[ 0 ] ); - // if the material field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0) + if ( materialData.diffuseColor ) material.color.copy( materialData.diffuseColor ); + if ( materialData.emissiveColor ) material.emissive.copy( materialData.emissiveColor ); + if ( materialData.shininess ) material.shininess = materialData.shininess; + if ( materialData.specularColor ) material.specular.copy( materialData.specularColor ); + if ( materialData.transparency ) material.opacity = 1 - materialData.transparency; + if ( materialData.transparency > 0 ) material.transparent = true; - material = new MeshBasicMaterial( { color: 0x000000 } ); + } else { - } + // if the material field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0) - break; + material = new MeshBasicMaterial( { color: 0x000000 } ); - case 'texture': - var textureNode = fieldValues[ 0 ]; - if ( textureNode !== null ) { + } + + break; - if ( textureNode.name === 'ImageTexture' || textureNode.name === 'PixelTexture' ) { + case 'texture': + const textureNode = fieldValues[ 0 ]; + if ( textureNode !== null ) { - material.map = getNode( textureNode ); + if ( textureNode.name === 'ImageTexture' || textureNode.name === 'PixelTexture' ) { - } else { + material.map = getNode( textureNode ); - // MovieTexture not supported yet + } else { - } + // MovieTexture not supported yet } - break; + } - case 'textureTransform': - if ( fieldValues[ 0 ] !== null ) { + break; - transformData = getNode( fieldValues[ 0 ] ); + case 'textureTransform': + if ( fieldValues[ 0 ] !== null ) { - } + transformData = getNode( fieldValues[ 0 ] ); - break; + } - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - // only apply texture transform data if a texture was defined - - if ( material.map ) { + } - // respect VRML lighting model + // only apply texture transform data if a texture was defined - if ( material.map.__type ) { + if ( material.map ) { - switch ( material.map.__type ) { + // respect VRML lighting model - case TEXTURE_TYPE.INTENSITY_ALPHA: - material.opacity = 1; // ignore transparency - break; + if ( material.map.__type ) { - case TEXTURE_TYPE.RGB: - material.color.set( 0xffffff ); // ignore material color - break; + switch ( material.map.__type ) { - case TEXTURE_TYPE.RGBA: - material.color.set( 0xffffff ); // ignore material color - material.opacity = 1; // ignore transparency - break; + case TEXTURE_TYPE.INTENSITY_ALPHA: + material.opacity = 1; // ignore transparency + break; - default: + case TEXTURE_TYPE.RGB: + material.color.set( 0xffffff ); // ignore material color + break; - } + case TEXTURE_TYPE.RGBA: + material.color.set( 0xffffff ); // ignore material color + material.opacity = 1; // ignore transparency + break; - delete material.map.__type; + default: } - // apply texture transform - - if ( transformData ) { - - material.map.center.copy( transformData.center ); - material.map.rotation = transformData.rotation; - material.map.repeat.copy( transformData.scale ); - material.map.offset.copy( transformData.translation ); - - } + delete material.map.__type; } - return material; - - } - - function buildMaterialNode( node ) { - - var materialData = {}; - - var fields = node.fields; - - for ( var i = 0, l = fields.length; i < l; i ++ ) { + // apply texture transform - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + if ( transformData ) { - switch ( fieldName ) { + material.map.center.copy( transformData.center ); + material.map.rotation = transformData.rotation; + material.map.repeat.copy( transformData.scale ); + material.map.offset.copy( transformData.translation ); - case 'ambientIntensity': - // field not supported - break; - - case 'diffuseColor': - materialData.diffuseColor = new Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - break; + } - case 'emissiveColor': - materialData.emissiveColor = new Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - break; + } - case 'shininess': - materialData.shininess = fieldValues[ 0 ]; - break; + return material; - case 'specularColor': - materialData.emissiveColor = new Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); - break; + } - case 'transparency': - materialData.transparency = fieldValues[ 0 ]; - break; + function buildMaterialNode( node ) { - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + const materialData = {}; - } + const fields = node.fields; - } + for ( let i = 0, l = fields.length; i < l; i ++ ) { - return materialData; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - } + switch ( fieldName ) { - function parseHexColor( hex, textureType, color ) { + case 'ambientIntensity': + // field not supported + break; - switch ( textureType ) { + case 'diffuseColor': + materialData.diffuseColor = new Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); + break; - case TEXTURE_TYPE.INTENSITY: - // Intensity texture: A one-component image specifies one-byte hexadecimal or integer values representing the intensity of the image - var value = parseInt( hex ); - color.r = value; - color.g = value; - color.b = value; + case 'emissiveColor': + materialData.emissiveColor = new Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; - case TEXTURE_TYPE.INTENSITY_ALPHA: - // Intensity+Alpha texture: A two-component image specifies the intensity in the first (high) byte and the alpha opacity in the second (low) byte. - var value = parseInt( '0x' + hex.substring( 2, 4 ) ); - color.r = value; - color.g = value; - color.b = value; - color.a = parseInt( '0x' + hex.substring( 4, 6 ) ); + case 'shininess': + materialData.shininess = fieldValues[ 0 ]; break; - case TEXTURE_TYPE.RGB: - // RGB texture: Pixels in a three-component image specify the red component in the first (high) byte, followed by the green and blue components - color.r = parseInt( '0x' + hex.substring( 2, 4 ) ); - color.g = parseInt( '0x' + hex.substring( 4, 6 ) ); - color.b = parseInt( '0x' + hex.substring( 6, 8 ) ); + case 'specularColor': + materialData.emissiveColor = new Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; - case TEXTURE_TYPE.RGBA: - // RGBA texture: Four-component images specify the alpha opacity byte after red/green/blue - color.r = parseInt( '0x' + hex.substring( 2, 4 ) ); - color.g = parseInt( '0x' + hex.substring( 4, 6 ) ); - color.b = parseInt( '0x' + hex.substring( 6, 8 ) ); - color.a = parseInt( '0x' + hex.substring( 8, 10 ) ); + case 'transparency': + materialData.transparency = fieldValues[ 0 ]; break; default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } } - function getTextureType( num_components ) { + return materialData; - var type; + } - switch ( num_components ) { + function parseHexColor( hex, textureType, color ) { + + let value; + + switch ( textureType ) { + + case TEXTURE_TYPE.INTENSITY: + // Intensity texture: A one-component image specifies one-byte hexadecimal or integer values representing the intensity of the image + value = parseInt( hex ); + color.r = value; + color.g = value; + color.b = value; + break; + + case TEXTURE_TYPE.INTENSITY_ALPHA: + // Intensity+Alpha texture: A two-component image specifies the intensity in the first (high) byte and the alpha opacity in the second (low) byte. + value = parseInt( '0x' + hex.substring( 2, 4 ) ); + color.r = value; + color.g = value; + color.b = value; + color.a = parseInt( '0x' + hex.substring( 4, 6 ) ); + break; + + case TEXTURE_TYPE.RGB: + // RGB texture: Pixels in a three-component image specify the red component in the first (high) byte, followed by the green and blue components + color.r = parseInt( '0x' + hex.substring( 2, 4 ) ); + color.g = parseInt( '0x' + hex.substring( 4, 6 ) ); + color.b = parseInt( '0x' + hex.substring( 6, 8 ) ); + break; + + case TEXTURE_TYPE.RGBA: + // RGBA texture: Four-component images specify the alpha opacity byte after red/green/blue + color.r = parseInt( '0x' + hex.substring( 2, 4 ) ); + color.g = parseInt( '0x' + hex.substring( 4, 6 ) ); + color.b = parseInt( '0x' + hex.substring( 6, 8 ) ); + color.a = parseInt( '0x' + hex.substring( 8, 10 ) ); + break; + + default: - case 1: - type = TEXTURE_TYPE.INTENSITY; - break; + } - case 2: - type = TEXTURE_TYPE.INTENSITY_ALPHA; - break; + } - case 3: - type = TEXTURE_TYPE.RGB; - break; + function getTextureType( num_components ) { - case 4: - type = TEXTURE_TYPE.RGBA; - break; + let type; - default: + switch ( num_components ) { - } + case 1: + type = TEXTURE_TYPE.INTENSITY; + break; + + case 2: + type = TEXTURE_TYPE.INTENSITY_ALPHA; + break; + + case 3: + type = TEXTURE_TYPE.RGB; + break; + + case 4: + type = TEXTURE_TYPE.RGBA; + break; - return type; + default: } - function buildPixelTextureNode( node ) { + return type; - var texture; - var wrapS = RepeatWrapping; - var wrapT = RepeatWrapping; + } + + function buildPixelTextureNode( node ) { - var fields = node.fields; + let texture; + let wrapS = RepeatWrapping; + let wrapT = RepeatWrapping; - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'image': - var width = fieldValues[ 0 ]; - var height = fieldValues[ 1 ]; - var num_components = fieldValues[ 2 ]; + switch ( fieldName ) { - var useAlpha = ( num_components === 2 || num_components === 4 ); - var textureType = getTextureType( num_components ); + case 'image': + const width = fieldValues[ 0 ]; + const height = fieldValues[ 1 ]; + const num_components = fieldValues[ 2 ]; - var size = ( ( useAlpha === true ) ? 4 : 3 ) * ( width * height ); - var data = new Uint8Array( size ); + const useAlpha = ( num_components === 2 || num_components === 4 ); + const textureType = getTextureType( num_components ); - var color = { r: 0, g: 0, b: 0, a: 0 }; + const size = ( ( useAlpha === true ) ? 4 : 3 ) * ( width * height ); + const data = new Uint8Array( size ); - for ( var j = 3, k = 0, jl = fieldValues.length; j < jl; j ++, k ++ ) { + const color = { r: 0, g: 0, b: 0, a: 0 }; - parseHexColor( fieldValues[ j ], textureType, color ); + for ( let j = 3, k = 0, jl = fieldValues.length; j < jl; j ++, k ++ ) { - if ( useAlpha === true ) { + parseHexColor( fieldValues[ j ], textureType, color ); - var stride = k * 4; + if ( useAlpha === true ) { - data[ stride + 0 ] = color.r; - data[ stride + 1 ] = color.g; - data[ stride + 2 ] = color.b; - data[ stride + 3 ] = color.a; + const stride = k * 4; - } else { + data[ stride + 0 ] = color.r; + data[ stride + 1 ] = color.g; + data[ stride + 2 ] = color.b; + data[ stride + 3 ] = color.a; - var stride = k * 3; + } else { - data[ stride + 0 ] = color.r; - data[ stride + 1 ] = color.g; - data[ stride + 2 ] = color.b; + const stride = k * 3; - } + data[ stride + 0 ] = color.r; + data[ stride + 1 ] = color.g; + data[ stride + 2 ] = color.b; } - texture = new DataTexture( data, width, height, ( useAlpha === true ) ? RGBAFormat : RGBFormat ); - texture.__type = textureType; // needed for material modifications - break; + } - case 'repeatS': - if ( fieldValues[ 0 ] === false ) wrapS = ClampToEdgeWrapping; - break; + texture = new DataTexture( data, width, height, ( useAlpha === true ) ? RGBAFormat : RGBFormat ); + texture.__type = textureType; // needed for material modifications + break; - case 'repeatT': - if ( fieldValues[ 0 ] === false ) wrapT = ClampToEdgeWrapping; - break; + case 'repeatS': + if ( fieldValues[ 0 ] === false ) wrapS = ClampToEdgeWrapping; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'repeatT': + if ( fieldValues[ 0 ] === false ) wrapT = ClampToEdgeWrapping; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - if ( texture ) { - - texture.wrapS = wrapS; - texture.wrapT = wrapT; + } - } + if ( texture ) { - return texture; + texture.wrapS = wrapS; + texture.wrapT = wrapT; } - function buildImageTextureNode( node ) { + return texture; - var texture; - var wrapS = RepeatWrapping; - var wrapT = RepeatWrapping; + } - var fields = node.fields; + function buildImageTextureNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + let texture; + let wrapS = RepeatWrapping; + let wrapT = RepeatWrapping; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'url': - var url = fieldValues[ 0 ]; - if ( url ) texture = textureLoader.load( url ); - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'repeatS': - if ( fieldValues[ 0 ] === false ) wrapS = ClampToEdgeWrapping; - break; + switch ( fieldName ) { - case 'repeatT': - if ( fieldValues[ 0 ] === false ) wrapT = ClampToEdgeWrapping; - break; + case 'url': + const url = fieldValues[ 0 ]; + if ( url ) texture = textureLoader.load( url ); + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'repeatS': + if ( fieldValues[ 0 ] === false ) wrapS = ClampToEdgeWrapping; + break; - } + case 'repeatT': + if ( fieldValues[ 0 ] === false ) wrapT = ClampToEdgeWrapping; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - if ( texture ) { + } - texture.wrapS = wrapS; - texture.wrapT = wrapT; + } - } + if ( texture ) { - return texture; + texture.wrapS = wrapS; + texture.wrapT = wrapT; } - function buildTextureTransformNode( node ) { + return texture; - var transformData = { - center: new Vector2(), - rotation: new Vector2(), - scale: new Vector2(), - translation: new Vector2() - }; + } - var fields = node.fields; + function buildTextureTransformNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const transformData = { + center: new Vector2(), + rotation: new Vector2(), + scale: new Vector2(), + translation: new Vector2() + }; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'center': - transformData.center.set( fieldValues[ 0 ], fieldValues[ 1 ] ); - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'rotation': - transformData.rotation = fieldValues[ 0 ]; - break; + switch ( fieldName ) { - case 'scale': - transformData.scale.set( fieldValues[ 0 ], fieldValues[ 1 ] ); - break; + case 'center': + transformData.center.set( fieldValues[ 0 ], fieldValues[ 1 ] ); + break; - case 'translation': - transformData.translation.set( fieldValues[ 0 ], fieldValues[ 1 ] ); - break; + case 'rotation': + transformData.rotation = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'scale': + transformData.scale.set( fieldValues[ 0 ], fieldValues[ 1 ] ); + break; - } + case 'translation': + transformData.translation.set( fieldValues[ 0 ], fieldValues[ 1 ] ); + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - return transformData; + } } - function buildGeometricNode( node ) { + return transformData; - return node.fields[ 0 ].values; + } - } + function buildGeometricNode( node ) { - function buildWorldInfoNode( node ) { + return node.fields[ 0 ].values; - var worldInfo = {}; + } - var fields = node.fields; + function buildWorldInfoNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const worldInfo = {}; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'title': - worldInfo.title = fieldValues[ 0 ]; - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'info': - worldInfo.info = fieldValues; - break; + switch ( fieldName ) { - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'title': + worldInfo.title = fieldValues[ 0 ]; + break; - } + case 'info': + worldInfo.info = fieldValues; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; - return worldInfo; + } } - function buildIndexedFaceSetNode( node ) { + return worldInfo; - var color, coord, normal, texCoord; - var ccw = true, solid = true, creaseAngle = 0; - var colorIndex, coordIndex, normalIndex, texCoordIndex; - var colorPerVertex = true, normalPerVertex = true; + } - var fields = node.fields; + function buildIndexedFaceSetNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + let color, coord, normal, texCoord; + let ccw = true, solid = true, creaseAngle = 0; + let colorIndex, coordIndex, normalIndex, texCoordIndex; + let colorPerVertex = true, normalPerVertex = true; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + const fields = node.fields; - switch ( fieldName ) { + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'color': - var colorNode = fieldValues[ 0 ]; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - if ( colorNode !== null ) { + switch ( fieldName ) { - color = getNode( colorNode ); + case 'color': + const colorNode = fieldValues[ 0 ]; - } + if ( colorNode !== null ) { - break; + color = getNode( colorNode ); - case 'coord': - var coordNode = fieldValues[ 0 ]; + } - if ( coordNode !== null ) { + break; - coord = getNode( coordNode ); + case 'coord': + const coordNode = fieldValues[ 0 ]; - } + if ( coordNode !== null ) { - break; + coord = getNode( coordNode ); - case 'normal': - var normalNode = fieldValues[ 0 ]; + } - if ( normalNode !== null ) { + break; - normal = getNode( normalNode ); + case 'normal': + const normalNode = fieldValues[ 0 ]; - } + if ( normalNode !== null ) { - break; + normal = getNode( normalNode ); - case 'texCoord': - var texCoordNode = fieldValues[ 0 ]; + } - if ( texCoordNode !== null ) { + break; - texCoord = getNode( texCoordNode ); + case 'texCoord': + const texCoordNode = fieldValues[ 0 ]; - } + if ( texCoordNode !== null ) { - break; + texCoord = getNode( texCoordNode ); - case 'ccw': - ccw = fieldValues[ 0 ]; - break; + } - case 'colorIndex': - colorIndex = fieldValues; - break; + break; - case 'colorPerVertex': - colorPerVertex = fieldValues[ 0 ]; - break; + case 'ccw': + ccw = fieldValues[ 0 ]; + break; - case 'convex': - // field not supported - break; + case 'colorIndex': + colorIndex = fieldValues; + break; - case 'coordIndex': - coordIndex = fieldValues; - break; + case 'colorPerVertex': + colorPerVertex = fieldValues[ 0 ]; + break; - case 'creaseAngle': - creaseAngle = fieldValues[ 0 ]; - break; + case 'convex': + // field not supported + break; - case 'normalIndex': - normalIndex = fieldValues; - break; + case 'coordIndex': + coordIndex = fieldValues; + break; - case 'normalPerVertex': - normalPerVertex = fieldValues[ 0 ]; - break; + case 'creaseAngle': + creaseAngle = fieldValues[ 0 ]; + break; - case 'solid': - solid = fieldValues[ 0 ]; - break; + case 'normalIndex': + normalIndex = fieldValues; + break; - case 'texCoordIndex': - texCoordIndex = fieldValues; - break; + case 'normalPerVertex': + normalPerVertex = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'solid': + solid = fieldValues[ 0 ]; + break; - } + case 'texCoordIndex': + texCoordIndex = fieldValues; + break; + + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - if ( coordIndex === undefined ) { + } - console.warn( 'THREE.VRMLLoader: Missing coordIndex.' ); + if ( coordIndex === undefined ) { - return new BufferGeometry(); // handle VRML files with incomplete geometry definition + console.warn( 'THREE.VRMLLoader: Missing coordIndex.' ); - } + return new BufferGeometry(); // handle VRML files with incomplete geometry definition - var triangulatedCoordIndex = triangulateFaceIndex( coordIndex, ccw ); + } - var positionAttribute; - var colorAttribute; - var normalAttribute; - var uvAttribute; + const triangulatedCoordIndex = triangulateFaceIndex( coordIndex, ccw ); - if ( color ) { + let colorAttribute; + let normalAttribute; + let uvAttribute; - if ( colorPerVertex === true ) { + if ( color ) { - if ( colorIndex && colorIndex.length > 0 ) { + if ( colorPerVertex === true ) { - // if the colorIndex field is not empty, then it is used to choose colors for each vertex of the IndexedFaceSet. + if ( colorIndex && colorIndex.length > 0 ) { - var triangulatedColorIndex = triangulateFaceIndex( colorIndex, ccw ); - colorAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedColorIndex, color, 3 ); + // if the colorIndex field is not empty, then it is used to choose colors for each vertex of the IndexedFaceSet. - } else { + const triangulatedColorIndex = triangulateFaceIndex( colorIndex, ccw ); + colorAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedColorIndex, color, 3 ); - // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the Color node + } else { - colorAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new Float32BufferAttribute( color, 3 ) ); + // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the Color node - } + colorAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new Float32BufferAttribute( color, 3 ) ); - } else { + } - if ( colorIndex && colorIndex.length > 0 ) { + } else { - // if the colorIndex field is not empty, then they are used to choose one color for each face of the IndexedFaceSet + if ( colorIndex && colorIndex.length > 0 ) { - var flattenFaceColors = flattenData( color, colorIndex ); - var triangulatedFaceColors = triangulateFaceData( flattenFaceColors, coordIndex ); - colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors ); + // if the colorIndex field is not empty, then they are used to choose one color for each face of the IndexedFaceSet - } else { + const flattenFaceColors = flattenData( color, colorIndex ); + const triangulatedFaceColors = triangulateFaceData( flattenFaceColors, coordIndex ); + colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors ); - // if the colorIndex field is empty, then the color are applied to each face of the IndexedFaceSet in order + } else { - var triangulatedFaceColors = triangulateFaceData( color, coordIndex ); - colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors ); + // if the colorIndex field is empty, then the color are applied to each face of the IndexedFaceSet in order + const triangulatedFaceColors = triangulateFaceData( color, coordIndex ); + colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors ); - } } } - if ( normal ) { + } - if ( normalPerVertex === true ) { + if ( normal ) { - // consider vertex normals + if ( normalPerVertex === true ) { - if ( normalIndex && normalIndex.length > 0 ) { + // consider vertex normals - // if the normalIndex field is not empty, then it is used to choose normals for each vertex of the IndexedFaceSet. + if ( normalIndex && normalIndex.length > 0 ) { - var triangulatedNormalIndex = triangulateFaceIndex( normalIndex, ccw ); - normalAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedNormalIndex, normal, 3 ); + // if the normalIndex field is not empty, then it is used to choose normals for each vertex of the IndexedFaceSet. - } else { + const triangulatedNormalIndex = triangulateFaceIndex( normalIndex, ccw ); + normalAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedNormalIndex, normal, 3 ); - // if the normalIndex field is empty, then the coordIndex field is used to choose normals from the Normal node + } else { - normalAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new Float32BufferAttribute( normal, 3 ) ); + // if the normalIndex field is empty, then the coordIndex field is used to choose normals from the Normal node - } + normalAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new Float32BufferAttribute( normal, 3 ) ); - } else { + } - // consider face normals + } else { - if ( normalIndex && normalIndex.length > 0 ) { + // consider face normals - // if the normalIndex field is not empty, then they are used to choose one normal for each face of the IndexedFaceSet + if ( normalIndex && normalIndex.length > 0 ) { - var flattenFaceNormals = flattenData( normal, normalIndex ); - var triangulatedFaceNormals = triangulateFaceData( flattenFaceNormals, coordIndex ); - normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals ); + // if the normalIndex field is not empty, then they are used to choose one normal for each face of the IndexedFaceSet - } else { + const flattenFaceNormals = flattenData( normal, normalIndex ); + const triangulatedFaceNormals = triangulateFaceData( flattenFaceNormals, coordIndex ); + normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals ); - // if the normalIndex field is empty, then the normals are applied to each face of the IndexedFaceSet in order + } else { - var triangulatedFaceNormals = triangulateFaceData( normal, coordIndex ); - normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals ); + // if the normalIndex field is empty, then the normals are applied to each face of the IndexedFaceSet in order - } + const triangulatedFaceNormals = triangulateFaceData( normal, coordIndex ); + normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals ); } - } else { + } - // if the normal field is NULL, then the loader should automatically generate normals, using creaseAngle to determine if and how normals are smoothed across shared vertices + } else { - normalAttribute = computeNormalAttribute( triangulatedCoordIndex, coord, creaseAngle ); + // if the normal field is NULL, then the loader should automatically generate normals, using creaseAngle to determine if and how normals are smoothed across shared vertices - } + normalAttribute = computeNormalAttribute( triangulatedCoordIndex, coord, creaseAngle ); - if ( texCoord ) { + } - // texture coordinates are always defined on vertex level + if ( texCoord ) { - if ( texCoordIndex && texCoordIndex.length > 0 ) { + // texture coordinates are always defined on vertex level - // if the texCoordIndex field is not empty, then it is used to choose texture coordinates for each vertex of the IndexedFaceSet. + if ( texCoordIndex && texCoordIndex.length > 0 ) { - var triangulatedTexCoordIndex = triangulateFaceIndex( texCoordIndex, ccw ); - uvAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedTexCoordIndex, texCoord, 2 ); + // if the texCoordIndex field is not empty, then it is used to choose texture coordinates for each vertex of the IndexedFaceSet. + const triangulatedTexCoordIndex = triangulateFaceIndex( texCoordIndex, ccw ); + uvAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedTexCoordIndex, texCoord, 2 ); - } else { - // if the texCoordIndex field is empty, then the coordIndex array is used to choose texture coordinates from the TextureCoordinate node + } else { - uvAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new Float32BufferAttribute( texCoord, 2 ) ); + // if the texCoordIndex field is empty, then the coordIndex array is used to choose texture coordinates from the TextureCoordinate node - } + uvAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new Float32BufferAttribute( texCoord, 2 ) ); } - var geometry = new BufferGeometry(); - positionAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new Float32BufferAttribute( coord, 3 ) ); + } - geometry.setAttribute( 'position', positionAttribute ); - geometry.setAttribute( 'normal', normalAttribute ); + const geometry = new BufferGeometry(); + const positionAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new Float32BufferAttribute( coord, 3 ) ); - // optional attributes + geometry.setAttribute( 'position', positionAttribute ); + geometry.setAttribute( 'normal', normalAttribute ); - if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); - if ( uvAttribute ) geometry.setAttribute( 'uv', uvAttribute ); + // optional attributes - // "solid" influences the material so let's store it for later use + if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); + if ( uvAttribute ) geometry.setAttribute( 'uv', uvAttribute ); - geometry._solid = solid; - geometry._type = 'mesh'; + // "solid" influences the material so let's store it for later use - return geometry; + geometry._solid = solid; + geometry._type = 'mesh'; - } + return geometry; - function buildIndexedLineSetNode( node ) { + } - var color, coord; - var colorIndex, coordIndex; - var colorPerVertex = true; + function buildIndexedLineSetNode( node ) { - var fields = node.fields; + let color, coord; + let colorIndex, coordIndex; + let colorPerVertex = true; - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'color': - var colorNode = fieldValues[ 0 ]; + switch ( fieldName ) { - if ( colorNode !== null ) { + case 'color': + const colorNode = fieldValues[ 0 ]; - color = getNode( colorNode ); + if ( colorNode !== null ) { - } + color = getNode( colorNode ); - break; + } - case 'coord': - var coordNode = fieldValues[ 0 ]; + break; - if ( coordNode !== null ) { + case 'coord': + const coordNode = fieldValues[ 0 ]; - coord = getNode( coordNode ); + if ( coordNode !== null ) { - } + coord = getNode( coordNode ); - break; + } - case 'colorIndex': - colorIndex = fieldValues; - break; + break; - case 'colorPerVertex': - colorPerVertex = fieldValues[ 0 ]; - break; + case 'colorIndex': + colorIndex = fieldValues; + break; - case 'coordIndex': - coordIndex = fieldValues; - break; + case 'colorPerVertex': + colorPerVertex = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'coordIndex': + coordIndex = fieldValues; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - // build lines + } - var colorAttribute; + // build lines - var expandedLineIndex = expandLineIndex( coordIndex ); // create an index for three.js's linesegment primitive + let colorAttribute; - if ( color ) { + const expandedLineIndex = expandLineIndex( coordIndex ); // create an index for three.js's linesegment primitive - if ( colorPerVertex === true ) { + if ( color ) { - if ( colorIndex.length > 0 ) { + if ( colorPerVertex === true ) { - // if the colorIndex field is not empty, then one color is used for each polyline of the IndexedLineSet. + if ( colorIndex.length > 0 ) { - var expandedColorIndex = expandLineIndex( colorIndex ); // compute colors for each line segment (rendering primitve) - colorAttribute = computeAttributeFromIndexedData( expandedLineIndex, expandedColorIndex, color, 3 ); // compute data on vertex level + // if the colorIndex field is not empty, then one color is used for each polyline of the IndexedLineSet. - } else { + const expandedColorIndex = expandLineIndex( colorIndex ); // compute colors for each line segment (rendering primitve) + colorAttribute = computeAttributeFromIndexedData( expandedLineIndex, expandedColorIndex, color, 3 ); // compute data on vertex level - // if the colorIndex field is empty, then the colors are applied to each polyline of the IndexedLineSet in order. + } else { - colorAttribute = toNonIndexedAttribute( expandedLineIndex, new Float32BufferAttribute( color, 3 ) ); + // if the colorIndex field is empty, then the colors are applied to each polyline of the IndexedLineSet in order. - } + colorAttribute = toNonIndexedAttribute( expandedLineIndex, new Float32BufferAttribute( color, 3 ) ); - } else { + } - if ( colorIndex.length > 0 ) { + } else { - // if the colorIndex field is not empty, then colors are applied to each vertex of the IndexedLineSet + if ( colorIndex.length > 0 ) { - var flattenLineColors = flattenData( color, colorIndex ); // compute colors for each VRML primitve - var expandedLineColors = expandLineData( flattenLineColors, coordIndex ); // compute colors for each line segment (rendering primitve) - colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level + // if the colorIndex field is not empty, then colors are applied to each vertex of the IndexedLineSet + const flattenLineColors = flattenData( color, colorIndex ); // compute colors for each VRML primitve + const expandedLineColors = expandLineData( flattenLineColors, coordIndex ); // compute colors for each line segment (rendering primitve) + colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level - } else { - // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the Color node + } else { - var expandedLineColors = expandLineData( color, coordIndex ); // compute colors for each line segment (rendering primitve) - colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level + // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the Color node - } + const expandedLineColors = expandLineData( color, coordIndex ); // compute colors for each line segment (rendering primitve) + colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level } } - // + } - var geometry = new BufferGeometry(); + // - var positionAttribute = toNonIndexedAttribute( expandedLineIndex, new Float32BufferAttribute( coord, 3 ) ); - geometry.setAttribute( 'position', positionAttribute ); + const geometry = new BufferGeometry(); - if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); + const positionAttribute = toNonIndexedAttribute( expandedLineIndex, new Float32BufferAttribute( coord, 3 ) ); + geometry.setAttribute( 'position', positionAttribute ); - geometry._type = 'line'; + if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); - return geometry; + geometry._type = 'line'; - } + return geometry; - function buildPointSetNode( node ) { + } - var geometry; - var color, coord; + function buildPointSetNode( node ) { - var fields = node.fields; + let color, coord; - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'color': - var colorNode = fieldValues[ 0 ]; + switch ( fieldName ) { - if ( colorNode !== null ) { + case 'color': + const colorNode = fieldValues[ 0 ]; - color = getNode( colorNode ); + if ( colorNode !== null ) { - } + color = getNode( colorNode ); - break; + } - case 'coord': - var coordNode = fieldValues[ 0 ]; + break; - if ( coordNode !== null ) { + case 'coord': + const coordNode = fieldValues[ 0 ]; - coord = getNode( coordNode ); + if ( coordNode !== null ) { - } + coord = getNode( coordNode ); - break; + } + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - var geometry = new BufferGeometry(); + } - geometry.setAttribute( 'position', new Float32BufferAttribute( coord, 3 ) ); - if ( color ) geometry.setAttribute( 'color', new Float32BufferAttribute( color, 3 ) ); + const geometry = new BufferGeometry(); - geometry._type = 'points'; + geometry.setAttribute( 'position', new Float32BufferAttribute( coord, 3 ) ); + if ( color ) geometry.setAttribute( 'color', new Float32BufferAttribute( color, 3 ) ); - return geometry; + geometry._type = 'points'; - } + return geometry; - function buildBoxNode( node ) { + } - var size = new Vector3( 2, 2, 2 ); + function buildBoxNode( node ) { - var fields = node.fields; + const size = new Vector3( 2, 2, 2 ); - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'size': - size.x = fieldValues[ 0 ]; - size.y = fieldValues[ 1 ]; - size.z = fieldValues[ 2 ]; - break; + switch ( fieldName ) { - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'size': + size.x = fieldValues[ 0 ]; + size.y = fieldValues[ 1 ]; + size.z = fieldValues[ 2 ]; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - var geometry = new BoxGeometry( size.x, size.y, size.z ); + } - return geometry; + const geometry = new BoxGeometry( size.x, size.y, size.z ); - } + return geometry; - function buildConeNode( node ) { + } - var radius = 1, height = 2, openEnded = false; + function buildConeNode( node ) { - var fields = node.fields; + let radius = 1, height = 2, openEnded = false; - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'bottom': - openEnded = ! fieldValues[ 0 ]; - break; + switch ( fieldName ) { - case 'bottomRadius': - radius = fieldValues[ 0 ]; - break; + case 'bottom': + openEnded = ! fieldValues[ 0 ]; + break; - case 'height': - height = fieldValues[ 0 ]; - break; + case 'bottomRadius': + radius = fieldValues[ 0 ]; + break; - case 'side': - // field not supported - break; + case 'height': + height = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'side': + // field not supported + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - var geometry = new ConeGeometry( radius, height, 16, 1, openEnded ); + } - return geometry; + const geometry = new ConeGeometry( radius, height, 16, 1, openEnded ); - } + return geometry; - function buildCylinderNode( node ) { + } - var radius = 1, height = 2; + function buildCylinderNode( node ) { - var fields = node.fields; + let radius = 1, height = 2; - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'bottom': - // field not supported - break; + switch ( fieldName ) { - case 'radius': - radius = fieldValues[ 0 ]; - break; + case 'bottom': + // field not supported + break; - case 'height': - height = fieldValues[ 0 ]; - break; + case 'radius': + radius = fieldValues[ 0 ]; + break; - case 'side': - // field not supported - break; + case 'height': + height = fieldValues[ 0 ]; + break; - case 'top': - // field not supported - break; + case 'side': + // field not supported + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'top': + // field not supported + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - var geometry = new CylinderGeometry( radius, radius, height, 16, 1 ); + } - return geometry; + const geometry = new CylinderGeometry( radius, radius, height, 16, 1 ); - } + return geometry; - function buildSphereNode( node ) { + } - var radius = 1; + function buildSphereNode( node ) { - var fields = node.fields; + let radius = 1; - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'radius': - radius = fieldValues[ 0 ]; - break; + switch ( fieldName ) { - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'radius': + radius = fieldValues[ 0 ]; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - var geometry = new SphereGeometry( radius, 16, 16 ); + } - return geometry; + const geometry = new SphereGeometry( radius, 16, 16 ); - } + return geometry; - function buildElevationGridNode( node ) { + } - var color; - var normal; - var texCoord; - var height; + function buildElevationGridNode( node ) { - var colorPerVertex = true; - var normalPerVertex = true; - var solid = true; - var ccw = true; - var creaseAngle = 0; - var xDimension = 2; - var zDimension = 2; - var xSpacing = 1; - var zSpacing = 1; + let color; + let normal; + let texCoord; + let height; - var fields = node.fields; + let colorPerVertex = true; + let normalPerVertex = true; + let solid = true; + let ccw = true; + let creaseAngle = 0; + let xDimension = 2; + let zDimension = 2; + let xSpacing = 1; + let zSpacing = 1; - for ( var i = 0, l = fields.length; i < l; i ++ ) { + const fields = node.fields; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - switch ( fieldName ) { + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'color': - var colorNode = fieldValues[ 0 ]; + switch ( fieldName ) { - if ( colorNode !== null ) { + case 'color': + const colorNode = fieldValues[ 0 ]; - color = getNode( colorNode ); + if ( colorNode !== null ) { - } + color = getNode( colorNode ); - break; + } - case 'normal': - var normalNode = fieldValues[ 0 ]; + break; - if ( normalNode !== null ) { + case 'normal': + const normalNode = fieldValues[ 0 ]; - normal = getNode( normalNode ); + if ( normalNode !== null ) { - } + normal = getNode( normalNode ); - break; + } - case 'texCoord': - var texCoordNode = fieldValues[ 0 ]; + break; - if ( texCoordNode !== null ) { + case 'texCoord': + const texCoordNode = fieldValues[ 0 ]; - texCoord = getNode( texCoordNode ); + if ( texCoordNode !== null ) { - } + texCoord = getNode( texCoordNode ); - break; + } - case 'height': - height = fieldValues; - break; + break; - case 'ccw': - ccw = fieldValues[ 0 ]; - break; + case 'height': + height = fieldValues; + break; - case 'colorPerVertex': - colorPerVertex = fieldValues[ 0 ]; - break; + case 'ccw': + ccw = fieldValues[ 0 ]; + break; - case 'creaseAngle': - creaseAngle = fieldValues[ 0 ]; - break; + case 'colorPerVertex': + colorPerVertex = fieldValues[ 0 ]; + break; - case 'normalPerVertex': - normalPerVertex = fieldValues[ 0 ]; - break; + case 'creaseAngle': + creaseAngle = fieldValues[ 0 ]; + break; - case 'solid': - solid = fieldValues[ 0 ]; - break; + case 'normalPerVertex': + normalPerVertex = fieldValues[ 0 ]; + break; - case 'xDimension': - xDimension = fieldValues[ 0 ]; - break; + case 'solid': + solid = fieldValues[ 0 ]; + break; - case 'xSpacing': - xSpacing = fieldValues[ 0 ]; - break; + case 'xDimension': + xDimension = fieldValues[ 0 ]; + break; - case 'zDimension': - zDimension = fieldValues[ 0 ]; - break; + case 'xSpacing': + xSpacing = fieldValues[ 0 ]; + break; - case 'zSpacing': - zSpacing = fieldValues[ 0 ]; - break; + case 'zDimension': + zDimension = fieldValues[ 0 ]; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'zSpacing': + zSpacing = fieldValues[ 0 ]; + break; - } + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - // vertex data + } - var vertices = []; - var normals = []; - var colors = []; - var uvs = []; + // vertex data - for ( var i = 0; i < zDimension; i ++ ) { + const vertices = []; + const normals = []; + const colors = []; + const uvs = []; - for ( var j = 0; j < xDimension; j ++ ) { + for ( let i = 0; i < zDimension; i ++ ) { - // compute a row major index + for ( let j = 0; j < xDimension; j ++ ) { - var index = ( i * xDimension ) + j; + // compute a row major index - // vertices + const index = ( i * xDimension ) + j; - var x = xSpacing * i; - var y = height[ index ]; - var z = zSpacing * j; + // vertices - vertices.push( x, y, z ); + const x = xSpacing * i; + const y = height[ index ]; + const z = zSpacing * j; - // colors + vertices.push( x, y, z ); - if ( color && colorPerVertex === true ) { + // colors - var r = color[ index * 3 + 0 ]; - var g = color[ index * 3 + 1 ]; - var b = color[ index * 3 + 2 ]; + if ( color && colorPerVertex === true ) { - colors.push( r, g, b ); + const r = color[ index * 3 + 0 ]; + const g = color[ index * 3 + 1 ]; + const b = color[ index * 3 + 2 ]; - } + colors.push( r, g, b ); - // normals + } - if ( normal && normalPerVertex === true ) { + // normals - var xn = normal[ index * 3 + 0 ]; - var yn = normal[ index * 3 + 1 ]; - var zn = normal[ index * 3 + 2 ]; + if ( normal && normalPerVertex === true ) { - normals.push( xn, yn, zn ); + const xn = normal[ index * 3 + 0 ]; + const yn = normal[ index * 3 + 1 ]; + const zn = normal[ index * 3 + 2 ]; - } + normals.push( xn, yn, zn ); - // uvs + } - if ( texCoord ) { + // uvs - var s = texCoord[ index * 2 + 0 ]; - var t = texCoord[ index * 2 + 1 ]; + if ( texCoord ) { - uvs.push( s, t ); + const s = texCoord[ index * 2 + 0 ]; + const t = texCoord[ index * 2 + 1 ]; + uvs.push( s, t ); - } else { - uvs.push( i / ( xDimension - 1 ), j / ( zDimension - 1 ) ); + } else { - } + uvs.push( i / ( xDimension - 1 ), j / ( zDimension - 1 ) ); } } - // indices + } - var indices = []; + // indices - for ( var i = 0; i < xDimension - 1; i ++ ) { + const indices = []; - for ( var j = 0; j < zDimension - 1; j ++ ) { + for ( let i = 0; i < xDimension - 1; i ++ ) { - // from https://tecfa.unige.ch/guides/vrml/vrml97/spec/part1/nodesRef.html#ElevationGrid + for ( let j = 0; j < zDimension - 1; j ++ ) { - var a = i + j * xDimension; - var b = i + ( j + 1 ) * xDimension; - var c = ( i + 1 ) + ( j + 1 ) * xDimension; - var d = ( i + 1 ) + j * xDimension; + // from https://tecfa.unige.ch/guides/vrml/vrml97/spec/part1/nodesRef.html#ElevationGrid - // faces + const a = i + j * xDimension; + const b = i + ( j + 1 ) * xDimension; + const c = ( i + 1 ) + ( j + 1 ) * xDimension; + const d = ( i + 1 ) + j * xDimension; - if ( ccw === true ) { + // faces - indices.push( a, c, b ); - indices.push( c, a, d ); + if ( ccw === true ) { - } else { + indices.push( a, c, b ); + indices.push( c, a, d ); - indices.push( a, b, c ); - indices.push( c, d, a ); + } else { - } + indices.push( a, b, c ); + indices.push( c, d, a ); } } - // + } - var positionAttribute = toNonIndexedAttribute( indices, new Float32BufferAttribute( vertices, 3 ) ); - var uvAttribute = toNonIndexedAttribute( indices, new Float32BufferAttribute( uvs, 2 ) ); - var colorAttribute; - var normalAttribute; + // - // color attribute + const positionAttribute = toNonIndexedAttribute( indices, new Float32BufferAttribute( vertices, 3 ) ); + const uvAttribute = toNonIndexedAttribute( indices, new Float32BufferAttribute( uvs, 2 ) ); + let colorAttribute; + let normalAttribute; - if ( color ) { + // color attribute - if ( colorPerVertex === false ) { + if ( color ) { - for ( var i = 0; i < xDimension - 1; i ++ ) { + if ( colorPerVertex === false ) { - for ( var j = 0; j < zDimension - 1; j ++ ) { + for ( let i = 0; i < xDimension - 1; i ++ ) { - var index = i + j * ( xDimension - 1 ); + for ( let j = 0; j < zDimension - 1; j ++ ) { - var r = color[ index * 3 + 0 ]; - var g = color[ index * 3 + 1 ]; - var b = color[ index * 3 + 2 ]; + const index = i + j * ( xDimension - 1 ); - // one color per quad + const r = color[ index * 3 + 0 ]; + const g = color[ index * 3 + 1 ]; + const b = color[ index * 3 + 2 ]; - colors.push( r, g, b ); colors.push( r, g, b ); colors.push( r, g, b ); - colors.push( r, g, b ); colors.push( r, g, b ); colors.push( r, g, b ); + // one color per quad - } + colors.push( r, g, b ); colors.push( r, g, b ); colors.push( r, g, b ); + colors.push( r, g, b ); colors.push( r, g, b ); colors.push( r, g, b ); } - colorAttribute = new Float32BufferAttribute( colors, 3 ); + } - } else { + colorAttribute = new Float32BufferAttribute( colors, 3 ); - colorAttribute = toNonIndexedAttribute( indices, new Float32BufferAttribute( colors, 3 ) ); + } else { - } + colorAttribute = toNonIndexedAttribute( indices, new Float32BufferAttribute( colors, 3 ) ); } - // normal attribute + } - if ( normal ) { + // normal attribute - if ( normalPerVertex === false ) { + if ( normal ) { - for ( var i = 0; i < xDimension - 1; i ++ ) { + if ( normalPerVertex === false ) { - for ( var j = 0; j < zDimension - 1; j ++ ) { + for ( let i = 0; i < xDimension - 1; i ++ ) { - var index = i + j * ( xDimension - 1 ); + for ( let j = 0; j < zDimension - 1; j ++ ) { - var xn = normal[ index * 3 + 0 ]; - var yn = normal[ index * 3 + 1 ]; - var zn = normal[ index * 3 + 2 ]; + const index = i + j * ( xDimension - 1 ); - // one normal per quad + const xn = normal[ index * 3 + 0 ]; + const yn = normal[ index * 3 + 1 ]; + const zn = normal[ index * 3 + 2 ]; - normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); - normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); + // one normal per quad - } + normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); + normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); } - normalAttribute = new Float32BufferAttribute( normals, 3 ); - - } else { - - normalAttribute = toNonIndexedAttribute( indices, new Float32BufferAttribute( normals, 3 ) ); - } + normalAttribute = new Float32BufferAttribute( normals, 3 ); + } else { - normalAttribute = computeNormalAttribute( indices, vertices, creaseAngle ); + normalAttribute = toNonIndexedAttribute( indices, new Float32BufferAttribute( normals, 3 ) ); } - // build geometry + } else { - var geometry = new BufferGeometry(); - geometry.setAttribute( 'position', positionAttribute ); - geometry.setAttribute( 'normal', normalAttribute ); - geometry.setAttribute( 'uv', uvAttribute ); + normalAttribute = computeNormalAttribute( indices, vertices, creaseAngle ); - if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); + } - // "solid" influences the material so let's store it for later use + // build geometry - geometry._solid = solid; - geometry._type = 'mesh'; + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', positionAttribute ); + geometry.setAttribute( 'normal', normalAttribute ); + geometry.setAttribute( 'uv', uvAttribute ); - return geometry; + if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute ); - } + // "solid" influences the material so let's store it for later use - function buildExtrusionNode( node ) { + geometry._solid = solid; + geometry._type = 'mesh'; - var crossSection = [ 1, 1, 1, - 1, - 1, - 1, - 1, 1, 1, 1 ]; - var spine = [ 0, 0, 0, 0, 1, 0 ]; - var scale; - var orientation; + return geometry; - var beginCap = true; - var ccw = true; - var creaseAngle = 0; - var endCap = true; - var solid = true; + } - var fields = node.fields; + function buildExtrusionNode( node ) { - for ( var i = 0, l = fields.length; i < l; i ++ ) { + let crossSection = [ 1, 1, 1, - 1, - 1, - 1, - 1, 1, 1, 1 ]; + let spine = [ 0, 0, 0, 0, 1, 0 ]; + let scale; + let orientation; - var field = fields[ i ]; - var fieldName = field.name; - var fieldValues = field.values; + let beginCap = true; + let ccw = true; + let creaseAngle = 0; + let endCap = true; + let solid = true; - switch ( fieldName ) { + const fields = node.fields; - case 'beginCap': - beginCap = fieldValues[ 0 ]; - break; + for ( let i = 0, l = fields.length; i < l; i ++ ) { - case 'ccw': - ccw = fieldValues[ 0 ]; - break; + const field = fields[ i ]; + const fieldName = field.name; + const fieldValues = field.values; - case 'convex': - // field not supported - break; + switch ( fieldName ) { - case 'creaseAngle': - creaseAngle = fieldValues[ 0 ]; - break; + case 'beginCap': + beginCap = fieldValues[ 0 ]; + break; - case 'crossSection': - crossSection = fieldValues; - break; + case 'ccw': + ccw = fieldValues[ 0 ]; + break; - case 'endCap': - endCap = fieldValues[ 0 ]; - break; + case 'convex': + // field not supported + break; - case 'orientation': - orientation = fieldValues; - break; + case 'creaseAngle': + creaseAngle = fieldValues[ 0 ]; + break; - case 'scale': - scale = fieldValues; - break; + case 'crossSection': + crossSection = fieldValues; + break; - case 'solid': - solid = fieldValues[ 0 ]; - break; + case 'endCap': + endCap = fieldValues[ 0 ]; + break; - case 'spine': - spine = fieldValues; // only extrusion along the Y-axis are supported so far - break; + case 'orientation': + orientation = fieldValues; + break; - default: - console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); - break; + case 'scale': + scale = fieldValues; + break; - } + case 'solid': + solid = fieldValues[ 0 ]; + break; + + case 'spine': + spine = fieldValues; // only extrusion along the Y-axis are supported so far + break; + + default: + console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); + break; } - var crossSectionClosed = ( crossSection[ 0 ] === crossSection[ crossSection.length - 2 ] && crossSection[ 1 ] === crossSection[ crossSection.length - 1 ] ); + } - // vertices + const crossSectionClosed = ( crossSection[ 0 ] === crossSection[ crossSection.length - 2 ] && crossSection[ 1 ] === crossSection[ crossSection.length - 1 ] ); - var vertices = []; - var spineVector = new Vector3(); - var scaling = new Vector3(); + // vertices - var axis = new Vector3(); - var vertex = new Vector3(); - var quaternion = new Quaternion(); + const vertices = []; + const spineVector = new Vector3(); + const scaling = new Vector3(); - for ( var i = 0, j = 0, o = 0, il = spine.length; i < il; i += 3, j += 2, o += 4 ) { + const axis = new Vector3(); + const vertex = new Vector3(); + const quaternion = new Quaternion(); - spineVector.fromArray( spine, i ); + for ( let i = 0, j = 0, o = 0, il = spine.length; i < il; i += 3, j += 2, o += 4 ) { - scaling.x = scale ? scale[ j + 0 ] : 1; - scaling.y = 1; - scaling.z = scale ? scale[ j + 1 ] : 1; + spineVector.fromArray( spine, i ); - axis.x = orientation ? orientation[ o + 0 ] : 0; - axis.y = orientation ? orientation[ o + 1 ] : 0; - axis.z = orientation ? orientation[ o + 2 ] : 1; - var angle = orientation ? orientation[ o + 3 ] : 0; + scaling.x = scale ? scale[ j + 0 ] : 1; + scaling.y = 1; + scaling.z = scale ? scale[ j + 1 ] : 1; - for ( var k = 0, kl = crossSection.length; k < kl; k += 2 ) { + axis.x = orientation ? orientation[ o + 0 ] : 0; + axis.y = orientation ? orientation[ o + 1 ] : 0; + axis.z = orientation ? orientation[ o + 2 ] : 1; + const angle = orientation ? orientation[ o + 3 ] : 0; - vertex.x = crossSection[ k + 0 ]; - vertex.y = 0; - vertex.z = crossSection[ k + 1 ]; + for ( let k = 0, kl = crossSection.length; k < kl; k += 2 ) { - // scale + vertex.x = crossSection[ k + 0 ]; + vertex.y = 0; + vertex.z = crossSection[ k + 1 ]; - vertex.multiply( scaling ); + // scale - // rotate + vertex.multiply( scaling ); - quaternion.setFromAxisAngle( axis, angle ); - vertex.applyQuaternion( quaternion ); + // rotate - // translate + quaternion.setFromAxisAngle( axis, angle ); + vertex.applyQuaternion( quaternion ); - vertex.add( spineVector ); + // translate - vertices.push( vertex.x, vertex.y, vertex.z ); + vertex.add( spineVector ); - } + vertices.push( vertex.x, vertex.y, vertex.z ); } - // indices + } - var indices = []; + // indices - var spineCount = spine.length / 3; - var crossSectionCount = crossSection.length / 2; + const indices = []; - for ( var i = 0; i < spineCount - 1; i ++ ) { + const spineCount = spine.length / 3; + const crossSectionCount = crossSection.length / 2; - for ( var j = 0; j < crossSectionCount - 1; j ++ ) { + for ( let i = 0; i < spineCount - 1; i ++ ) { - var a = j + i * crossSectionCount; - var b = ( j + 1 ) + i * crossSectionCount; - var c = j + ( i + 1 ) * crossSectionCount; - var d = ( j + 1 ) + ( i + 1 ) * crossSectionCount; + for ( let j = 0; j < crossSectionCount - 1; j ++ ) { - if ( ( j === crossSectionCount - 2 ) && ( crossSectionClosed === true ) ) { + const a = j + i * crossSectionCount; + let b = ( j + 1 ) + i * crossSectionCount; + const c = j + ( i + 1 ) * crossSectionCount; + let d = ( j + 1 ) + ( i + 1 ) * crossSectionCount; - b = i * crossSectionCount; - d = ( i + 1 ) * crossSectionCount; + if ( ( j === crossSectionCount - 2 ) && ( crossSectionClosed === true ) ) { - } + b = i * crossSectionCount; + d = ( i + 1 ) * crossSectionCount; - if ( ccw === true ) { + } - indices.push( a, b, c ); - indices.push( c, b, d ); + if ( ccw === true ) { - } else { + indices.push( a, b, c ); + indices.push( c, b, d ); - indices.push( a, c, b ); - indices.push( c, d, b ); + } else { - } + indices.push( a, c, b ); + indices.push( c, d, b ); } } - // triangulate cap + } - if ( beginCap === true || endCap === true ) { + // triangulate cap - var contour = []; + if ( beginCap === true || endCap === true ) { - for ( var i = 0, l = crossSection.length; i < l; i += 2 ) { + const contour = []; - contour.push( new Vector2( crossSection[ i ], crossSection[ i + 1 ] ) ); + for ( let i = 0, l = crossSection.length; i < l; i += 2 ) { - } + contour.push( new Vector2( crossSection[ i ], crossSection[ i + 1 ] ) ); - var faces = ShapeUtils.triangulateShape( contour, [] ); - var capIndices = []; + } - for ( var i = 0, l = faces.length; i < l; i ++ ) { + const faces = ShapeUtils.triangulateShape( contour, [] ); + const capIndices = []; - var face = faces[ i ]; + for ( let i = 0, l = faces.length; i < l; i ++ ) { - capIndices.push( face[ 0 ], face[ 1 ], face[ 2 ] ); + const face = faces[ i ]; - } + capIndices.push( face[ 0 ], face[ 1 ], face[ 2 ] ); - // begin cap + } - if ( beginCap === true ) { + // begin cap - for ( var i = 0, l = capIndices.length; i < l; i += 3 ) { + if ( beginCap === true ) { - if ( ccw === true ) { + for ( let i = 0, l = capIndices.length; i < l; i += 3 ) { - indices.push( capIndices[ i + 0 ], capIndices[ i + 1 ], capIndices[ i + 2 ] ); + if ( ccw === true ) { - } else { + indices.push( capIndices[ i + 0 ], capIndices[ i + 1 ], capIndices[ i + 2 ] ); - indices.push( capIndices[ i + 0 ], capIndices[ i + 2 ], capIndices[ i + 1 ] ); + } else { - } + indices.push( capIndices[ i + 0 ], capIndices[ i + 2 ], capIndices[ i + 1 ] ); } } - // end cap + } - if ( endCap === true ) { + // end cap - var indexOffset = crossSectionCount * ( spineCount - 1 ); // references to the first vertex of the last cross section + if ( endCap === true ) { - for ( var i = 0, l = capIndices.length; i < l; i += 3 ) { + const indexOffset = crossSectionCount * ( spineCount - 1 ); // references to the first vertex of the last cross section - if ( ccw === true ) { + for ( let i = 0, l = capIndices.length; i < l; i += 3 ) { - indices.push( indexOffset + capIndices[ i + 0 ], indexOffset + capIndices[ i + 2 ], indexOffset + capIndices[ i + 1 ] ); + if ( ccw === true ) { - } else { + indices.push( indexOffset + capIndices[ i + 0 ], indexOffset + capIndices[ i + 2 ], indexOffset + capIndices[ i + 1 ] ); - indices.push( indexOffset + capIndices[ i + 0 ], indexOffset + capIndices[ i + 1 ], indexOffset + capIndices[ i + 2 ] ); + } else { - } + indices.push( indexOffset + capIndices[ i + 0 ], indexOffset + capIndices[ i + 1 ], indexOffset + capIndices[ i + 2 ] ); } @@ -2682,593 +2675,597 @@ var VRMLLoader = ( function () { } - var positionAttribute = toNonIndexedAttribute( indices, new Float32BufferAttribute( vertices, 3 ) ); - var normalAttribute = computeNormalAttribute( indices, vertices, creaseAngle ); + } - var geometry = new BufferGeometry(); - geometry.setAttribute( 'position', positionAttribute ); - geometry.setAttribute( 'normal', normalAttribute ); - // no uvs yet + const positionAttribute = toNonIndexedAttribute( indices, new Float32BufferAttribute( vertices, 3 ) ); + const normalAttribute = computeNormalAttribute( indices, vertices, creaseAngle ); - // "solid" influences the material so let's store it for later use + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', positionAttribute ); + geometry.setAttribute( 'normal', normalAttribute ); + // no uvs yet - geometry._solid = solid; - geometry._type = 'mesh'; + // "solid" influences the material so let's store it for later use - return geometry; + geometry._solid = solid; + geometry._type = 'mesh'; - } + return geometry; - // helper functions + } - function resolveUSE( identifier ) { + // helper functions - var node = nodeMap[ identifier ]; - var build = getNode( node ); + function resolveUSE( identifier ) { - // because the same 3D objects can have different transformations, it's necessary to clone them. - // materials can be influenced by the geometry (e.g. vertex normals). cloning is necessary to avoid - // any side effects + const node = nodeMap[ identifier ]; + const build = getNode( node ); - return ( build.isObject3D || build.isMaterial ) ? build.clone() : build; + // because the same 3D objects can have different transformations, it's necessary to clone them. + // materials can be influenced by the geometry (e.g. vertex normals). cloning is necessary to avoid + // any side effects - } + return ( build.isObject3D || build.isMaterial ) ? build.clone() : build; - function parseFieldChildren( children, owner ) { + } - for ( var i = 0, l = children.length; i < l; i ++ ) { + function parseFieldChildren( children, owner ) { - var object = getNode( children[ i ] ); + for ( let i = 0, l = children.length; i < l; i ++ ) { - if ( object instanceof Object3D ) owner.add( object ); + const object = getNode( children[ i ] ); - } + if ( object instanceof Object3D ) owner.add( object ); } - function triangulateFaceIndex( index, ccw ) { + } - var indices = []; + function triangulateFaceIndex( index, ccw ) { - // since face defintions can have more than three vertices, it's necessary to - // perform a simple triangulation + const indices = []; - var start = 0; + // since face defintions can have more than three vertices, it's necessary to + // perform a simple triangulation - for ( var i = 0, l = index.length; i < l; i ++ ) { + let start = 0; - var i1 = index[ start ]; - var i2 = index[ i + ( ccw ? 1 : 2 ) ]; - var i3 = index[ i + ( ccw ? 2 : 1 ) ]; + for ( let i = 0, l = index.length; i < l; i ++ ) { - indices.push( i1, i2, i3 ); + const i1 = index[ start ]; + const i2 = index[ i + ( ccw ? 1 : 2 ) ]; + const i3 = index[ i + ( ccw ? 2 : 1 ) ]; - // an index of -1 indicates that the current face has ended and the next one begins + indices.push( i1, i2, i3 ); - if ( index[ i + 3 ] === - 1 || i + 3 >= l ) { + // an index of -1 indicates that the current face has ended and the next one begins - i += 3; - start = i + 1; + if ( index[ i + 3 ] === - 1 || i + 3 >= l ) { - } + i += 3; + start = i + 1; } - return indices; - } - function triangulateFaceData( data, index ) { + return indices; + + } - var triangulatedData = []; + function triangulateFaceData( data, index ) { - var start = 0; + const triangulatedData = []; - for ( var i = 0, l = index.length; i < l; i ++ ) { + let start = 0; - var stride = start * 3; + for ( let i = 0, l = index.length; i < l; i ++ ) { - var x = data[ stride ]; - var y = data[ stride + 1 ]; - var z = data[ stride + 2 ]; + const stride = start * 3; - triangulatedData.push( x, y, z ); + const x = data[ stride ]; + const y = data[ stride + 1 ]; + const z = data[ stride + 2 ]; - // an index of -1 indicates that the current face has ended and the next one begins + triangulatedData.push( x, y, z ); - if ( index[ i + 3 ] === - 1 || i + 3 >= l ) { + // an index of -1 indicates that the current face has ended and the next one begins - i += 3; - start ++; + if ( index[ i + 3 ] === - 1 || i + 3 >= l ) { - } + i += 3; + start ++; } - return triangulatedData; - } - function flattenData( data, index ) { + return triangulatedData; - var flattenData = []; + } - for ( var i = 0, l = index.length; i < l; i ++ ) { + function flattenData( data, index ) { - var i1 = index[ i ]; + const flattenData = []; - var stride = i1 * 3; + for ( let i = 0, l = index.length; i < l; i ++ ) { - var x = data[ stride ]; - var y = data[ stride + 1 ]; - var z = data[ stride + 2 ]; + const i1 = index[ i ]; - flattenData.push( x, y, z ); + const stride = i1 * 3; - } + const x = data[ stride ]; + const y = data[ stride + 1 ]; + const z = data[ stride + 2 ]; - return flattenData; + flattenData.push( x, y, z ); } - function expandLineIndex( index ) { + return flattenData; - var indices = []; + } - for ( var i = 0, l = index.length; i < l; i ++ ) { + function expandLineIndex( index ) { - var i1 = index[ i ]; - var i2 = index[ i + 1 ]; + const indices = []; - indices.push( i1, i2 ); + for ( let i = 0, l = index.length; i < l; i ++ ) { - // an index of -1 indicates that the current line has ended and the next one begins + const i1 = index[ i ]; + const i2 = index[ i + 1 ]; - if ( index[ i + 2 ] === - 1 || i + 2 >= l ) { + indices.push( i1, i2 ); - i += 2; + // an index of -1 indicates that the current line has ended and the next one begins - } + if ( index[ i + 2 ] === - 1 || i + 2 >= l ) { - } + i += 2; - return indices; + } } - function expandLineData( data, index ) { + return indices; - var triangulatedData = []; + } - var start = 0; + function expandLineData( data, index ) { - for ( var i = 0, l = index.length; i < l; i ++ ) { + const triangulatedData = []; - var stride = start * 3; + let start = 0; - var x = data[ stride ]; - var y = data[ stride + 1 ]; - var z = data[ stride + 2 ]; + for ( let i = 0, l = index.length; i < l; i ++ ) { - triangulatedData.push( x, y, z ); + const stride = start * 3; - // an index of -1 indicates that the current line has ended and the next one begins + const x = data[ stride ]; + const y = data[ stride + 1 ]; + const z = data[ stride + 2 ]; - if ( index[ i + 2 ] === - 1 || i + 2 >= l ) { + triangulatedData.push( x, y, z ); - i += 2; - start ++; + // an index of -1 indicates that the current line has ended and the next one begins - } + if ( index[ i + 2 ] === - 1 || i + 2 >= l ) { - } + i += 2; + start ++; - return triangulatedData; + } } - var vA = new Vector3(); - var vB = new Vector3(); - var vC = new Vector3(); + return triangulatedData; + + } - var uvA = new Vector2(); - var uvB = new Vector2(); - var uvC = new Vector2(); + const vA = new Vector3(); + const vB = new Vector3(); + const vC = new Vector3(); - function computeAttributeFromIndexedData( coordIndex, index, data, itemSize ) { + const uvA = new Vector2(); + const uvB = new Vector2(); + const uvC = new Vector2(); - var array = []; + function computeAttributeFromIndexedData( coordIndex, index, data, itemSize ) { - // we use the coordIndex.length as delimiter since normalIndex must contain at least as many indices + const array = []; - for ( var i = 0, l = coordIndex.length; i < l; i += 3 ) { + // we use the coordIndex.length as delimiter since normalIndex must contain at least as many indices - var a = index[ i ]; - var b = index[ i + 1 ]; - var c = index[ i + 2 ]; + for ( let i = 0, l = coordIndex.length; i < l; i += 3 ) { - if ( itemSize === 2 ) { + const a = index[ i ]; + const b = index[ i + 1 ]; + const c = index[ i + 2 ]; - uvA.fromArray( data, a * itemSize ); - uvB.fromArray( data, b * itemSize ); - uvC.fromArray( data, c * itemSize ); + if ( itemSize === 2 ) { - array.push( uvA.x, uvA.y ); - array.push( uvB.x, uvB.y ); - array.push( uvC.x, uvC.y ); + uvA.fromArray( data, a * itemSize ); + uvB.fromArray( data, b * itemSize ); + uvC.fromArray( data, c * itemSize ); - } else { + array.push( uvA.x, uvA.y ); + array.push( uvB.x, uvB.y ); + array.push( uvC.x, uvC.y ); - vA.fromArray( data, a * itemSize ); - vB.fromArray( data, b * itemSize ); - vC.fromArray( data, c * itemSize ); + } else { - array.push( vA.x, vA.y, vA.z ); - array.push( vB.x, vB.y, vB.z ); - array.push( vC.x, vC.y, vC.z ); + vA.fromArray( data, a * itemSize ); + vB.fromArray( data, b * itemSize ); + vC.fromArray( data, c * itemSize ); - } + array.push( vA.x, vA.y, vA.z ); + array.push( vB.x, vB.y, vB.z ); + array.push( vC.x, vC.y, vC.z ); } - return new Float32BufferAttribute( array, itemSize ); - } - function computeAttributeFromFaceData( index, faceData ) { + return new Float32BufferAttribute( array, itemSize ); - var array = []; + } - for ( var i = 0, j = 0, l = index.length; i < l; i += 3, j ++ ) { + function computeAttributeFromFaceData( index, faceData ) { - vA.fromArray( faceData, j * 3 ); + const array = []; - array.push( vA.x, vA.y, vA.z ); - array.push( vA.x, vA.y, vA.z ); - array.push( vA.x, vA.y, vA.z ); + for ( let i = 0, j = 0, l = index.length; i < l; i += 3, j ++ ) { - } + vA.fromArray( faceData, j * 3 ); - return new Float32BufferAttribute( array, 3 ); + array.push( vA.x, vA.y, vA.z ); + array.push( vA.x, vA.y, vA.z ); + array.push( vA.x, vA.y, vA.z ); } - function computeAttributeFromLineData( index, lineData ) { + return new Float32BufferAttribute( array, 3 ); - var array = []; + } - for ( var i = 0, j = 0, l = index.length; i < l; i += 2, j ++ ) { + function computeAttributeFromLineData( index, lineData ) { - vA.fromArray( lineData, j * 3 ); + const array = []; - array.push( vA.x, vA.y, vA.z ); - array.push( vA.x, vA.y, vA.z ); + for ( let i = 0, j = 0, l = index.length; i < l; i += 2, j ++ ) { - } + vA.fromArray( lineData, j * 3 ); - return new Float32BufferAttribute( array, 3 ); + array.push( vA.x, vA.y, vA.z ); + array.push( vA.x, vA.y, vA.z ); } - function toNonIndexedAttribute( indices, attribute ) { + return new Float32BufferAttribute( array, 3 ); - var array = attribute.array; - var itemSize = attribute.itemSize; + } - var array2 = new array.constructor( indices.length * itemSize ); + function toNonIndexedAttribute( indices, attribute ) { - var index = 0, index2 = 0; + const array = attribute.array; + const itemSize = attribute.itemSize; - for ( var i = 0, l = indices.length; i < l; i ++ ) { + const array2 = new array.constructor( indices.length * itemSize ); - index = indices[ i ] * itemSize; + let index = 0, index2 = 0; - for ( var j = 0; j < itemSize; j ++ ) { + for ( let i = 0, l = indices.length; i < l; i ++ ) { - array2[ index2 ++ ] = array[ index ++ ]; + index = indices[ i ] * itemSize; - } + for ( let j = 0; j < itemSize; j ++ ) { - } + array2[ index2 ++ ] = array[ index ++ ]; - return new Float32BufferAttribute( array2, itemSize ); + } } - var ab = new Vector3(); - var cb = new Vector3(); + return new Float32BufferAttribute( array2, itemSize ); - function computeNormalAttribute( index, coord, creaseAngle ) { + } - var faces = []; - var vertexNormals = {}; + const ab = new Vector3(); + const cb = new Vector3(); - // prepare face and raw vertex normals + function computeNormalAttribute( index, coord, creaseAngle ) { - for ( var i = 0, l = index.length; i < l; i += 3 ) { + const faces = []; + const vertexNormals = {}; - var a = index[ i ]; - var b = index[ i + 1 ]; - var c = index[ i + 2 ]; + // prepare face and raw vertex normals - var face = new Face( a, b, c ); + for ( let i = 0, l = index.length; i < l; i += 3 ) { - vA.fromArray( coord, a * 3 ); - vB.fromArray( coord, b * 3 ); - vC.fromArray( coord, c * 3 ); + const a = index[ i ]; + const b = index[ i + 1 ]; + const c = index[ i + 2 ]; - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + const face = new Face( a, b, c ); - cb.normalize(); + vA.fromArray( coord, a * 3 ); + vB.fromArray( coord, b * 3 ); + vC.fromArray( coord, c * 3 ); - face.normal.copy( cb ); + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - if ( vertexNormals[ a ] === undefined ) vertexNormals[ a ] = []; - if ( vertexNormals[ b ] === undefined ) vertexNormals[ b ] = []; - if ( vertexNormals[ c ] === undefined ) vertexNormals[ c ] = []; + cb.normalize(); - vertexNormals[ a ].push( face.normal ); - vertexNormals[ b ].push( face.normal ); - vertexNormals[ c ].push( face.normal ); + face.normal.copy( cb ); - faces.push( face ); + if ( vertexNormals[ a ] === undefined ) vertexNormals[ a ] = []; + if ( vertexNormals[ b ] === undefined ) vertexNormals[ b ] = []; + if ( vertexNormals[ c ] === undefined ) vertexNormals[ c ] = []; - } + vertexNormals[ a ].push( face.normal ); + vertexNormals[ b ].push( face.normal ); + vertexNormals[ c ].push( face.normal ); - // compute vertex normals and build final geometry + faces.push( face ); - var normals = []; + } - for ( var i = 0, l = faces.length; i < l; i ++ ) { + // compute vertex normals and build final geometry - var face = faces[ i ]; + const normals = []; - var nA = weightedNormal( vertexNormals[ face.a ], face.normal, creaseAngle ); - var nB = weightedNormal( vertexNormals[ face.b ], face.normal, creaseAngle ); - var nC = weightedNormal( vertexNormals[ face.c ], face.normal, creaseAngle ); + for ( let i = 0, l = faces.length; i < l; i ++ ) { - vA.fromArray( coord, face.a * 3 ); - vB.fromArray( coord, face.b * 3 ); - vC.fromArray( coord, face.c * 3 ); + const face = faces[ i ]; - normals.push( nA.x, nA.y, nA.z ); - normals.push( nB.x, nB.y, nB.z ); - normals.push( nC.x, nC.y, nC.z ); + const nA = weightedNormal( vertexNormals[ face.a ], face.normal, creaseAngle ); + const nB = weightedNormal( vertexNormals[ face.b ], face.normal, creaseAngle ); + const nC = weightedNormal( vertexNormals[ face.c ], face.normal, creaseAngle ); - } + vA.fromArray( coord, face.a * 3 ); + vB.fromArray( coord, face.b * 3 ); + vC.fromArray( coord, face.c * 3 ); - return new Float32BufferAttribute( normals, 3 ); + normals.push( nA.x, nA.y, nA.z ); + normals.push( nB.x, nB.y, nB.z ); + normals.push( nC.x, nC.y, nC.z ); } - function weightedNormal( normals, vector, creaseAngle ) { + return new Float32BufferAttribute( normals, 3 ); - var normal = new Vector3(); + } - if ( creaseAngle === 0 ) { + function weightedNormal( normals, vector, creaseAngle ) { - normal.copy( vector ); + const normal = new Vector3(); - } else { + if ( creaseAngle === 0 ) { - for ( var i = 0, l = normals.length; i < l; i ++ ) { + normal.copy( vector ); - if ( normals[ i ].angleTo( vector ) < creaseAngle ) { + } else { - normal.add( normals[ i ] ); + for ( let i = 0, l = normals.length; i < l; i ++ ) { - } + if ( normals[ i ].angleTo( vector ) < creaseAngle ) { + + normal.add( normals[ i ] ); } } - return normal.normalize(); - } - function toColorArray( colors ) { + return normal.normalize(); - var array = []; + } - for ( var i = 0, l = colors.length; i < l; i += 3 ) { + function toColorArray( colors ) { - array.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + const array = []; - } + for ( let i = 0, l = colors.length; i < l; i += 3 ) { - return array; + array.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); } - /** - * Vertically paints the faces interpolating between the - * specified colors at the specified angels. This is used for the Background - * node, but could be applied to other nodes with multiple faces as well. - * - * When used with the Background node, default is directionIsDown is true if - * interpolating the skyColor down from the Zenith. When interpolationg up from - * the Nadir i.e. interpolating the groundColor, the directionIsDown is false. - * - * The first angle is never specified, it is the Zenith (0 rad). Angles are specified - * in radians. The geometry is thought a sphere, but could be anything. The color interpolation - * is linear along the Y axis in any case. - * - * You must specify one more color than you have angles at the beginning of the colors array. - * This is the color of the Zenith (the top of the shape). - * - * @param {BufferGeometry} geometry - * @param {number} radius - * @param {array} angles - * @param {array} colors - * @param {boolean} topDown - Whether to work top down or bottom up. - */ - function paintFaces( geometry, radius, angles, colors, topDown ) { + return array; - // compute threshold values + } + + /** + * Vertically paints the faces interpolating between the + * specified colors at the specified angels. This is used for the Background + * node, but could be applied to other nodes with multiple faces as well. + * + * When used with the Background node, default is directionIsDown is true if + * interpolating the skyColor down from the Zenith. When interpolationg up from + * the Nadir i.e. interpolating the groundColor, the directionIsDown is false. + * + * The first angle is never specified, it is the Zenith (0 rad). Angles are specified + * in radians. The geometry is thought a sphere, but could be anything. The color interpolation + * is linear along the Y axis in any case. + * + * You must specify one more color than you have angles at the beginning of the colors array. + * This is the color of the Zenith (the top of the shape). + * + * @param {BufferGeometry} geometry + * @param {number} radius + * @param {array} angles + * @param {array} colors + * @param {boolean} topDown - Whether to work top down or bottom up. + */ + function paintFaces( geometry, radius, angles, colors, topDown ) { + + // compute threshold values + + const thresholds = []; + const startAngle = ( topDown === true ) ? 0 : Math.PI; + + for ( let i = 0, l = colors.length; i < l; i ++ ) { + + let angle = ( i === 0 ) ? 0 : angles[ i - 1 ]; + angle = ( topDown === true ) ? angle : ( startAngle - angle ); + + const point = new Vector3(); + point.setFromSphericalCoords( radius, angle, 0 ); + + thresholds.push( point ); - var thresholds = []; - var startAngle = ( topDown === true ) ? 0 : Math.PI; + } - for ( var i = 0, l = colors.length; i < l; i ++ ) { + // generate vertex colors - var angle = ( i === 0 ) ? 0 : angles[ i - 1 ]; - angle = ( topDown === true ) ? angle : ( startAngle - angle ); + const indices = geometry.index; + const positionAttribute = geometry.attributes.position; + const colorAttribute = new BufferAttribute( new Float32Array( geometry.attributes.position.count * 3 ), 3 ); - var point = new Vector3(); - point.setFromSphericalCoords( radius, angle, 0 ); + const position = new Vector3(); + const color = new Color(); - thresholds.push( point ); + for ( let i = 0; i < indices.count; i ++ ) { - } + const index = indices.getX( i ); + position.fromBufferAttribute( positionAttribute, index ); - // generate vertex colors + let thresholdIndexA, thresholdIndexB; + let t = 1; - var indices = geometry.index; - var positionAttribute = geometry.attributes.position; - var colorAttribute = new BufferAttribute( new Float32Array( geometry.attributes.position.count * 3 ), 3 ); + for ( let j = 1; j < thresholds.length; j ++ ) { - var position = new Vector3(); - var color = new Color(); + thresholdIndexA = j - 1; + thresholdIndexB = j; - for ( var i = 0; i < indices.count; i ++ ) { + const thresholdA = thresholds[ thresholdIndexA ]; + const thresholdB = thresholds[ thresholdIndexB ]; - var index = indices.getX( i ); - position.fromBufferAttribute( positionAttribute, index ); + if ( topDown === true ) { - var thresholdIndexA, thresholdIndexB; - var t = 1; + // interpolation for sky color - for ( var j = 1; j < thresholds.length; j ++ ) { + if ( position.y <= thresholdA.y && position.y > thresholdB.y ) { - thresholdIndexA = j - 1; - thresholdIndexB = j; + t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y ); - var thresholdA = thresholds[ thresholdIndexA ]; - var thresholdB = thresholds[ thresholdIndexB ]; + break; - if ( topDown === true ) { + } - // interpolation for sky color + } else { - if ( position.y <= thresholdA.y && position.y > thresholdB.y ) { + // interpolation for ground color - t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y ); + if ( position.y >= thresholdA.y && position.y < thresholdB.y ) { - break; + t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y ); - } + break; - } else { + } - // interpolation for ground color + } - if ( position.y >= thresholdA.y && position.y < thresholdB.y ) { + } - t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y ); + const colorA = colors[ thresholdIndexA ]; + const colorB = colors[ thresholdIndexB ]; - break; + color.copy( colorA ).lerp( colorB, t ); - } + colorAttribute.setXYZ( index, color.r, color.g, color.b ); - } + } - } + geometry.setAttribute( 'color', colorAttribute ); - var colorA = colors[ thresholdIndexA ]; - var colorB = colors[ thresholdIndexB ]; + } - color.copy( colorA ).lerp( colorB, t ); + // - colorAttribute.setXYZ( index, color.r, color.g, color.b ); + const textureLoader = new TextureLoader( this.manager ); + textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin ); - } + // check version (only 2.0 is supported) - geometry.setAttribute( 'color', colorAttribute ); + if ( data.indexOf( '#VRML V2.0' ) === - 1 ) { - } + throw Error( 'THREE.VRMLLexer: Version of VRML asset not supported.' ); - // + } - var textureLoader = new TextureLoader( this.manager ); - textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin ); + // create JSON representing the tree structure of the VRML asset - // check version (only 2.0 is supported) + const tree = generateVRMLTree( data ); - if ( data.indexOf( '#VRML V2.0' ) === - 1 ) { + // parse the tree structure to a three.js scene - throw Error( 'THREE.VRMLLexer: Version of VRML asset not supported.' ); + const scene = parseTree( tree ); - } + return scene; - // create JSON representing the tree structure of the VRML asset + } - var tree = generateVRMLTree( data ); +} - // parse the tree structure to a three.js scene +class VRMLLexer { - var scene = parseTree( tree ); + constructor( tokens ) { - return scene; + this.lexer = new chevrotain.Lexer( tokens ); // eslint-disable-line no-undef - } + } - } ); + lex( inputText ) { - function VRMLLexer( tokens ) { + const lexingResult = this.lexer.tokenize( inputText ); - this.lexer = new chevrotain.Lexer( tokens ); // eslint-disable-line no-undef + if ( lexingResult.errors.length > 0 ) { - } + console.error( lexingResult.errors ); - VRMLLexer.prototype = { + throw Error( 'THREE.VRMLLexer: Lexing errors detected.' ); - constructor: VRMLLexer, + } - lex: function ( inputText ) { + return lexingResult; - var lexingResult = this.lexer.tokenize( inputText ); + } - if ( lexingResult.errors.length > 0 ) { +} - console.error( lexingResult.errors ); +const ChevrotainParser = chevrotain.Parser;// eslint-disable-line no-undef - throw Error( 'THREE.VRMLLexer: Lexing errors detected.' ); +class VRMLParser extends ChevrotainParser { - } + constructor( tokenVocabulary ) { - return lexingResult; + super( tokenVocabulary ); - } + const $ = this; - }; - - function VRMLParser( tokenVocabulary ) { - - chevrotain.Parser.call( this, tokenVocabulary ); // eslint-disable-line no-undef - - var $ = this; - - var Version = tokenVocabulary[ 'Version' ]; - var LCurly = tokenVocabulary[ 'LCurly' ]; - var RCurly = tokenVocabulary[ 'RCurly' ]; - var LSquare = tokenVocabulary[ 'LSquare' ]; - var RSquare = tokenVocabulary[ 'RSquare' ]; - var Identifier = tokenVocabulary[ 'Identifier' ]; - var RouteIdentifier = tokenVocabulary[ 'RouteIdentifier' ]; - var StringLiteral = tokenVocabulary[ 'StringLiteral' ]; - var HexLiteral = tokenVocabulary[ 'HexLiteral' ]; - var NumberLiteral = tokenVocabulary[ 'NumberLiteral' ]; - var TrueLiteral = tokenVocabulary[ 'TrueLiteral' ]; - var FalseLiteral = tokenVocabulary[ 'FalseLiteral' ]; - var NullLiteral = tokenVocabulary[ 'NullLiteral' ]; - var DEF = tokenVocabulary[ 'DEF' ]; - var USE = tokenVocabulary[ 'USE' ]; - var ROUTE = tokenVocabulary[ 'ROUTE' ]; - var TO = tokenVocabulary[ 'TO' ]; - var NodeName = tokenVocabulary[ 'NodeName' ]; + const Version = tokenVocabulary[ 'Version' ]; + const LCurly = tokenVocabulary[ 'LCurly' ]; + const RCurly = tokenVocabulary[ 'RCurly' ]; + const LSquare = tokenVocabulary[ 'LSquare' ]; + const RSquare = tokenVocabulary[ 'RSquare' ]; + const Identifier = tokenVocabulary[ 'Identifier' ]; + const RouteIdentifier = tokenVocabulary[ 'RouteIdentifier' ]; + const StringLiteral = tokenVocabulary[ 'StringLiteral' ]; + const HexLiteral = tokenVocabulary[ 'HexLiteral' ]; + const NumberLiteral = tokenVocabulary[ 'NumberLiteral' ]; + const TrueLiteral = tokenVocabulary[ 'TrueLiteral' ]; + const FalseLiteral = tokenVocabulary[ 'FalseLiteral' ]; + const NullLiteral = tokenVocabulary[ 'NullLiteral' ]; + const DEF = tokenVocabulary[ 'DEF' ]; + const USE = tokenVocabulary[ 'USE' ]; + const ROUTE = tokenVocabulary[ 'ROUTE' ]; + const TO = tokenVocabulary[ 'TO' ]; + const NodeName = tokenVocabulary[ 'NodeName' ]; $.RULE( 'vrml', function () { @@ -3474,10 +3471,11 @@ var VRMLLoader = ( function () { } - VRMLParser.prototype = Object.create( chevrotain.Parser.prototype ); // eslint-disable-line no-undef - VRMLParser.prototype.constructor = VRMLParser; +} - function Face( a, b, c ) { +class Face { + + constructor( a, b, c ) { this.a = a; this.b = b; @@ -3486,15 +3484,13 @@ var VRMLLoader = ( function () { } - var TEXTURE_TYPE = { - INTENSITY: 1, - INTENSITY_ALPHA: 2, - RGB: 3, - RGBA: 4 - }; - - return VRMLLoader; +} -} )(); +const TEXTURE_TYPE = { + INTENSITY: 1, + INTENSITY_ALPHA: 2, + RGB: 3, + RGBA: 4 +}; export { VRMLLoader }; diff --git a/examples/jsm/loaders/VRMLoader.js b/examples/jsm/loaders/VRMLoader.js index 66638bd42b18a5..cf8c87e1e4bed9 100644 --- a/examples/jsm/loaders/VRMLoader.js +++ b/examples/jsm/loaders/VRMLoader.js @@ -8,9 +8,9 @@ import { GLTFLoader } from '../loaders/GLTFLoader.js'; // VRM is based on glTF 2.0 and VRM extension is defined // in top-level json.extensions.VRM -var VRMLoader = ( function () { +class VRMLoader extends Loader { - function VRMLoader( manager ) { + constructor( manager ) { if ( GLTFLoader === undefined ) { @@ -18,69 +18,61 @@ var VRMLoader = ( function () { } - Loader.call( this, manager ); + super( manager ); - this.gltfLoader = new GLTFLoader( this.manager ); + this.gltfLoader = new GLTFLoader( manager ); } - VRMLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + load( url, onLoad, onProgress, onError ) { - constructor: VRMLoader, + const scope = this; - load: function ( url, onLoad, onProgress, onError ) { + this.gltfLoader.load( url, function ( gltf ) { - var scope = this; + try { - this.gltfLoader.load( url, function ( gltf ) { + scope.parse( gltf, onLoad ); - try { + } catch ( e ) { - scope.parse( gltf, onLoad ); + if ( onError ) { - } catch ( e ) { + onError( e ); - if ( onError ) { + } else { - onError( e ); - - } else { - - console.error( e ); - - } - - scope.manager.itemError( url ); + console.error( e ); } - }, onProgress, onError ); + scope.manager.itemError( url ); - }, + } - setDRACOLoader: function ( dracoLoader ) { + }, onProgress, onError ); - this.gltfLoader.setDRACOLoader( dracoLoader ); - return this; + } - }, + setDRACOLoader( dracoLoader ) { - parse: function ( gltf, onLoad ) { + this.gltfLoader.setDRACOLoader( dracoLoader ); + return this; - // var gltfParser = gltf.parser; - // var gltfExtensions = gltf.userData.gltfExtensions || {}; - // var vrmExtension = gltfExtensions.VRM || {}; + } - // handle VRM Extension here + parse( gltf, onLoad ) { - onLoad( gltf ); + // const gltfParser = gltf.parser; + // const gltfExtensions = gltf.userData.gltfExtensions || {}; + // const vrmExtension = gltfExtensions.VRM || {}; - } + // handle VRM Extension here - } ); + onLoad( gltf ); - return VRMLoader; + } -} )(); +} export { VRMLoader };