language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
mrdoob
three.js
450e71cba34aa0524e67341548dc7635cdf3fc7f.json
Reset branch to dev
editor/js/Viewport.js
@@ -5,9 +5,6 @@ var Viewport = function ( editor ) { var signals = editor.signals; - var config = editor.config; - - var sceneCameras = editor.sceneCameras; var container = new UI.Panel(); container.setId( 'viewport' ); @@ -315,7 +312,6 @@ var Viewport = function ( editor ) { renderer.autoClear = false; renderer.autoUpdateScene = false; - renderer.setScissorTest( true ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight ); @@ -547,70 +543,17 @@ var Viewport = function ( editor ) { requestAnimationFrame( animate ); // - var viewport = new THREE.Vector4(); function render() { sceneHelpers.updateMatrixWorld(); scene.updateMatrixWorld(); - var width = container.dom.offsetWidth; - var height = container.dom.offsetHeight; - - viewport.set( 0, 0, width, height ); - renderScene( camera, viewport, true ); - - switch ( config.getKey( 'sceneCameraView' ) ) { - - case 'left': - for ( var i = 0; i < sceneCameras.length; ++ i ) { - - viewport.set( 0, height * 0.25 * i, width * 0.25, height * 0.25 ); - renderScene( sceneCameras[ i ], viewport ); - - } - break; - case 'right': - for ( var i = 0; i < sceneCameras.length; ++ i ) { - - viewport.set( width * 0.75, height * 0.25 * i, width * 0.25, height * 0.25 ); - renderScene( sceneCameras[ i ], viewport ); - - } - break; - case 'bottom': - for ( var i = 0; i < sceneCameras.length; ++ i ) { - - viewport.set( width * 0.25 * i, 0, width * 0.25, height * 0.25 ); - renderScene( sceneCameras[ i ], viewport ); - - } - break; - case 'top': - for ( var i = 0; i < sceneCameras.length; ++ i ) { - - viewport.set( width * 0.25 * i, height * 0.75, width * 0.25, height * 0.25 ); - renderScene( sceneCameras[ i ], viewport ); - - } - break; - default: - console.error( "Unknown scene view type: " + config.getKey( "sceneCameraView" ) ); - break; - - } - - } - - function renderScene( cam, viewport, showHelpers ) { - - renderer.setViewport( viewport ); - renderer.setScissor( viewport ); - renderer.render( scene, cam ); + renderer.render( scene, camera ); - if ( showHelpers === true && renderer instanceof THREE.RaytracingRenderer === false ) { + if ( renderer instanceof THREE.RaytracingRenderer === false ) { - renderer.render( sceneHelpers, cam ); + renderer.render( sceneHelpers, camera ); }
true
Other
mrdoob
three.js
471b9404eef23a4ec11bb6504de74cb9a1f196bc.json
Add TypeScript definitions for some utils
examples/jsm/utils/BufferGeometryUtils.d.ts
@@ -0,0 +1,7 @@ +import { BufferAttribute, BufferGeometry } from '../../../src/Three'; + +export namespace BufferGeometryUtils { + export function mergeBufferGeometries(geometries: BufferGeometry[]): BufferGeometry; + export function computeTangents(geometry: BufferGeometry): null; + export function mergeBufferAttributes(attributes: BufferAttribute[]): BufferAttribute; +}
true
Other
mrdoob
three.js
471b9404eef23a4ec11bb6504de74cb9a1f196bc.json
Add TypeScript definitions for some utils
examples/jsm/utils/GeometryUtils.d.ts
@@ -0,0 +1,13 @@ +/** + * @deprecated + */ +export namespace GeometryUtils { + /** + * @deprecated Use {@link Geometry#merge geometry.merge( geometry2, matrix, materialIndexOffset )} instead. + */ + export function merge(geometry1: any, geometry2: any, materialIndexOffset?: any): any; + /** + * @deprecated Use {@link Geometry#center geometry.center()} instead. + */ + export function center(geometry: any): any; +}
true
Other
mrdoob
three.js
471b9404eef23a4ec11bb6504de74cb9a1f196bc.json
Add TypeScript definitions for some utils
examples/jsm/utils/SceneUtils.d.ts
@@ -0,0 +1,7 @@ +import { Geometry, Material, Object3D, Scene } from '../../../src/Three'; + +export namespace SceneUtils { + export function createMultiMaterialObject(geometry: Geometry, materials: Material[]): Object3D; + export function detach(child: Object3D, parent: Object3D, scene: Scene): void; + export function attach(child: Object3D, scene: Scene, parent: Object3D): void; +}
true
Other
mrdoob
three.js
5ab4aa1c53b498f4f99d1dccfa293c8e24cb1bcb.json
Update code style
editor/js/Sidebar.Object.js
@@ -318,32 +318,36 @@ Sidebar.Object = function ( editor ) { var cameraViewRow = new UI.Row().setDisplay( editor.selected !== null && editor.selected.isCamera ? 'block' : 'none' ); container.add( cameraViewRow ); - cameraViewRow.add( new UI.Text(strings.getKey( 'sidebar/object/view' )).setWidth('90px')); + cameraViewRow.add( new UI.Text( strings.getKey( 'sidebar/object/view' ) ).setWidth( '90px' ) ); + + var cameraViewCheckbox = new UI.Checkbox( false ).onChange( update ).onClick( function () { - var cameraViewCheckbox = new UI.Checkbox(false).onChange(update).onClick(function() { var object = editor.selected; - if(object.isCamera !== true) return; - - if(sceneCameras.indexOf(object) === -1) - { - if(sceneCameras.length === 4) - { - alert("Only 4 scene cameras can be shown at once."); - cameraViewCheckbox.setValue(false); + if ( object.isCamera !== true ) return; + + if ( sceneCameras.indexOf( object ) === - 1 ) { + + if ( sceneCameras.length === 4 ) { + + alert( "Only 4 scene cameras can be shown at once." ); + cameraViewCheckbox.setValue( false ); return; + } - sceneCameras.push(object); - cameraViewCheckbox.setValue(true); - } - else - { - sceneCameras.splice(sceneCameras.indexOf(object), 1); - cameraViewCheckbox.setValue(false); + sceneCameras.push( object ); + cameraViewCheckbox.setValue( true ); + + } else { + + sceneCameras.splice( sceneCameras.indexOf( object ), 1 ); + cameraViewCheckbox.setValue( false ); + } signals.sceneGraphChanged.dispatch(); - }); + + } ); cameraViewRow.add( cameraViewCheckbox ); // @@ -722,14 +726,15 @@ Sidebar.Object = function ( editor ) { } - if(object.isCamera === true) { + if ( object.isCamera === true ) { - cameraViewRow.setDisplay('block'); - cameraViewCheckbox.setValue(sceneCameras.indexOf(object) !== -1) + cameraViewRow.setDisplay( 'block' ); + cameraViewCheckbox.setValue( sceneCameras.indexOf( object ) !== - 1 ); + + } else { + + cameraViewRow.setDisplay( 'none' ); - } - else { - cameraViewRow.setDisplay('none'); } objectVisible.setValue( object.visible );
true
Other
mrdoob
three.js
5ab4aa1c53b498f4f99d1dccfa293c8e24cb1bcb.json
Update code style
editor/js/Sidebar.Settings.Viewport.js
@@ -18,28 +18,30 @@ Sidebar.Settings.Viewport = function ( editor ) { container.add( new UI.Text( strings.getKey( 'sidebar/settings/viewport/view' ) ).setWidth( '90px' ) ); - var sceneViewOptions = new UI.Select().setOptions({ - left : 'left', - right : 'right', - top : 'top', - bottom : 'bottom' - }); - - if(config.getKey('sceneView') !== undefined) - { - sceneViewOptions.setValue(config.getKey('sceneView')); - } - else - { - sceneViewOptions.setValue('left'); + var sceneViewOptions = new UI.Select().setOptions( { + left: 'left', + right: 'right', + top: 'top', + bottom: 'bottom' + } ); + + if ( config.getKey( 'sceneCameraView' ) !== undefined ) { + + sceneViewOptions.setValue( config.getKey( 'sceneCameraView' ) ); + + } else { + + sceneViewOptions.setValue( 'left' ); + } - - sceneViewOptions.onChange(function() - { - config.setKey('sceneView', sceneViewOptions.getValue()); + + sceneViewOptions.onChange( function () { + + config.setKey( 'sceneCameraView', sceneViewOptions.getValue() ); signals.sceneGraphChanged.dispatch(); - }); - container.add(sceneViewOptions); + + } ); + container.add( sceneViewOptions ); /* var snapSize = new UI.Number( 25 ).setWidth( '40px' ).onChange( update );
true
Other
mrdoob
three.js
5ab4aa1c53b498f4f99d1dccfa293c8e24cb1bcb.json
Update code style
editor/js/Storage.js
@@ -6,7 +6,7 @@ var Storage = function () { var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; - if ( indexedDB === undefined ) { + if ( indexedDB === undefined ) { console.warn( 'Storage: IndexedDB not available.' ); return { init: function () {}, get: function () {}, set: function () {}, clear: function () {} };
true
Other
mrdoob
three.js
5ab4aa1c53b498f4f99d1dccfa293c8e24cb1bcb.json
Update code style
editor/js/Viewport.js
@@ -315,7 +315,7 @@ var Viewport = function ( editor ) { renderer.autoClear = false; renderer.autoUpdateScene = false; - renderer.setScissorTest(true); + renderer.setScissorTest( true ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight ); @@ -556,53 +556,64 @@ var Viewport = function ( editor ) { var width = container.dom.offsetWidth; var height = container.dom.offsetHeight; - - viewport.set(0, 0, width, height); - renderScene(camera, viewport, true); - switch(config.getKey('sceneView')) - { + viewport.set( 0, 0, width, height ); + renderScene( camera, viewport, true ); + + switch ( config.getKey( 'sceneCameraView' ) ) { + case 'left': - for(var i = 0; i < sceneCameras.length; ++i) { - viewport.set(0, height * 0.25 * i, width * 0.25, height * 0.25); - renderScene(sceneCameras[i], viewport); + for ( var i = 0; i < sceneCameras.length; ++ i ) { + + viewport.set( 0, height * 0.25 * i, width * 0.25, height * 0.25 ); + renderScene( sceneCameras[ i ], viewport ); + } break; case 'right': - for(var i = 0; i < sceneCameras.length; ++i) { - viewport.set(width * 0.75, height * 0.25 * i, width * 0.25, height * 0.25); - renderScene(sceneCameras[i], viewport); + for ( var i = 0; i < sceneCameras.length; ++ i ) { + + viewport.set( width * 0.75, height * 0.25 * i, width * 0.25, height * 0.25 ); + renderScene( sceneCameras[ i ], viewport ); + } break; case 'bottom': - for(var i = 0; i < sceneCameras.length; ++i) { - viewport.set(width * 0.25 * i, 0, width * 0.25, height * 0.25); - renderScene(sceneCameras[i], viewport); + for ( var i = 0; i < sceneCameras.length; ++ i ) { + + viewport.set( width * 0.25 * i, 0, width * 0.25, height * 0.25 ); + renderScene( sceneCameras[ i ], viewport ); + } break; case 'top': - for(var i = 0; i < sceneCameras.length; ++i) { - viewport.set(width * 0.25 * i, height * 0.75, width * 0.25, height * 0.25); - renderScene(sceneCameras[i], viewport); + for ( var i = 0; i < sceneCameras.length; ++ i ) { + + viewport.set( width * 0.25 * i, height * 0.75, width * 0.25, height * 0.25 ); + renderScene( sceneCameras[ i ], viewport ); + } break; default: - console.error("Unknown scene view type: " + config.getKey("sceneView")); + console.error( "Unknown scene view type: " + config.getKey( "sceneCameraView" ) ); break; + } + } - function renderScene(cam, viewport, showHelpers) - { - renderer.setViewport(viewport); - renderer.setScissor(viewport); + function renderScene( cam, viewport, showHelpers ) { + + renderer.setViewport( viewport ); + renderer.setScissor( viewport ); renderer.render( scene, cam ); if ( showHelpers === true && renderer instanceof THREE.RaytracingRenderer === false ) { renderer.render( sceneHelpers, cam ); } + } return container;
true
Other
mrdoob
three.js
53025930cb233a92120a128f34aead87e51cb7f5.json
Remove the material from the Object3D typings.
src/core/Object3D.d.ts
@@ -39,11 +39,6 @@ export class Object3D extends EventDispatcher { name: string; type: string; - - /** - * The material of the object. - */ - material: Material; /** * Object's parent in the scene graph.
false
Other
mrdoob
three.js
dd184263c3225e65c5b342be05d5da5c26fdc8da.json
Get camera values from matrix world
editor/js/Sidebar.Object.js
@@ -323,6 +323,7 @@ Sidebar.Object = function ( editor ) { if ( editor.selected.isCamera === true && cameraTransitioning === false ) { + editor.selected.updateMatrixWorld( true ); editor.currentCamera = transitionCamera; transitionCamera.copy( editor.selected ); cameraViewButton.dom.setAttribute( 'viewset', '' ); @@ -417,9 +418,13 @@ Sidebar.Object = function ( editor ) { function getCameraData( camera ) { + var position = new THREE.Vector3(); + var quaternion = new THREE.Quaternion(); + var scale = new THREE.Vector3(); + camera.matrixWorld.decompose( position, quaternion, scale ); return { - position: camera.position.clone(), - quaternion: camera.quaternion.clone(), + position: position, + quaternion: quaternion, fov: camera.fov, near: camera.near, far: camera.far,
false
Other
mrdoob
three.js
91c461372bbbd499fb6dde9596af913c5cc1b348.json
Add TypeScript definitions for MTLLoader
examples/jsm/loaders/MTLLoader.d.ts
@@ -0,0 +1,104 @@ +import { + Material, + LoadingManager, + Mapping, + EventDispatcher, + BufferGeometry, + Side, + Texture, + Vector2, + Wrapping +} from '../../../src/Three'; + +export interface MaterialCreatorOptions { + /** + * side: Which side to apply the material + * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide + */ + side?: Side; + /* + * wrap: What type of wrapping to apply for textures + * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping + */ + wrap?: Wrapping; + /* + * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255 + * Default: false, assumed to be already normalized + */ + normalizeRGB?: boolean; + /* + * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's + * Default: false + */ + ignoreZeroRGBs?: boolean; + /* + * invertTrProperty: Use values 1 of Tr field for fully opaque. This option is useful for obj + * exported from 3ds MAX, vcglib or meshlab. + * Default: false + */ + invertTrProperty?: boolean; +} + +export class MTLLoader extends EventDispatcher { + constructor(manager?: LoadingManager); + manager: LoadingManager; + materialOptions: MaterialCreatorOptions; + path: string; + texturePath: string; + crossOrigin: boolean; + + load(url: string, onLoad: (materialCreator: MaterialCreator) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; + parse(text: string) : MaterialCreator; + setPath(path: string) : void; + setTexturePath(path: string) : void; + setBaseUrl(path: string) : void; + setCrossOrigin(value: boolean) : void; + setMaterialOptions(value: MaterialCreatorOptions) : void; +} + +export interface MaterialInfo { + ks?: number[]; + kd?: number[]; + ke?: number[]; + map_kd?: string; + map_ks?: string; + map_ke?: string; + norm?: string; + map_bump?: string; + bump?: string; + map_d?: string; + ns?: number; + d?: number; + tr?: number; +} + +export interface TexParams { + scale: Vector2; + offset: Vector2; + url: string; +} + +export class MaterialCreator { + constructor(baseUrl?: string, options?: MaterialCreatorOptions); + + baseUrl : string; + options : MaterialCreatorOptions; + materialsInfo : {[key: string]: MaterialInfo}; + materials : {[key: string]: Material}; + private materialsArray : Material[]; + nameLookup : {[key: string]: number}; + side : Side; + wrap : Wrapping; + + setCrossOrigin( value: boolean ) : void; + setManager( value: LoadingManager ) : void; + setMaterials( materialsInfo: {[key: string]: MaterialInfo} ) : void; + convert( materialsInfo: {[key: string]: MaterialInfo} ) : {[key: string]: MaterialInfo}; + preload() : void; + getIndex( materialName: string ) : Material; + getAsArray() : Material[]; + create( materialName: string ) : Material; + createMaterial_( materialName: string ) : Material; + getTextureParams( value: string, matParams: any ) : TexParams; + loadTexture(url: string, mapping?: Mapping, onLoad?: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): Texture; +}
false
Other
mrdoob
three.js
abfcd4aa188f978d07592e4f494ad30d945a171a.json
Resolve performance issue: 55~ 60fps
examples/js/MarchingCubes.js
@@ -47,7 +47,7 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) this.field = new Float32Array( this.size3 ); this.normal_cache = new Float32Array( this.size3 * 3 ); - this.palette = new Float32Array( this.size3 * 4 ); + this.palette = new Float32Array( this.size3 * 3 ); // immediate render mode simulator @@ -86,7 +86,7 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) } - function VIntX( q, offset, isol, x, y, z, valp1, valp2, c_valp1, c_valp2 ) { + function VIntX( q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2 ) { var mu = ( isol - valp1 ) / ( valp2 - valp1 ), nc = scope.normal_cache; @@ -99,13 +99,13 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) nlist[ offset + 1 ] = lerp( nc[ q + 1 ], nc[ q + 4 ], mu ); nlist[ offset + 2 ] = lerp( nc[ q + 2 ], nc[ q + 5 ], mu ); - clist[ offset + 0 ] = lerp( c_valp1[ 0 ], c_valp2[ 0 ], mu ); - clist[ offset + 1 ] = lerp( c_valp1[ 1 ], c_valp2[ 1 ], mu ); - clist[ offset + 2 ] = lerp( c_valp1[ 2 ], c_valp2[ 2 ], mu ); + clist[ offset + 0 ] = lerp( scope.palette[ c_offset1 * 3 + 0 ], scope.palette[ c_offset2 * 3 + 0 ], mu ); + clist[ offset + 1 ] = lerp( scope.palette[ c_offset1 * 3 + 1 ], scope.palette[ c_offset2 * 3 + 1 ], mu ); + clist[ offset + 2 ] = lerp( scope.palette[ c_offset1 * 3 + 2 ], scope.palette[ c_offset2 * 3 + 2 ], mu ); } - function VIntY( q, offset, isol, x, y, z, valp1, valp2, c_valp1, c_valp2 ) { + function VIntY( q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2 ) { var mu = ( isol - valp1 ) / ( valp2 - valp1 ), nc = scope.normal_cache; @@ -120,13 +120,13 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) nlist[ offset + 1 ] = lerp( nc[ q + 1 ], nc[ q2 + 1 ], mu ); nlist[ offset + 2 ] = lerp( nc[ q + 2 ], nc[ q2 + 2 ], mu ); - clist[ offset + 0 ] = lerp( c_valp1[ 0 ], c_valp2[ 0 ], mu ); - clist[ offset + 1 ] = lerp( c_valp1[ 1 ], c_valp2[ 1 ], mu ); - clist[ offset + 2 ] = lerp( c_valp1[ 2 ], c_valp2[ 2 ], mu ); + clist[ offset + 0 ] = lerp( scope.palette[ c_offset1 * 3 + 0 ], scope.palette[ c_offset2 * 3 + 0 ], mu ); + clist[ offset + 1 ] = lerp( scope.palette[ c_offset1 * 3 + 1 ], scope.palette[ c_offset2 * 3 + 1 ], mu ); + clist[ offset + 2 ] = lerp( scope.palette[ c_offset1 * 3 + 2 ], scope.palette[ c_offset2 * 3 + 2 ], mu ); } - function VIntZ( q, offset, isol, x, y, z, valp1, valp2, c_valp1, c_valp2 ) { + function VIntZ( q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2 ) { var mu = ( isol - valp1 ) / ( valp2 - valp1 ), nc = scope.normal_cache; @@ -141,9 +141,9 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) nlist[ offset + 1 ] = lerp( nc[ q + 1 ], nc[ q2 + 1 ], mu ); nlist[ offset + 2 ] = lerp( nc[ q + 2 ], nc[ q2 + 2 ], mu ); - clist[ offset + 0 ] = lerp( c_valp1[ 0 ], c_valp2[ 0 ], mu ); - clist[ offset + 1 ] = lerp( c_valp1[ 1 ], c_valp2[ 1 ], mu ); - clist[ offset + 2 ] = lerp( c_valp1[ 2 ], c_valp2[ 2 ], mu ); + clist[ offset + 0 ] = lerp( scope.palette[ c_offset1 * 3 + 0 ], scope.palette[ c_offset2 * 3 + 0 ], mu ); + clist[ offset + 1 ] = lerp( scope.palette[ c_offset1 * 3 + 1 ], scope.palette[ c_offset2 * 3 + 1 ], mu ); + clist[ offset + 2 ] = lerp( scope.palette[ c_offset1 * 3 + 2 ], scope.palette[ c_offset2 * 3 + 2 ], mu ); } @@ -187,31 +187,6 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) field6 = scope.field[ qyz ], field7 = scope.field[ q1yz ]; - var c_field0 = scope.palette - .slice( q * 4, q * 4 + 3 ) - .map( v => v / scope.palette[ q * 4 + 3 ] ), // slicing (r, g, b) part - c_field1 = scope.palette - .slice( q1 * 4, q1 * 4 + 3 ) - .map( v => v / scope.palette[ q1 * 4 + 3 ] ), - c_field2 = scope.palette - .slice( qy * 4, qy * 4 + 3 ) - .map( v => v / scope.palette[ qy * 4 + 3 ] ), - c_field3 = scope.palette - .slice( q1y * 4, q1y * 4 + 3 ) - .map( v => v / scope.palette[ q1y * 4 + 3 ] ), - c_field4 = scope.palette - .slice( qz * 4, qz * 4 + 3 ) - .map( v => v / scope.palette[ qz * 4 + 3 ] ), - c_field5 = scope.palette - .slice( q1z * 4, q1z * 4 + 3 ) - .map( v => v / scope.palette[ q1z * 4 + 3 ] ), - c_field6 = scope.palette - .slice( qyz * 4, qyz * 4 + 3 ) - .map( v => v / scope.palette[ qyz * 4 + 3 ] ), - c_field7 = scope.palette - .slice( q1yz * 4, q1yz * 4 + 3 ) - .map( v => v / scope.palette[ q1yz * 4 + 3 ] ); - if ( field0 < isol ) cubeindex |= 1; if ( field1 < isol ) cubeindex |= 2; if ( field2 < isol ) cubeindex |= 8; @@ -237,31 +212,31 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) compNorm( q ); compNorm( q1 ); - VIntX( q * 3, 0, isol, fx, fy, fz, field0, field1, c_field0, c_field1 ); + VIntX( q * 3, 0, isol, fx, fy, fz, field0, field1, q, q1 ); } if ( bits & 2 ) { compNorm( q1 ); compNorm( q1y ); - VIntY( q1 * 3, 3, isol, fx2, fy, fz, field1, field3, c_field1, c_field3 ); + VIntY( q1 * 3, 3, isol, fx2, fy, fz, field1, field3, q1, q1y ); } if ( bits & 4 ) { compNorm( qy ); compNorm( q1y ); - VIntX( qy * 3, 6, isol, fx, fy2, fz, field2, field3, c_field2, c_field3 ); + VIntX( qy * 3, 6, isol, fx, fy2, fz, field2, field3, qy, q1y ); } if ( bits & 8 ) { compNorm( q ); compNorm( qy ); - VIntY( q * 3, 9, isol, fx, fy, fz, field0, field2, c_field0, c_field2 ); + VIntY( q * 3, 9, isol, fx, fy, fz, field0, field2, q, qy ); } @@ -271,7 +246,7 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) compNorm( qz ); compNorm( q1z ); - VIntX( qz * 3, 12, isol, fx, fy, fz2, field4, field5, c_field4, c_field5 ); + VIntX( qz * 3, 12, isol, fx, fy, fz2, field4, field5, qz, q1z ); } @@ -288,8 +263,8 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) fz2, field5, field7, - c_field5, - c_field7 + q1z, + q1yz ); } @@ -307,8 +282,8 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) fz2, field6, field7, - c_field6, - c_field7 + qyz, + q1yz ); } @@ -317,7 +292,7 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) compNorm( qz ); compNorm( qyz ); - VIntY( qz * 3, 21, isol, fx, fy, fz2, field4, field6, c_field4, c_field6 ); + VIntY( qz * 3, 21, isol, fx, fy, fz2, field4, field6, qz, qyz ); } @@ -326,15 +301,15 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) compNorm( q ); compNorm( qz ); - VIntZ( q * 3, 24, isol, fx, fy, fz, field0, field4, c_field0, c_field4 ); + VIntZ( q * 3, 24, isol, fx, fy, fz, field0, field4, q, qz ); } if ( bits & 512 ) { compNorm( q1 ); compNorm( q1z ); - VIntZ( q1 * 3, 27, isol, fx2, fy, fz, field1, field5, c_field1, c_field5 ); + VIntZ( q1 * 3, 27, isol, fx2, fy, fz, field1, field5, q1, q1z ); } @@ -351,8 +326,8 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) fz, field3, field7, - c_field3, - c_field7 + q1y, + q1yz ); } @@ -361,7 +336,7 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) compNorm( qy ); compNorm( qyz ); - VIntZ( qy * 3, 33, isol, fx, fy2, fz, field2, field6, c_field2, c_field6 ); + VIntZ( qy * 3, 33, isol, fx, fy2, fz, field2, field6, qy, qyz ); } @@ -570,7 +545,6 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) var sign = Math.sign( strength ); strength = Math.abs( strength ); var userDefineColor = ! ( colors === undefined || colors === null ); - console.log( ballx, bally, ballz ); var ballColor = new THREE.Color( ballx, bally, ballz ); if ( userDefineColor ) { @@ -651,10 +625,9 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) Math.sqrt( ( x - xs ) * ( x - xs ) + ( y - ys ) * ( y - ys ) + ( z - zs ) * ( z - zs ) ) / radius; const contrib = 1 - ratio * ratio * ratio * ( ratio * ( ratio * 6 - 15 ) + 10 ); - this.palette[ ( y_offset + x ) * 4 + 0 ] += ballColor.r * contrib; - this.palette[ ( y_offset + x ) * 4 + 1 ] += ballColor.g * contrib; - this.palette[ ( y_offset + x ) * 4 + 2 ] += ballColor.b * contrib; - this.palette[ ( y_offset + x ) * 4 + 3 ] += contrib; + this.palette[ ( y_offset + x ) * 3 + 0 ] += ballColor.r * contrib; + this.palette[ ( y_offset + x ) * 3 + 1 ] += ballColor.g * contrib; + this.palette[ ( y_offset + x ) * 3 + 2 ] += ballColor.b * contrib; } @@ -809,9 +782,9 @@ THREE.MarchingCubes = function ( resolution, material, enableUvs, enableColors ) this.normal_cache[ i * 3 ] = 0.0; this.field[ i ] = 0.0; - this.palette[ i * 4 ] = this.palette[ i * 4 + 1 ] = this.palette[ - i * 4 + 2 - ] = this.palette[ i * 4 + 3 ] = 0.0; + this.palette[ i * 3 ] = this.palette[ i * 3 + 1 ] = this.palette[ + i * 3 + 2 + ] = 0.0; }
false
Other
mrdoob
three.js
8b98b74076d961b755c1f46dcb168ccf61bc3291.json
Remove unneeded closure
editor/js/Sidebar.Geometry.TubeGeometry.js
@@ -27,17 +27,13 @@ Sidebar.Geometry.TubeGeometry = function ( editor, object ) { var pointsList = new UI.Div(); points.add( pointsList ); - ( function () { + var parameterPoints = parameters.path.points; + for ( var i = 0; i < parameterPoints.length; i ++ ) { - var points = parameters.path.points; - for ( var i = 0; i < points.length; i ++ ) { + var point = parameterPoints[ i ]; + pointsList.add( createPointRow( point.x, point.y, point.z ) ); - var point = points[ i ]; - pointsList.add( createPointRow( point.x, point.y, point.z ) ); - - } - - } )(); + } var addPointButton = new UI.Button( '+' ).onClick( function () {
false
Other
mrdoob
three.js
310491179af08eebbf245d0fd53a734fe13088eb.json
Remove unnecessary object.userData check
examples/js/exporters/GLTFExporter.js
@@ -336,7 +336,7 @@ THREE.GLTFExporter.prototype = { */ function serializeUserData( object, gltfProperty ) { - if ( ! object.userData || Object.keys( object.userData ).length === 0 ) { + if ( Object.keys( object.userData ).length === 0 ) { return;
false
Other
mrdoob
three.js
61a49191a8e3872fc6f5911301e5ae05f39e759f.json
Update BufferGeometry tets
test/unit/src/core/BufferGeometry.tests.js
@@ -809,6 +809,7 @@ export default QUnit.module( 'Core', () => { var index = new BufferAttribute( new Uint16Array( [ 0, 1, 2, 3 ] ), 1 ); var attribute1 = new BufferAttribute( new Uint16Array( [ 1, 3, 5, 7 ] ), 1 ); + attribute1.name = "attribute1"; var a = new BufferGeometry(); a.name = "JSONQUnit.test"; // a.parameters = { "placeholder": 0 }; @@ -817,7 +818,6 @@ export default QUnit.module( 'Core', () => { a.addGroup( 0, 1, 2 ); a.boundingSphere = new Sphere( new Vector3( x, y, z ), 0.5 ); var j = a.toJSON(); - var gold = { "metadata": { "version": 4.5, @@ -833,7 +833,8 @@ export default QUnit.module( 'Core', () => { "itemSize": 1, "type": "Uint16Array", "array": [ 1, 3, 5, 7 ], - "normalized": false + "normalized": false, + "name": "attribute1" } }, "index": { @@ -856,6 +857,22 @@ export default QUnit.module( 'Core', () => { assert.deepEqual( j, gold, "Generated JSON is as expected" ); + // add morphAttributes + a.morphAttributes.attribute1 = []; + a.morphAttributes.attribute1.push( attribute1.clone() ); + j = a.toJSON(); + gold.data.morphAttributes = { + "attribute1": [ { + "itemSize": 1, + "type": "Uint16Array", + "array": [ 1, 3, 5, 7 ], + "normalized": false, + "name": "attribute1" + } ] + }; + + assert.deepEqual( j, gold, "Generated JSON with morphAttributes is as expected" ); + } ); QUnit.test( "clone", ( assert ) => {
false
Other
mrdoob
three.js
d06ece07677cf9bded2fce17c363e142624ae7fc.json
Serialize name in BufferGeometry.toJSON()
src/core/BufferGeometry.js
@@ -1003,13 +1003,17 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy var array = Array.prototype.slice.call( attribute.array ); - data.data.attributes[ key ] = { + var attributeData = { itemSize: attribute.itemSize, type: attribute.array.constructor.name, array: array, normalized: attribute.normalized }; + if ( attribute.name !== '' ) attributeData.name = attribute.name; + + data.data.attributes[ key ] = attributeData; + } var morphAttributes = {};
true
Other
mrdoob
three.js
d06ece07677cf9bded2fce17c363e142624ae7fc.json
Serialize name in BufferGeometry.toJSON()
src/loaders/BufferGeometryLoader.js
@@ -51,7 +51,9 @@ Object.assign( BufferGeometryLoader.prototype, { var attribute = attributes[ key ]; var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); - geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); + var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + geometry.addAttribute( key, bufferAttribute ); }
true
Other
mrdoob
three.js
61b7e8c5af6d0151163fc762c7385682d153cc01.json
Add TypeScript definitions for GLTFExporter
examples/jsm/exporters/GLTFExporter.d.ts
@@ -0,0 +1,7 @@ +import { Object3D } from '../../../src/Three'; + +export class GLTFExporter { + constructor(); + + parse(input: Object3D, onCompleted: (gltf: object) => void, options: object): null; +}
false
Other
mrdoob
three.js
1dfd109aee9980547382b121b5e3499e5933ccbc.json
Use createFillQuadScene also in OutlinePass
examples/js/postprocessing/OutlinePass.js
@@ -101,12 +101,7 @@ THREE.OutlinePass = function ( resolution, scene, camera, selectedObjects ) { this.oldClearColor = new THREE.Color(); this.oldClearAlpha = 1; - this.camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); - this.scene = new THREE.Scene(); - - this.quad = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), null ); - this.quad.frustumCulled = false; // Avoid getting clipped - this.scene.add( this.quad ); + this.fillQuad = THREE.Pass.createFillQuadScene( null ); this.tempPulseColor1 = new THREE.Color(); this.tempPulseColor2 = new THREE.Color(); @@ -302,11 +297,11 @@ THREE.OutlinePass.prototype = Object.assign( Object.create( THREE.Pass.prototype this.renderScene.background = currentBackground; // 2. Downsample to Half resolution - this.quad.material = this.materialCopy; + this.fillQuad.quad.material = this.materialCopy; this.copyUniforms[ "tDiffuse" ].value = this.renderTargetMaskBuffer.texture; renderer.setRenderTarget( this.renderTargetMaskDownSampleBuffer ); renderer.clear(); - renderer.render( this.scene, this.camera ); + renderer.render( this.fillQuad.quad, this.fillQuad.camera ); this.tempPulseColor1.copy( this.visibleEdgeColor ); this.tempPulseColor2.copy( this.hiddenEdgeColor ); @@ -320,44 +315,44 @@ THREE.OutlinePass.prototype = Object.assign( Object.create( THREE.Pass.prototype } // 3. Apply Edge Detection Pass - this.quad.material = this.edgeDetectionMaterial; + this.fillQuad.quad.material = this.edgeDetectionMaterial; this.edgeDetectionMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskDownSampleBuffer.texture; this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height ); this.edgeDetectionMaterial.uniforms[ "visibleEdgeColor" ].value = this.tempPulseColor1; this.edgeDetectionMaterial.uniforms[ "hiddenEdgeColor" ].value = this.tempPulseColor2; renderer.setRenderTarget( this.renderTargetEdgeBuffer1 ); renderer.clear(); - renderer.render( this.scene, this.camera ); + renderer.render( this.fillQuad.quad, this.fillQuad.camera ); // 4. Apply Blur on Half res - this.quad.material = this.separableBlurMaterial1; + this.fillQuad.quad.material = this.separableBlurMaterial1; this.separableBlurMaterial1.uniforms[ "colorTexture" ].value = this.renderTargetEdgeBuffer1.texture; this.separableBlurMaterial1.uniforms[ "direction" ].value = THREE.OutlinePass.BlurDirectionX; this.separableBlurMaterial1.uniforms[ "kernelRadius" ].value = this.edgeThickness; renderer.setRenderTarget( this.renderTargetBlurBuffer1 ); renderer.clear(); - renderer.render( this.scene, this.camera ); + renderer.render( this.fillQuad.quad, this.fillQuad.camera ); this.separableBlurMaterial1.uniforms[ "colorTexture" ].value = this.renderTargetBlurBuffer1.texture; this.separableBlurMaterial1.uniforms[ "direction" ].value = THREE.OutlinePass.BlurDirectionY; renderer.setRenderTarget( this.renderTargetEdgeBuffer1 ); renderer.clear(); - renderer.render( this.scene, this.camera ); + renderer.render( this.fillQuad.quad, this.fillQuad.camera ); // Apply Blur on quarter res - this.quad.material = this.separableBlurMaterial2; + this.fillQuad.quad.material = this.separableBlurMaterial2; this.separableBlurMaterial2.uniforms[ "colorTexture" ].value = this.renderTargetEdgeBuffer1.texture; this.separableBlurMaterial2.uniforms[ "direction" ].value = THREE.OutlinePass.BlurDirectionX; renderer.setRenderTarget( this.renderTargetBlurBuffer2 ); renderer.clear(); - renderer.render( this.scene, this.camera ); + renderer.render( this.fillQuad.quad, this.fillQuad.camera ); this.separableBlurMaterial2.uniforms[ "colorTexture" ].value = this.renderTargetBlurBuffer2.texture; this.separableBlurMaterial2.uniforms[ "direction" ].value = THREE.OutlinePass.BlurDirectionY; renderer.setRenderTarget( this.renderTargetEdgeBuffer2 ); renderer.clear(); - renderer.render( this.scene, this.camera ); + renderer.render( this.fillQuad.quad, this.fillQuad.camera ); // Blend it additively over the input texture - this.quad.material = this.overlayMaterial; + this.fillQuad.quad.material = this.overlayMaterial; this.overlayMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskBuffer.texture; this.overlayMaterial.uniforms[ "edgeTexture1" ].value = this.renderTargetEdgeBuffer1.texture; this.overlayMaterial.uniforms[ "edgeTexture2" ].value = this.renderTargetEdgeBuffer2.texture; @@ -370,7 +365,7 @@ THREE.OutlinePass.prototype = Object.assign( Object.create( THREE.Pass.prototype if ( maskActive ) renderer.context.enable( renderer.context.STENCIL_TEST ); renderer.setRenderTarget( readBuffer ); - renderer.render( this.scene, this.camera ); + renderer.render( this.fillQuad.quad, this.fillQuad.camera ); renderer.setClearColor( this.oldClearColor, this.oldClearAlpha ); renderer.autoClear = oldAutoClear; @@ -379,10 +374,10 @@ THREE.OutlinePass.prototype = Object.assign( Object.create( THREE.Pass.prototype if ( this.renderToScreen ) { - this.quad.material = this.materialCopy; + this.fillQuad.quad.material = this.materialCopy; this.copyUniforms[ "tDiffuse" ].value = readBuffer.texture; renderer.setRenderTarget( null ); - renderer.render( this.scene, this.camera ); + renderer.render( this.fillQuad.quad, this.fillQuad.camera ); }
false
Other
mrdoob
three.js
d9f860366c0b1f81cf1171b1a0a0a370bd1d8771.json
Update GLTFExporter to jsm
examples/jsm/exporters/GLTFExporter.js
@@ -0,0 +1,2229 @@ +/** + * @author fernandojsg / http://fernandojsg.com + * @author Don McCurdy / https://www.donmccurdy.com + * @author Takahiro / https://github.com/takahirox + */ + +import { + NearestFilter, + NearestMipMapNearestFilter, + NearestMipMapLinearFilter, + LinearFilter, + LinearMipMapNearestFilter, + LinearMipMapLinearFilter, + ClampToEdgeWrapping, + RepeatWrapping, + MirroredRepeatWrapping, + Scene, + BufferAttribute, + BufferGeometry, + TriangleFanDrawMode, + TriangleStripDrawMode, + RGBAFormat, + DoubleSide, + PropertyBinding, + InterpolateDiscrete, + InterpolateLinear, + Vector3, +} from "../../../build/three.module.js"; + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ +var WEBGL_CONSTANTS = { + POINTS: 0x0000, + LINES: 0x0001, + LINE_LOOP: 0x0002, + LINE_STRIP: 0x0003, + TRIANGLES: 0x0004, + TRIANGLE_STRIP: 0x0005, + TRIANGLE_FAN: 0x0006, + + UNSIGNED_BYTE: 0x1401, + UNSIGNED_SHORT: 0x1403, + FLOAT: 0x1406, + UNSIGNED_INT: 0x1405, + ARRAY_BUFFER: 0x8892, + ELEMENT_ARRAY_BUFFER: 0x8893, + + NEAREST: 0x2600, + LINEAR: 0x2601, + NEAREST_MIPMAP_NEAREST: 0x2700, + LINEAR_MIPMAP_NEAREST: 0x2701, + NEAREST_MIPMAP_LINEAR: 0x2702, + LINEAR_MIPMAP_LINEAR: 0x2703, + + CLAMP_TO_EDGE: 33071, + MIRRORED_REPEAT: 33648, + REPEAT: 10497 +}; + +var THREE_TO_WEBGL = {}; + +THREE_TO_WEBGL[ NearestFilter ] = WEBGL_CONSTANTS.NEAREST; +THREE_TO_WEBGL[ NearestMipMapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST; +THREE_TO_WEBGL[ NearestMipMapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR; +THREE_TO_WEBGL[ LinearFilter ] = WEBGL_CONSTANTS.LINEAR; +THREE_TO_WEBGL[ LinearMipMapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST; +THREE_TO_WEBGL[ LinearMipMapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR; + +THREE_TO_WEBGL[ ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE; +THREE_TO_WEBGL[ RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT; +THREE_TO_WEBGL[ MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT; + +var PATH_PROPERTIES = { + scale: 'scale', + position: 'translation', + quaternion: 'rotation', + morphTargetInfluences: 'weights' +}; + +//------------------------------------------------------------------------------ +// GLTF Exporter +//------------------------------------------------------------------------------ +var GLTFExporter = ( function () { + + function GLTFExporter() { + } + + GLTFExporter.prototype = { + + constructor: GLTFExporter, + /** + * Parse scenes and generate GLTF output + * @param {Scene or [Scenes]} input Scene or Array of Scenes + * @param {Function} onDone Callback on completed + * @param {Object} options options + */ + parse: function ( input, onDone, options ) { + + var DEFAULT_OPTIONS = { + binary: false, + trs: false, + onlyVisible: true, + truncateDrawRange: true, + embedImages: true, + animations: [], + forceIndices: false, + forcePowerOfTwoTextures: false + }; + + options = Object.assign( {}, DEFAULT_OPTIONS, options ); + + if ( options.animations.length > 0 ) { + + // Only TRS properties, and not matrices, may be targeted by animation. + options.trs = true; + + } + + var outputJSON = { + + asset: { + + version: "2.0", + generator: "GLTFExporter" + + } + + }; + + var byteOffset = 0; + var buffers = []; + var pending = []; + var nodeMap = new Map(); + var skins = []; + var extensionsUsed = {}; + var cachedData = { + + meshes: new Map(), + attributes: new Map(), + attributesNormalized: new Map(), + materials: new Map(), + textures: new Map(), + images: new Map() + + }; + + var cachedCanvas; + + /** + * Compare two arrays + */ + /** + * Compare two arrays + * @param {Array} array1 Array 1 to compare + * @param {Array} array2 Array 2 to compare + * @return {Boolean} Returns true if both arrays are equal + */ + function equalArray( array1, array2 ) { + + return ( array1.length === array2.length ) && array1.every( function ( element, index ) { + + return element === array2[ index ]; + + } ); + + } + + /** + * Converts a string to an ArrayBuffer. + * @param {string} text + * @return {ArrayBuffer} + */ + function stringToArrayBuffer( text ) { + + if ( window.TextEncoder !== undefined ) { + + return new TextEncoder().encode( text ).buffer; + + } + + var array = new Uint8Array( new ArrayBuffer( text.length ) ); + + for ( var i = 0, il = text.length; i < il; i ++ ) { + + var value = text.charCodeAt( i ); + + // Replacing multi-byte character with space(0x20). + array[ i ] = value > 0xFF ? 0x20 : value; + + } + + return array.buffer; + + } + + /** + * Get the min and max vectors from the given attribute + * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count + * @param {Integer} start + * @param {Integer} count + * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components) + */ + function getMinMax( attribute, start, count ) { + + var output = { + + min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ), + max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY ) + + }; + + for ( var i = start; i < start + count; i ++ ) { + + for ( var a = 0; a < attribute.itemSize; a ++ ) { + + var value = attribute.array[ i * attribute.itemSize + a ]; + output.min[ a ] = Math.min( output.min[ a ], value ); + output.max[ a ] = Math.max( output.max[ a ], value ); + + } + + } + + return output; + + } + + /** + * Checks if image size is POT. + * + * @param {Image} image The image to be checked. + * @returns {Boolean} Returns true if image size is POT. + * + */ + function isPowerOfTwo( image ) { + + return Math.isPowerOfTwo( image.width ) && Math.isPowerOfTwo( image.height ); + + } + + /** + * Checks if normal attribute values are normalized. + * + * @param {BufferAttribute} normal + * @returns {Boolean} + * + */ + function isNormalizedNormalAttribute( normal ) { + + if ( cachedData.attributesNormalized.has( normal ) ) { + + return false; + + } + + var v = new Vector3(); + + for ( var i = 0, il = normal.count; i < il; i ++ ) { + + // 0.0005 is from glTF-validator + if ( Math.abs( v.fromArray( normal.array, i * 3 ).length() - 1.0 ) > 0.0005 ) return false; + + } + + return true; + + } + + /** + * Creates normalized normal buffer attribute. + * + * @param {BufferAttribute} normal + * @returns {BufferAttribute} + * + */ + function createNormalizedNormalAttribute( normal ) { + + if ( cachedData.attributesNormalized.has( normal ) ) { + + return cachedData.attributesNormalized.get( normal ); + + } + + var attribute = normal.clone(); + + var v = new Vector3(); + + for ( var i = 0, il = attribute.count; i < il; i ++ ) { + + v.fromArray( attribute.array, i * 3 ); + + if ( v.x === 0 && v.y === 0 && v.z === 0 ) { + + // if values can't be normalized set (1, 0, 0) + v.setX( 1.0 ); + + } else { + + v.normalize(); + + } + + v.toArray( attribute.array, i * 3 ); + + } + + cachedData.attributesNormalized.set( normal, attribute ); + + return attribute; + + } + + /** + * Get the required size + padding for a buffer, rounded to the next 4-byte boundary. + * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment + * + * @param {Integer} bufferSize The size the original buffer. + * @returns {Integer} new buffer size with required padding. + * + */ + function getPaddedBufferSize( bufferSize ) { + + return Math.ceil( bufferSize / 4 ) * 4; + + } + + /** + * Returns a buffer aligned to 4-byte boundary. + * + * @param {ArrayBuffer} arrayBuffer Buffer to pad + * @param {Integer} paddingByte (Optional) + * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer + */ + function getPaddedArrayBuffer( arrayBuffer, paddingByte ) { + + paddingByte = paddingByte || 0; + + var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength ); + + if ( paddedLength !== arrayBuffer.byteLength ) { + + var array = new Uint8Array( paddedLength ); + array.set( new Uint8Array( arrayBuffer ) ); + + if ( paddingByte !== 0 ) { + + for ( var i = arrayBuffer.byteLength; i < paddedLength; i ++ ) { + + array[ i ] = paddingByte; + + } + + } + + return array.buffer; + + } + + return arrayBuffer; + + } + + /** + * Serializes a userData. + * + * @param {Object3D|Material} object + * @returns {Object} + */ + function serializeUserData( object ) { + + try { + + return JSON.parse( JSON.stringify( object.userData ) ); + + } catch ( error ) { + + console.warn( 'GLTFExporter: userData of \'' + object.name + '\' ' + + 'won\'t be serialized because of JSON.stringify error - ' + error.message ); + + return {}; + + } + + } + + /** + * Applies a texture transform, if present, to the map definition. Requires + * the KHR_texture_transform extension. + */ + function applyTextureTransform( mapDef, texture ) { + + var didTransform = false; + var transformDef = {}; + + if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) { + + transformDef.offset = texture.offset.toArray(); + didTransform = true; + + } + + if ( texture.rotation !== 0 ) { + + transformDef.rotation = texture.rotation; + didTransform = true; + + } + + if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) { + + transformDef.scale = texture.repeat.toArray(); + didTransform = true; + + } + + if ( didTransform ) { + + mapDef.extensions = mapDef.extensions || {}; + mapDef.extensions[ 'KHR_texture_transform' ] = transformDef; + extensionsUsed[ 'KHR_texture_transform' ] = true; + + } + + } + + /** + * Process a buffer to append to the default one. + * @param {ArrayBuffer} buffer + * @return {Integer} + */ + function processBuffer( buffer ) { + + if ( ! outputJSON.buffers ) { + + outputJSON.buffers = [ { byteLength: 0 } ]; + + } + + // All buffers are merged before export. + buffers.push( buffer ); + + return 0; + + } + + /** + * Process and generate a BufferView + * @param {BufferAttribute} attribute + * @param {number} componentType + * @param {number} start + * @param {number} count + * @param {number} target (Optional) Target usage of the BufferView + * @return {Object} + */ + function processBufferView( attribute, componentType, start, count, target ) { + + if ( ! outputJSON.bufferViews ) { + + outputJSON.bufferViews = []; + + } + + // Create a new dataview and dump the attribute's array into it + + var componentSize; + + if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) { + + componentSize = 1; + + } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) { + + componentSize = 2; + + } else { + + componentSize = 4; + + } + + var byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize ); + var dataView = new DataView( new ArrayBuffer( byteLength ) ); + var offset = 0; + + for ( var i = start; i < start + count; i ++ ) { + + for ( var a = 0; a < attribute.itemSize; a ++ ) { + + // @TODO Fails on InterleavedBufferAttribute, and could probably be + // optimized for normal BufferAttribute. + var value = attribute.array[ i * attribute.itemSize + a ]; + + if ( componentType === WEBGL_CONSTANTS.FLOAT ) { + + dataView.setFloat32( offset, value, true ); + + } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) { + + dataView.setUint32( offset, value, true ); + + } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) { + + dataView.setUint16( offset, value, true ); + + } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) { + + dataView.setUint8( offset, value ); + + } + + offset += componentSize; + + } + + } + + var gltfBufferView = { + + buffer: processBuffer( dataView.buffer ), + byteOffset: byteOffset, + byteLength: byteLength + + }; + + if ( target !== undefined ) gltfBufferView.target = target; + + if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) { + + // Only define byteStride for vertex attributes. + gltfBufferView.byteStride = attribute.itemSize * componentSize; + + } + + byteOffset += byteLength; + + outputJSON.bufferViews.push( gltfBufferView ); + + // @TODO Merge bufferViews where possible. + var output = { + + id: outputJSON.bufferViews.length - 1, + byteLength: 0 + + }; + + return output; + + } + + /** + * Process and generate a BufferView from an image Blob. + * @param {Blob} blob + * @return {Promise<Integer>} + */ + function processBufferViewImage( blob ) { + + if ( ! outputJSON.bufferViews ) { + + outputJSON.bufferViews = []; + + } + + return new Promise( function ( resolve ) { + + var reader = new window.FileReader(); + reader.readAsArrayBuffer( blob ); + reader.onloadend = function () { + + var buffer = getPaddedArrayBuffer( reader.result ); + + var bufferView = { + buffer: processBuffer( buffer ), + byteOffset: byteOffset, + byteLength: buffer.byteLength + }; + + byteOffset += buffer.byteLength; + + outputJSON.bufferViews.push( bufferView ); + + resolve( outputJSON.bufferViews.length - 1 ); + + }; + + } ); + + } + + /** + * Process attribute to generate an accessor + * @param {BufferAttribute} attribute Attribute to process + * @param {BufferGeometry} geometry (Optional) Geometry used for truncated draw range + * @param {Integer} start (Optional) + * @param {Integer} count (Optional) + * @return {Integer} Index of the processed accessor on the "accessors" array + */ + function processAccessor( attribute, geometry, start, count ) { + + var types = { + + 1: 'SCALAR', + 2: 'VEC2', + 3: 'VEC3', + 4: 'VEC4', + 16: 'MAT4' + + }; + + var componentType; + + // Detect the component type of the attribute array (float, uint or ushort) + if ( attribute.array.constructor === Float32Array ) { + + componentType = WEBGL_CONSTANTS.FLOAT; + + } else if ( attribute.array.constructor === Uint32Array ) { + + componentType = WEBGL_CONSTANTS.UNSIGNED_INT; + + } else if ( attribute.array.constructor === Uint16Array ) { + + componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT; + + } else if ( attribute.array.constructor === Uint8Array ) { + + componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE; + + } else { + + throw new Error( 'GLTFExporter: Unsupported bufferAttribute component type.' ); + + } + + if ( start === undefined ) start = 0; + if ( count === undefined ) count = attribute.count; + + // @TODO Indexed buffer geometry with drawRange not supported yet + if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) { + + var end = start + count; + var end2 = geometry.drawRange.count === Infinity + ? attribute.count + : geometry.drawRange.start + geometry.drawRange.count; + + start = Math.max( start, geometry.drawRange.start ); + count = Math.min( end, end2 ) - start; + + if ( count < 0 ) count = 0; + + } + + // Skip creating an accessor if the attribute doesn't have data to export + if ( count === 0 ) { + + return null; + + } + + var minMax = getMinMax( attribute, start, count ); + + var bufferViewTarget; + + // If geometry isn't provided, don't infer the target usage of the bufferView. For + // animation samplers, target must not be set. + if ( geometry !== undefined ) { + + bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER; + + } + + var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget ); + + var gltfAccessor = { + + bufferView: bufferView.id, + byteOffset: bufferView.byteOffset, + componentType: componentType, + count: count, + max: minMax.max, + min: minMax.min, + type: types[ attribute.itemSize ] + + }; + + if ( ! outputJSON.accessors ) { + + outputJSON.accessors = []; + + } + + outputJSON.accessors.push( gltfAccessor ); + + return outputJSON.accessors.length - 1; + + } + + /** + * Process image + * @param {Image} image to process + * @param {Integer} format of the image (e.g. RGBFormat, RGBAFormat etc) + * @param {Boolean} flipY before writing out the image + * @return {Integer} Index of the processed texture in the "images" array + */ + function processImage( image, format, flipY ) { + + if ( ! cachedData.images.has( image ) ) { + + cachedData.images.set( image, {} ); + + } + + var cachedImages = cachedData.images.get( image ); + var mimeType = format === RGBAFormat ? 'image/png' : 'image/jpeg'; + var key = mimeType + ":flipY/" + flipY.toString(); + + if ( cachedImages[ key ] !== undefined ) { + + return cachedImages[ key ]; + + } + + if ( ! outputJSON.images ) { + + outputJSON.images = []; + + } + + var gltfImage = { mimeType: mimeType }; + + if ( options.embedImages ) { + + var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' ); + + canvas.width = image.width; + canvas.height = image.height; + + if ( options.forcePowerOfTwoTextures && ! isPowerOfTwo( image ) ) { + + console.warn( 'GLTFExporter: Resized non-power-of-two image.', image ); + + canvas.width = Math.floorPowerOfTwo( canvas.width ); + canvas.height = Math.floorPowerOfTwo( canvas.height ); + + } + + var ctx = canvas.getContext( '2d' ); + + if ( flipY === true ) { + + ctx.translate( 0, canvas.height ); + ctx.scale( 1, - 1 ); + + } + + ctx.drawImage( image, 0, 0, canvas.width, canvas.height ); + + if ( options.binary === true ) { + + pending.push( new Promise( function ( resolve ) { + + canvas.toBlob( function ( blob ) { + + processBufferViewImage( blob ).then( function ( bufferViewIndex ) { + + gltfImage.bufferView = bufferViewIndex; + + resolve(); + + } ); + + }, mimeType ); + + } ) ); + + } else { + + gltfImage.uri = canvas.toDataURL( mimeType ); + + } + + } else { + + gltfImage.uri = image.src; + + } + + outputJSON.images.push( gltfImage ); + + var index = outputJSON.images.length - 1; + cachedImages[ key ] = index; + + return index; + + } + + /** + * Process sampler + * @param {Texture} map Texture to process + * @return {Integer} Index of the processed texture in the "samplers" array + */ + function processSampler( map ) { + + if ( ! outputJSON.samplers ) { + + outputJSON.samplers = []; + + } + + var gltfSampler = { + + magFilter: THREE_TO_WEBGL[ map.magFilter ], + minFilter: THREE_TO_WEBGL[ map.minFilter ], + wrapS: THREE_TO_WEBGL[ map.wrapS ], + wrapT: THREE_TO_WEBGL[ map.wrapT ] + + }; + + outputJSON.samplers.push( gltfSampler ); + + return outputJSON.samplers.length - 1; + + } + + /** + * Process texture + * @param {Texture} map Map to process + * @return {Integer} Index of the processed texture in the "textures" array + */ + function processTexture( map ) { + + if ( cachedData.textures.has( map ) ) { + + return cachedData.textures.get( map ); + + } + + if ( ! outputJSON.textures ) { + + outputJSON.textures = []; + + } + + var gltfTexture = { + + sampler: processSampler( map ), + source: processImage( map.image, map.format, map.flipY ) + + }; + + outputJSON.textures.push( gltfTexture ); + + var index = outputJSON.textures.length - 1; + cachedData.textures.set( map, index ); + + return index; + + } + + /** + * Process material + * @param {Material} material Material to process + * @return {Integer} Index of the processed material in the "materials" array + */ + function processMaterial( material ) { + + if ( cachedData.materials.has( material ) ) { + + return cachedData.materials.get( material ); + + } + + if ( ! outputJSON.materials ) { + + outputJSON.materials = []; + + } + + if ( material.isShaderMaterial ) { + + console.warn( 'GLTFExporter: ShaderMaterial not supported.' ); + return null; + + } + + // @QUESTION Should we avoid including any attribute that has the default value? + var gltfMaterial = { + + pbrMetallicRoughness: {} + + }; + + if ( material.isMeshBasicMaterial ) { + + gltfMaterial.extensions = { KHR_materials_unlit: {} }; + + extensionsUsed[ 'KHR_materials_unlit' ] = true; + + } else if ( ! material.isMeshStandardMaterial ) { + + console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' ); + + } + + // pbrMetallicRoughness.baseColorFactor + var color = material.color.toArray().concat( [ material.opacity ] ); + + if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) { + + gltfMaterial.pbrMetallicRoughness.baseColorFactor = color; + + } + + if ( material.isMeshStandardMaterial ) { + + gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness; + gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness; + + } else if ( material.isMeshBasicMaterial ) { + + gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.0; + gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.9; + + } else { + + gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5; + gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5; + + } + + // pbrMetallicRoughness.metallicRoughnessTexture + if ( material.metalnessMap || material.roughnessMap ) { + + if ( material.metalnessMap === material.roughnessMap ) { + + var metalRoughMapDef = { index: processTexture( material.metalnessMap ) }; + applyTextureTransform( metalRoughMapDef, material.metalnessMap ); + gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef; + + } else { + + console.warn( 'GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' ); + + } + + } + + // pbrMetallicRoughness.baseColorTexture + if ( material.map ) { + + var baseColorMapDef = { index: processTexture( material.map ) }; + applyTextureTransform( baseColorMapDef, material.map ); + gltfMaterial.pbrMetallicRoughness.baseColorTexture = baseColorMapDef; + + } + + if ( material.isMeshBasicMaterial || + material.isLineBasicMaterial || + material.isPointsMaterial ) { + + } else { + + // emissiveFactor + var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray(); + + if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) { + + gltfMaterial.emissiveFactor = emissive; + + } + + // emissiveTexture + if ( material.emissiveMap ) { + + var emissiveMapDef = { index: processTexture( material.emissiveMap ) }; + applyTextureTransform( emissiveMapDef, material.emissiveMap ); + gltfMaterial.emissiveTexture = emissiveMapDef; + + } + + } + + // normalTexture + if ( material.normalMap ) { + + var normalMapDef = { index: processTexture( material.normalMap ) }; + + if ( material.normalScale.x !== - 1 ) { + + if ( material.normalScale.x !== material.normalScale.y ) { + + console.warn( 'GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' ); + + } + + normalMapDef.scale = material.normalScale.x; + + } + + applyTextureTransform( normalMapDef, material.normalMap ); + + gltfMaterial.normalTexture = normalMapDef; + + } + + // occlusionTexture + if ( material.aoMap ) { + + var occlusionMapDef = { + index: processTexture( material.aoMap ), + texCoord: 1 + }; + + if ( material.aoMapIntensity !== 1.0 ) { + + occlusionMapDef.strength = material.aoMapIntensity; + + } + + applyTextureTransform( occlusionMapDef, material.aoMap ); + + gltfMaterial.occlusionTexture = occlusionMapDef; + + } + + // alphaMode + if ( material.transparent || material.alphaTest > 0.0 ) { + + gltfMaterial.alphaMode = material.opacity < 1.0 ? 'BLEND' : 'MASK'; + + // Write alphaCutoff if it's non-zero and different from the default (0.5). + if ( material.alphaTest > 0.0 && material.alphaTest !== 0.5 ) { + + gltfMaterial.alphaCutoff = material.alphaTest; + + } + + } + + // doubleSided + if ( material.side === DoubleSide ) { + + gltfMaterial.doubleSided = true; + + } + + if ( material.name !== '' ) { + + gltfMaterial.name = material.name; + + } + + if ( Object.keys( material.userData ).length > 0 ) { + + gltfMaterial.extras = serializeUserData( material ); + + } + + outputJSON.materials.push( gltfMaterial ); + + var index = outputJSON.materials.length - 1; + cachedData.materials.set( material, index ); + + return index; + + } + + /** + * Process mesh + * @param {Mesh} mesh Mesh to process + * @return {Integer} Index of the processed mesh in the "meshes" array + */ + function processMesh( mesh ) { + + var cacheKey = mesh.geometry.uuid + ':' + mesh.material.uuid; + if ( cachedData.meshes.has( cacheKey ) ) { + + return cachedData.meshes.get( cacheKey ); + + } + + var geometry = mesh.geometry; + + var mode; + + // Use the correct mode + if ( mesh.isLineSegments ) { + + mode = WEBGL_CONSTANTS.LINES; + + } else if ( mesh.isLineLoop ) { + + mode = WEBGL_CONSTANTS.LINE_LOOP; + + } else if ( mesh.isLine ) { + + mode = WEBGL_CONSTANTS.LINE_STRIP; + + } else if ( mesh.isPoints ) { + + mode = WEBGL_CONSTANTS.POINTS; + + } else { + + if ( ! geometry.isBufferGeometry ) { + + console.warn( 'GLTFExporter: Exporting Geometry will increase file size. Use BufferGeometry instead.' ); + + var geometryTemp = new BufferGeometry(); + geometryTemp.fromGeometry( geometry ); + geometry = geometryTemp; + + } + + if ( mesh.drawMode === TriangleFanDrawMode ) { + + console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' ); + mode = WEBGL_CONSTANTS.TRIANGLE_FAN; + + } else if ( mesh.drawMode === TriangleStripDrawMode ) { + + mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP; + + } else { + + mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES; + + } + + } + + var gltfMesh = {}; + + var attributes = {}; + var primitives = []; + var targets = []; + + // Conversion between attributes names in threejs and gltf spec + var nameConversion = { + + uv: 'TEXCOORD_0', + uv2: 'TEXCOORD_1', + color: 'COLOR_0', + skinWeight: 'WEIGHTS_0', + skinIndex: 'JOINTS_0' + + }; + + var originalNormal = geometry.getAttribute( 'normal' ); + + if ( originalNormal !== undefined && ! isNormalizedNormalAttribute( originalNormal ) ) { + + console.warn( 'GLTFExporter: Creating normalized normal attribute from the non-normalized one.' ); + + geometry.addAttribute( 'normal', createNormalizedNormalAttribute( originalNormal ) ); + + } + + // @QUESTION Detect if .vertexColors = VertexColors? + // For every attribute create an accessor + var modifiedAttribute = null; + for ( var attributeName in geometry.attributes ) { + + var attribute = geometry.attributes[ attributeName ]; + attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase(); + if (attributeName == 'PRIMITIVEID') + continue; + + if ( cachedData.attributes.has( attribute ) ) { + + attributes[ attributeName ] = cachedData.attributes.get( attribute ); + continue; + + } + + // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT. + modifiedAttribute = null; + var array = attribute.array; + if ( attributeName === 'JOINTS_0' && + ! ( array instanceof Uint16Array ) && + ! ( array instanceof Uint8Array ) ) { + + console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' ); + modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized ); + + } + + if ( attributeName.substr( 0, 5 ) !== 'MORPH' ) { + + var accessor = processAccessor( modifiedAttribute || attribute, geometry ); + if ( accessor !== null ) { + + attributes[ attributeName ] = accessor; + cachedData.attributes.set( attribute, accessor ); + + } + + } + + } + + if ( originalNormal !== undefined ) geometry.addAttribute( 'normal', originalNormal ); + + // Skip if no exportable attributes found + if ( Object.keys( attributes ).length === 0 ) { + + return null; + + } + + // Morph targets + if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) { + + var weights = []; + var targetNames = []; + var reverseDictionary = {}; + + if ( mesh.morphTargetDictionary !== undefined ) { + + for ( var key in mesh.morphTargetDictionary ) { + + reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key; + + } + + } + + for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) { + + var target = {}; + + var warned = false; + + for ( var attributeName in geometry.morphAttributes ) { + + // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT. + // Three.js doesn't support TANGENT yet. + + if ( attributeName !== 'position' && attributeName !== 'normal' ) { + + if ( ! warned ) { + + console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' ); + warned = true; + + } + + continue; + + } + + var attribute = geometry.morphAttributes[ attributeName ][ i ]; + var gltfAttributeName = attributeName.toUpperCase(); + + // Three.js morph attribute has absolute values while the one of glTF has relative values. + // + // glTF 2.0 Specification: + // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets + + var baseAttribute = geometry.attributes[ attributeName ]; + + if ( cachedData.attributes.has( attribute ) ) { + + target[ gltfAttributeName ] = cachedData.attributes.get( attribute ); + continue; + + } + + // Clones attribute not to override + var relativeAttribute = attribute.clone(); + + for ( var j = 0, jl = attribute.count; j < jl; j ++ ) { + + relativeAttribute.setXYZ( + j, + attribute.getX( j ) - baseAttribute.getX( j ), + attribute.getY( j ) - baseAttribute.getY( j ), + attribute.getZ( j ) - baseAttribute.getZ( j ) + ); + + } + + target[ gltfAttributeName ] = processAccessor( relativeAttribute, geometry ); + cachedData.attributes.set( baseAttribute, target[ gltfAttributeName ] ); + + } + + targets.push( target ); + + weights.push( mesh.morphTargetInfluences[ i ] ); + if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] ); + + } + + gltfMesh.weights = weights; + + if ( targetNames.length > 0 ) { + + gltfMesh.extras = {}; + gltfMesh.extras.targetNames = targetNames; + + } + + } + + var extras = ( Object.keys( geometry.userData ).length > 0 ) ? serializeUserData( geometry ) : undefined; + + var forceIndices = options.forceIndices; + var isMultiMaterial = Array.isArray( mesh.material ); + + if ( isMultiMaterial && geometry.groups.length === 0 ) return null; + + if ( ! forceIndices && geometry.index === null && isMultiMaterial ) { + + // temporal workaround. + console.warn( 'GLTFExporter: Creating index for non-indexed multi-material mesh.' ); + forceIndices = true; + + } + + var didForceIndices = false; + + if ( geometry.index === null && forceIndices ) { + + var indices = []; + + for ( var i = 0, il = geometry.attributes.position.count; i < il; i ++ ) { + + indices[ i ] = i; + + } + + geometry.setIndex( indices ); + + didForceIndices = true; + + } + + var materials = isMultiMaterial ? mesh.material : [ mesh.material ]; + var groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ]; + + for ( var i = 0, il = groups.length; i < il; i ++ ) { + + var primitive = { + mode: mode, + attributes: attributes, + }; + + if ( extras ) primitive.extras = extras; + + if ( targets.length > 0 ) primitive.targets = targets; + + if ( geometry.index !== null ) { + + if ( cachedData.attributes.has( geometry.index ) ) { + + primitive.indices = cachedData.attributes.get( geometry.index ); + } else { + + primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count ); + cachedData.attributes.set( geometry.index, primitive.indices ); + } + if (primitive.indices === null) + delete primitive.indices + } + + var material = processMaterial( materials[ groups[ i ].materialIndex ] ); + + if ( material !== null ) { + + primitive.material = material; + + } + + primitives.push( primitive ); + + } + + if ( didForceIndices ) { + + geometry.setIndex( null ); + + } + + gltfMesh.primitives = primitives; + + if ( ! outputJSON.meshes ) { + + outputJSON.meshes = []; + + } + + outputJSON.meshes.push( gltfMesh ); + + var index = outputJSON.meshes.length - 1; + cachedData.meshes.set( cacheKey, index ); + + return index; + + } + + /** + * Process camera + * @param {Camera} camera Camera to process + * @return {Integer} Index of the processed mesh in the "camera" array + */ + function processCamera( camera ) { + + if ( ! outputJSON.cameras ) { + + outputJSON.cameras = []; + + } + + var isOrtho = camera.isOrthographicCamera; + + var gltfCamera = { + + type: isOrtho ? 'orthographic' : 'perspective' + + }; + + if ( isOrtho ) { + + gltfCamera.orthographic = { + + xmag: camera.right * 2, + ymag: camera.top * 2, + zfar: camera.far <= 0 ? 0.001 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + + }; + + } else { + + gltfCamera.perspective = { + + aspectRatio: camera.aspect, + yfov: Math.degToRad( camera.fov ), + zfar: camera.far <= 0 ? 0.001 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + + }; + + } + + if ( camera.name !== '' ) { + + gltfCamera.name = camera.type; + + } + + outputJSON.cameras.push( gltfCamera ); + + return outputJSON.cameras.length - 1; + + } + + /** + * Creates glTF animation entry from AnimationClip object. + * + * Status: + * - Only properties listed in PATH_PROPERTIES may be animated. + * + * @param {AnimationClip} clip + * @param {Object3D} root + * @return {number} + */ + function processAnimation( clip, root ) { + + if ( ! outputJSON.animations ) { + + outputJSON.animations = []; + + } + + clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root ); + + var tracks = clip.tracks; + var channels = []; + var samplers = []; + + for ( var i = 0; i < tracks.length; ++ i ) { + + var track = tracks[ i ]; + var trackBinding = PropertyBinding.parseTrackName( track.name ); + var trackNode = PropertyBinding.findNode( root, trackBinding.nodeName ); + var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ]; + + if ( trackBinding.objectName === 'bones' ) { + + if ( trackNode.isSkinnedMesh === true ) { + + trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex ); + + } else { + + trackNode = undefined; + + } + + } + + if ( ! trackNode || ! trackProperty ) { + + console.warn( 'GLTFExporter: Could not export animation track "%s".', track.name ); + return null; + + } + + var inputItemSize = 1; + var outputItemSize = track.values.length / track.times.length; + + if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) { + + outputItemSize /= trackNode.morphTargetInfluences.length; + + } + + var interpolation; + + // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE + + // Detecting glTF cubic spline interpolant by checking factory method's special property + // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return + // valid value from .getInterpolation(). + if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) { + + interpolation = 'CUBICSPLINE'; + + // itemSize of CUBICSPLINE keyframe is 9 + // (VEC3 * 3: inTangent, splineVertex, and outTangent) + // but needs to be stored as VEC3 so dividing by 3 here. + outputItemSize /= 3; + + } else if ( track.getInterpolation() === InterpolateDiscrete ) { + + interpolation = 'STEP'; + + } else { + + interpolation = 'LINEAR'; + + } + + samplers.push( { + + input: processAccessor( new BufferAttribute( track.times, inputItemSize ) ), + output: processAccessor( new BufferAttribute( track.values, outputItemSize ) ), + interpolation: interpolation + + } ); + + channels.push( { + + sampler: samplers.length - 1, + target: { + node: nodeMap.get( trackNode ), + path: trackProperty + } + + } ); + + } + + outputJSON.animations.push( { + + name: clip.name || 'clip_' + outputJSON.animations.length, + samplers: samplers, + channels: channels + + } ); + + return outputJSON.animations.length - 1; + + } + + function processSkin( object ) { + + var node = outputJSON.nodes[ nodeMap.get( object ) ]; + + var skeleton = object.skeleton; + var rootJoint = object.skeleton.bones[ 0 ]; + + if ( rootJoint === undefined ) return null; + + var joints = []; + var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 ); + + for ( var i = 0; i < skeleton.bones.length; ++ i ) { + + joints.push( nodeMap.get( skeleton.bones[ i ] ) ); + + skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 ); + + } + + if ( outputJSON.skins === undefined ) { + + outputJSON.skins = []; + + } + + outputJSON.skins.push( { + + inverseBindMatrices: processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ), + joints: joints, + skeleton: nodeMap.get( rootJoint ) + + } ); + + var skinIndex = node.skin = outputJSON.skins.length - 1; + + return skinIndex; + + } + + function processLight( light ) { + + var lightDef = {}; + + if ( light.name ) lightDef.name = light.name; + + lightDef.color = light.color.toArray(); + + lightDef.intensity = light.intensity; + + if ( light.isDirectionalLight ) { + + lightDef.type = 'directional'; + + } else if ( light.isPointLight ) { + + lightDef.type = 'point'; + if ( light.distance > 0 ) lightDef.range = light.distance; + + } else if ( light.isSpotLight ) { + + lightDef.type = 'spot'; + if ( light.distance > 0 ) lightDef.range = light.distance; + lightDef.spot = {}; + lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0; + lightDef.spot.outerConeAngle = light.angle; + + } + + if ( light.decay !== undefined && light.decay !== 2 ) { + + console.warn( 'GLTFExporter: Light decay may be lost. glTF is physically-based, ' + + 'and expects light.decay=2.' ); + + } + + if ( light.target + && ( light.target.parent !== light + || light.target.position.x !== 0 + || light.target.position.y !== 0 + || light.target.position.z !== - 1 ) ) { + + console.warn( 'GLTFExporter: Light direction may be lost. For best results, ' + + 'make light.target a child of the light with position 0,0,-1.' ); + + } + + var lights = outputJSON.extensions[ 'KHR_lights_punctual' ].lights; + lights.push( lightDef ); + return lights.length - 1; + + } + + /** + * Process Object3D node + * @param {Object3D} node Object3D to processNode + * @return {Integer} Index of the node in the nodes list + */ + function processNode( object ) { + + if ( ! outputJSON.nodes ) { + + outputJSON.nodes = []; + + } + + var gltfNode = {}; + + if ( options.trs ) { + + var rotation = object.quaternion.toArray(); + var position = object.position.toArray(); + var scale = object.scale.toArray(); + + if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) { + + gltfNode.rotation = rotation; + + } + + if ( ! equalArray( position, [ 0, 0, 0 ] ) ) { + + gltfNode.translation = position; + + } + + if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) { + + gltfNode.scale = scale; + + } + + } else { + + object.updateMatrix(); + if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) { + + gltfNode.matrix = object.matrix.elements; + + } + + } + + // We don't export empty strings name because it represents no-name in Three.js. + if ( object.name !== '' ) { + + gltfNode.name = String( object.name ); + + } + + if ( object.userData && Object.keys( object.userData ).length > 0 ) { + + gltfNode.extras = serializeUserData( object ); + + } + + if ( object.isMesh || object.isLine || object.isPoints ) { + + var mesh = processMesh( object ); + + if ( mesh !== null ) { + + gltfNode.mesh = mesh; + + } + + } else if ( object.isCamera ) { + + gltfNode.camera = processCamera( object ); + + } else if ( object.isDirectionalLight || object.isPointLight || object.isSpotLight ) { + + if ( ! extensionsUsed[ 'KHR_lights_punctual' ] ) { + + outputJSON.extensions = outputJSON.extensions || {}; + outputJSON.extensions[ 'KHR_lights_punctual' ] = { lights: [] }; + extensionsUsed[ 'KHR_lights_punctual' ] = true; + + } + + gltfNode.extensions = gltfNode.extensions || {}; + gltfNode.extensions[ 'KHR_lights_punctual' ] = { light: processLight( object ) }; + + } else if ( object.isLight ) { + + console.warn( `GLTFExporter: light ${object.name} of type ${object.constructor.name}: Only directional, point, and spot lights are supported.` ); + return null; + + } + + if ( object.isSkinnedMesh ) { + + skins.push( object ); + + } + + if ( object.children.length > 0 ) { + + var children = []; + + for ( var i = 0, l = object.children.length; i < l; i ++ ) { + + var child = object.children[ i ]; + + if ( child.visible || options.onlyVisible === false ) { + + var node = processNode( child ); + + if ( node !== null ) { + + children.push( node ); + + } + + } + + } + + if ( children.length > 0 ) { + + gltfNode.children = children; + + } + + + } + + outputJSON.nodes.push( gltfNode ); + + var nodeIndex = outputJSON.nodes.length - 1; + nodeMap.set( object, nodeIndex ); + + return nodeIndex; + + } + + /** + * Process Scene + * @param {Scene} node Scene to process + */ + function processScene( scene ) { + + if ( ! outputJSON.scenes ) { + + outputJSON.scenes = []; + outputJSON.scene = 0; + + } + + var gltfScene = { + + nodes: [] + + }; + + if ( scene.name !== '' ) { + + gltfScene.name = scene.name; + + } + + if ( scene.userData && Object.keys( scene.userData ).length > 0 ) { + + gltfScene.extras = serializeUserData( scene ); + + } + + outputJSON.scenes.push( gltfScene ); + + var nodes = []; + + for ( var i = 0, l = scene.children.length; i < l; i ++ ) { + + var child = scene.children[ i ]; + + if ( child.visible || options.onlyVisible === false ) { + + var node = processNode( child ); + + if ( node !== null ) { + + nodes.push( node ); + + } + + } + + } + + if ( nodes.length > 0 ) { + + gltfScene.nodes = nodes; + + } + + } + + /** + * Creates a Scene to hold a list of objects and parse it + * @param {Array} objects List of objects to process + */ + function processObjects( objects ) { + + var scene = new Scene(); + scene.name = 'AuxScene'; + + for ( var i = 0; i < objects.length; i ++ ) { + + // We push directly to children instead of calling `add` to prevent + // modify the .parent and break its original scene and hierarchy + scene.children.push( objects[ i ] ); + + } + + processScene( scene ); + + } + + function processInput( input ) { + + input = input instanceof Array ? input : [ input ]; + + var objectsWithoutScene = []; + + for ( var i = 0; i < input.length; i ++ ) { + + if ( input[ i ] instanceof Scene ) { + + processScene( input[ i ] ); + + } else { + + objectsWithoutScene.push( input[ i ] ); + + } + + } + + if ( objectsWithoutScene.length > 0 ) { + + processObjects( objectsWithoutScene ); + + } + + for ( var i = 0; i < skins.length; ++ i ) { + + processSkin( skins[ i ] ); + + } + + for ( var i = 0; i < options.animations.length; ++ i ) { + + processAnimation( options.animations[ i ], input[ 0 ] ); + + } + + } + + processInput( input ); + + Promise.all( pending ).then( function () { + + // Merge buffers. + var blob = new Blob( buffers, { type: 'application/octet-stream' } ); + + // Declare extensions. + var extensionsUsedList = Object.keys( extensionsUsed ); + if ( extensionsUsedList.length > 0 ) outputJSON.extensionsUsed = extensionsUsedList; + + if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) { + + // Update bytelength of the single buffer. + outputJSON.buffers[ 0 ].byteLength = blob.size; + + var reader = new window.FileReader(); + + if ( options.binary === true ) { + + // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification + + var GLB_HEADER_BYTES = 12; + var GLB_HEADER_MAGIC = 0x46546C67; + var GLB_VERSION = 2; + + var GLB_CHUNK_PREFIX_BYTES = 8; + var GLB_CHUNK_TYPE_JSON = 0x4E4F534A; + var GLB_CHUNK_TYPE_BIN = 0x004E4942; + + reader.readAsArrayBuffer( blob ); + reader.onloadend = function () { + + // Binary chunk. + var binaryChunk = getPaddedArrayBuffer( reader.result ); + var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) ); + binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true ); + binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true ); + + // JSON chunk. + var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ) ), 0x20 ); + var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) ); + jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true ); + jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true ); + + // GLB header. + var header = new ArrayBuffer( GLB_HEADER_BYTES ); + var headerView = new DataView( header ); + headerView.setUint32( 0, GLB_HEADER_MAGIC, true ); + headerView.setUint32( 4, GLB_VERSION, true ); + var totalByteLength = GLB_HEADER_BYTES + + jsonChunkPrefix.byteLength + jsonChunk.byteLength + + binaryChunkPrefix.byteLength + binaryChunk.byteLength; + headerView.setUint32( 8, totalByteLength, true ); + + var glbBlob = new Blob( [ + header, + jsonChunkPrefix, + jsonChunk, + binaryChunkPrefix, + binaryChunk + ], { type: 'application/octet-stream' } ); + + var glbReader = new window.FileReader(); + glbReader.readAsArrayBuffer( glbBlob ); + glbReader.onloadend = function () { + + onDone( glbReader.result ); + + }; + + }; + + } else { + + reader.readAsDataURL( blob ); + reader.onloadend = function () { + + var base64data = reader.result; + outputJSON.buffers[ 0 ].uri = base64data; + onDone( outputJSON ); + + }; + + } + + } else { + + onDone( outputJSON ); + + } + + } ); + + } + + }; + + GLTFExporter.Utils = { + + insertKeyframe: function ( track, time ) { + + var tolerance = 0.001; // 1ms + var valueSize = track.getValueSize(); + + var times = new track.TimeBufferType( track.times.length + 1 ); + var values = new track.ValueBufferType( track.values.length + valueSize ); + var interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) ); + + var index; + + if ( track.times.length === 0 ) { + + times[ 0 ] = time; + + for ( var i = 0; i < valueSize; i ++ ) { + + values[ i ] = 0; + + } + + index = 0; + + } else if ( time < track.times[ 0 ] ) { + + if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0; + + times[ 0 ] = time; + times.set( track.times, 1 ); + + values.set( interpolant.evaluate( time ), 0 ); + values.set( track.values, valueSize ); + + index = 0; + + } else if ( time > track.times[ track.times.length - 1 ] ) { + + if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) { + + return track.times.length - 1; + + } + + times[ times.length - 1 ] = time; + times.set( track.times, 0 ); + + values.set( track.values, 0 ); + values.set( interpolant.evaluate( time ), track.values.length ); + + index = times.length - 1; + + } else { + + for ( var i = 0; i < track.times.length; i ++ ) { + + if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i; + + if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) { + + times.set( track.times.slice( 0, i + 1 ), 0 ); + times[ i + 1 ] = time; + times.set( track.times.slice( i + 1 ), i + 2 ); + + values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 ); + values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize ); + values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize ); + + index = i + 1; + + break; + + } + + } + + } + + track.times = times; + track.values = values; + + return index; + + }, + + mergeMorphTargetTracks: function ( clip, root ) { + + var tracks = []; + var mergedTracks = {}; + var sourceTracks = clip.tracks; + + for ( var i = 0; i < sourceTracks.length; ++ i ) { + + var sourceTrack = sourceTracks[ i ]; + var sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name ); + var sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName ); + + if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) { + + // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is. + tracks.push( sourceTrack ); + continue; + + } + + if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete + && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) { + + if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + + // This should never happen, because glTF morph target animations + // affect all targets already. + throw new Error( 'GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' ); + + } + + console.warn( 'GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' ); + + sourceTrack = sourceTrack.clone(); + sourceTrack.setInterpolation( InterpolateLinear ); + + } + + var targetCount = sourceTrackNode.morphTargetInfluences.length; + var targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ]; + + if ( targetIndex === undefined ) { + + throw new Error( 'GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex ); + + } + + var mergedTrack; + + // If this is the first time we've seen this object, create a new + // track to store merged keyframe data for each morph target. + if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) { + + mergedTrack = sourceTrack.clone(); + + var values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length ); + + for ( var j = 0; j < mergedTrack.times.length; j ++ ) { + + values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ]; + + } + + mergedTrack.name = '.morphTargetInfluences'; + mergedTrack.values = values; + + mergedTracks[ sourceTrackNode.uuid ] = mergedTrack; + tracks.push( mergedTrack ); + + continue; + + } + + var mergedKeyframeIndex = 0; + var sourceKeyframeIndex = 0; + var sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) ); + + mergedTrack = mergedTracks[ sourceTrackNode.uuid ]; + + // For every existing keyframe of the merged track, write a (possibly + // interpolated) value from the source track. + for ( var j = 0; j < mergedTrack.times.length; j ++ ) { + + mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] ); + + } + + // For every existing keyframe of the source track, write a (possibly + // new) keyframe to the merged track. Values from the previous loop may + // be written again, but keyframes are de-duplicated. + for ( var j = 0; j < sourceTrack.times.length; j ++ ) { + + var keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] ); + mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ]; + + } + + } + + clip.tracks = tracks; + + return clip; + + } + + }; + return GLTFExporter; +} )(); + +export { GLTFExporter };
false
Other
mrdoob
three.js
3286c15d6ae4c442437beb313937dea213ef4be7.json
Keep that top comment, like other big libs do
.editorconfig
@@ -1,3 +1,5 @@ +# http://editorconfig.org + root = true [*]
false
Other
mrdoob
three.js
61abd4263c403a392b499eecd7eb062b4a1c1603.json
Add a .editorconfig file to enforce coding style
.editorconfig
@@ -0,0 +1,13 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true + +[*.{js,ts,html}] +charset = utf-8 +indent_style = tab +indent_size = 2 + +[*.{js,ts}] +trim_trailing_whitespace = true
false
Other
mrdoob
three.js
aa219bc65af7d82fadc6e643a7b7e25ab0526e06.json
Add TypeScript definitions for example modules
examples/jsm/controls/MapControls.d.ts
@@ -0,0 +1,71 @@ +import { + Camera, + EventDispatcher, + MOUSE, + Object3D, + Vector3 +} from '../../../src/Three'; + +export class MapControls extends EventDispatcher { + constructor(object: Camera, domElement?: HTMLElement); + + object: Camera; + domElement: HTMLElement | HTMLDocument; + + // API + enabled: boolean; + target: Vector3; + + enableZoom: boolean; + zoomSpeed: number; + minDistance: number; + maxDistance: number; + enableRotate: boolean; + rotateSpeed: number; + enablePan: boolean; + keyPanSpeed: number; + maxZoom: number; + minZoom: number; + panSpeed: number; + autoRotate: boolean; + autoRotateSpeed: number; + minPolarAngle: number; + maxPolarAngle: number; + minAzimuthAngle: number; + maxAzimuthAngle: number; + enableKeys: boolean; + screenSpacePanning: boolean; + keys: { LEFT: number; UP: number; RIGHT: number; BOTTOM: number }; + mouseButtons: { LEFT: MOUSE; MIDDLE: MOUSE; RIGHT: MOUSE }; + enableDamping: boolean; + dampingFactor: number; + target0: Vector3; + position0: Vector3; + zoom0: number; + + rotateLeft(angle?: number): void; + + rotateUp(angle?: number): void; + + panLeft(distance?: number): void; + + panUp(distance?: number): void; + + pan(deltaX: number, deltaY: number): void; + + dollyIn(dollyScale: number): void; + + dollyOut(dollyScale: number): void; + + saveState(): void; + + update(): boolean; + + reset(): void; + + dispose(): void; + + getPolarAngle(): number; + + getAzimuthalAngle(): number; +}
true
Other
mrdoob
three.js
aa219bc65af7d82fadc6e643a7b7e25ab0526e06.json
Add TypeScript definitions for example modules
examples/jsm/controls/OrbitControls.d.ts
@@ -0,0 +1,70 @@ +import { Camera, MOUSE, Object3D, Vector3 } from '../../../src/Three'; + +export class OrbitControls { + constructor(object: Camera, domElement?: HTMLElement); + + object: Camera; + domElement: HTMLElement | HTMLDocument; + + // API + enabled: boolean; + target: Vector3; + + // deprecated + center: Vector3; + + enableZoom: boolean; + zoomSpeed: number; + minDistance: number; + maxDistance: number; + enableRotate: boolean; + rotateSpeed: number; + enablePan: boolean; + keyPanSpeed: number; + autoRotate: boolean; + autoRotateSpeed: number; + minPolarAngle: number; + maxPolarAngle: number; + minAzimuthAngle: number; + maxAzimuthAngle: number; + enableKeys: boolean; + keys: {LEFT: number; UP: number; RIGHT: number; BOTTOM: number;}; + mouseButtons: {ORBIT: MOUSE; ZOOM: MOUSE; PAN: MOUSE;}; + enableDamping: boolean; + dampingFactor: number; + screenSpacePanning: boolean; + + + rotateLeft(angle?: number): void; + + rotateUp(angle?: number): void; + + panLeft(distance?: number): void; + + panUp(distance?: number): void; + + pan(deltaX: number, deltaY: number): void; + + dollyIn(dollyScale: number): void; + + dollyOut(dollyScale: number): void; + + update(): void; + + reset(): void; + + dispose(): void; + + getPolarAngle(): number; + + getAzimuthalAngle(): number; + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void): void; + + hasEventListener(type: string, listener: (event: any) => void): boolean; + + removeEventListener(type: string, listener: (event: any) => void): void; + + dispatchEvent(event: {type: string; target: any;}): void; +}
true
Other
mrdoob
three.js
aa219bc65af7d82fadc6e643a7b7e25ab0526e06.json
Add TypeScript definitions for example modules
examples/jsm/controls/TrackballControls.d.ts
@@ -0,0 +1,47 @@ +import { Camera, EventDispatcher, Vector3 } from '../../../src/Three'; + +export class TrackballControls extends EventDispatcher { + constructor(object: Camera, domElement?: HTMLElement); + + object: Camera; + domElement: HTMLElement; + + // API + enabled: boolean; + screen: {left: number; top: number; width: number; height: number}; + rotateSpeed: number; + zoomSpeed: number; + panSpeed: number; + noRotate: boolean; + noZoom: boolean; + noPan: boolean; + noRoll: boolean; + staticMoving: boolean; + dynamicDampingFactor: number; + minDistance: number; + maxDistance: number; + keys: number[]; + + target: Vector3; + position0: Vector3; + target0: Vector3; + up0: Vector3; + + update(): void; + + reset(): void; + + dispose(): void; + + checkDistances(): void; + + zoomCamera(): void; + + panCamera(): void; + + rotateCamera(): void; + + handleResize(): void; + + handleEvent(event: any): void; +}
true
Other
mrdoob
three.js
aa219bc65af7d82fadc6e643a7b7e25ab0526e06.json
Add TypeScript definitions for example modules
examples/jsm/loaders/GLTFLoader.d.ts
@@ -0,0 +1,27 @@ +import { + AnimationClip, + Camera, + LoadingManager, + Scene +} from '../../../src/Three'; + +export interface GLTF { + animations: AnimationClip[]; + scene: Scene; + scenes: Scene[]; + cameras: Camera[]; + asset: object; +} + +export class GLTFLoader { + constructor(manager?: LoadingManager); + manager: LoadingManager; + path: string; + + load(url: string, onLoad: (gltf: GLTF) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void) : void; + setPath(path: string) : GLTFLoader; + setResourcePath(path: string) : GLTFLoader; + setCrossOrigin(value: string): void; + setDRACOLoader(dracoLoader: object): void; + parse(data: ArrayBuffer, path: string, onLoad: (gltf: GLTF) => void, onError?: (event: ErrorEvent) => void) : void; +}
true
Other
mrdoob
three.js
aa219bc65af7d82fadc6e643a7b7e25ab0526e06.json
Add TypeScript definitions for example modules
examples/jsm/loaders/OBJLoader.d.ts
@@ -0,0 +1,19 @@ +import { + Material, + LoadingManager, + Group +} from '../../../src/Three'; + +export class OBJLoader { + constructor(manager?: LoadingManager); + manager: LoadingManager; + regexp: any; + materials: Material[]; + path: string; + + load(url: string, onLoad: (group: Group) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; + parse(data: string) : Group; + setPath(value: string) : void; + setMaterials(materials: Material[]) : void; + _createParserState() : any; +}
true
Other
mrdoob
three.js
96db842b11d79e2e62c4323caf69dca443fc531a.json
Add camera.far argument
examples/webgl_clipping_stencil.html
@@ -115,7 +115,7 @@ scene = new THREE.Scene(); - camera = new THREE.PerspectiveCamera( 36, window.innerWidth / window.innerHeight, 1 ); + camera = new THREE.PerspectiveCamera( 36, window.innerWidth / window.innerHeight, 1, 100 ); camera.position.set( 0, 1.3, 3 ); scene.add( new THREE.AmbientLight( 0xffffff, 0.5 ) );
false
Other
mrdoob
three.js
5fe89aabb870dda767078fb54426b6e2d3529a9b.json
add helpers, distance -> constant
examples/webgl_clipping_stencil.html
@@ -36,28 +36,31 @@ <script> var camera, scene, renderer, startTime, object, stats; - var planes, planeObjects; + var planes, planeObjects, planeHelpers; var clock; var params = { animate: true, planeX: { - distance: 0, - negated: false + constant: 0, + negated: false, + displayHelper: false }, planeY: { - distance: 0, - negated: false + constant: 0, + negated: false, + displayHelper: false }, planeZ: { - distance: 0, - negated: false + constant: 0, + negated: false, + displayHelper: false } @@ -135,6 +138,14 @@ new THREE.Plane( new THREE.Vector3( 0, 0, - 1 ), 0 ) ]; + planeHelpers = planes.map( p => new THREE.PlaneHelper( p, 2, 0xffffff ) ); + planeHelpers.forEach( ph => { + + ph.visible = false; + scene.add( ph ); + + } ); + var geometry = new THREE.TorusKnotBufferGeometry( 0.4, 0.15, 220, 60 ); object = new THREE.Group(); scene.add( object ); @@ -232,31 +243,34 @@ gui.add( params, 'animate' ); var planeX = gui.addFolder( 'planeX' ); - planeX.add( params.planeX, 'distance' ).min( - 0.5 ).max( 0.5 ).onChange( d => planes[ 0 ].constant = d ); + planeX.add( params.planeX, 'displayHelper' ).onChange( v => planeHelpers[ 0 ].visible = v ); + planeX.add( params.planeX, 'constant' ).min( - 1 ).max( 1 ).onChange( d => planes[ 0 ].constant = d ); planeX.add( params.planeX, 'negated' ).onChange( d => { planes[ 0 ].negate(); - params.planeX.distance = planes[ 0 ].constant; + params.planeX.constant = planes[ 0 ].constant; } ); planeX.open(); var planeY = gui.addFolder( 'planeY' ); - planeY.add( params.planeY, 'distance' ).min( - 0.5 ).max( 0.5 ).onChange( d => planes[ 1 ].constant = d ); + planeY.add( params.planeY, 'displayHelper' ).onChange( v => planeHelpers[ 1 ].visible = v ); + planeY.add( params.planeY, 'constant' ).min( - 1 ).max( 1 ).onChange( d => planes[ 1 ].constant = d ); planeY.add( params.planeY, 'negated' ).onChange( d => { planes[ 1 ].negate(); - params.planeY.distance = planes[ 1 ].constant; + params.planeY.constant = planes[ 1 ].constant; } ); planeY.open(); var planeZ = gui.addFolder( 'planeZ' ); - planeZ.add( params.planeZ, 'distance' ).min( - 0.5 ).max( 0.5 ).onChange( d => planes[ 2 ].constant = d ); + planeZ.add( params.planeZ, 'displayHelper' ).onChange( v => planeHelpers[ 2 ].visible = v ); + planeZ.add( params.planeZ, 'constant' ).min( - 1 ).max( 1 ).onChange( d => planes[ 2 ].constant = d ); planeZ.add( params.planeZ, 'negated' ).onChange( d => { planes[ 2 ].negate(); - params.planeZ.distance = planes[ 2 ].constant; + params.planeZ.constant = planes[ 2 ].constant; } ); planeZ.open();
false
Other
mrdoob
three.js
6428719732de464a64d19c955e889f4d39c42a8e.json
remove extraneous comment
examples/webgl_clipping_stencil.html
@@ -180,7 +180,6 @@ } - // Handle camera entering model var material = new THREE.MeshStandardMaterial( { color: 0xFFC107,
false
Other
mrdoob
three.js
b76644f560090f96ce6142b183defb37a619a66d.json
add info tag
examples/webgl_clipping_stencil.html
@@ -6,14 +6,28 @@ <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <style> body { - margin: 0px; + color: #ffffff; + font-family:Monospace; + font-size:13px; + text-align:center; + font-weight: bold; + background-color: #000000; + margin: 0px; overflow: hidden; } + #info { + color: #fff; + position: absolute; + top: 0px; width: 100%; + padding: 5px; + } </style> </head> <body> + <div id="info"><a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - solid geometry with clip planes and stencil materials</div> + <script src="../build/three.js"></script> <script src="js/controls/OrbitControls.js"></script> <script src="js/libs/stats.min.js"></script>
false
Other
mrdoob
three.js
7b53b66a5d21989a599748279763548ef9ab3d82.json
add module for public
package.json
@@ -15,6 +15,7 @@ "build/three.module.js", "src", "examples/js", + "examples/jsm", "examples/fonts" ], "directories": {
false
Other
mrdoob
three.js
99a213e2b6ec8f997f634a5e6454a4c7d74ccd66.json
add glsl comment tag
src/materials/ShaderMaterial.js
@@ -31,8 +31,17 @@ function ShaderMaterial( parameters ) { this.defines = {}; this.uniforms = {}; - this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; - this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; + this.vertexShader = /* glsl */ ` + void main() { + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + } + `; + + this.fragmentShader = /* glsl */ ` + void main() { + gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); + } + `; this.linewidth = 1;
false
Other
mrdoob
three.js
4c8e6c773271f5f8af02356e82b00062bd128fc9.json
Fix #15684. Remove hidden character.
src/renderers/webgl/WebGLTextures.js
@@ -131,7 +131,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } - if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F || + if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) { extensions.get( 'EXT_color_buffer_float' );
false
Other
mrdoob
three.js
7a4c9629d071c440dd990ad7b5036a0887a669e2.json
Update ArrayCamera to subcamera.viewport API.
examples/webgl_camera_array.html
@@ -26,18 +26,20 @@ function init() { - var AMOUNT = 6; - var SIZE = 1 / AMOUNT; var ASPECT_RATIO = window.innerWidth / window.innerHeight; + var AMOUNT = 6; + var WIDTH = ( window.innerWidth / AMOUNT ) * window.devicePixelRatio; + var HEIGHT = ( window.innerHeight / AMOUNT ) * window.devicePixelRatio; + var cameras = []; for ( var y = 0; y < AMOUNT; y ++ ) { for ( var x = 0; x < AMOUNT; x ++ ) { var subcamera = new THREE.PerspectiveCamera( 40, ASPECT_RATIO, 0.1, 10 ); - subcamera.bounds = new THREE.Vector4( x / AMOUNT, y / AMOUNT, SIZE, SIZE ); + subcamera.viewport = new THREE.Vector4( Math.floor( x * WIDTH ), Math.floor( y * HEIGHT ), Math.ceil( WIDTH ), Math.ceil( HEIGHT ) ); subcamera.position.x = ( x / AMOUNT ) - 0.5; subcamera.position.y = 0.5 - ( y / AMOUNT ); subcamera.position.z = 1.5;
false
Other
mrdoob
three.js
505c61a048eaa0dd6b012a060e4f0878f231902b.json
squash getters and setters
examples/js/loaders/GLTFLoader.js
@@ -630,7 +630,7 @@ THREE.GLTFLoader = ( function () { * @pailhead */ - function MeshStandardSGMaterial( params ) { + function GLTFMeshStandardSGMaterial( params ) { THREE.MeshStandardMaterial.call( this ); @@ -704,51 +704,24 @@ THREE.GLTFLoader = ( function () { }; + /*eslint-disable*/ Object.defineProperties( this, { specularMap: { - get: function () { - - return uniforms.specularMap.value; - - }, - set: function ( v ) { - - uniforms.specularMap.value = v; - - } + get: function () { return uniforms.specularMap.value; }, + set: function ( v ) { uniforms.specularMap.value = v; } }, specular: { - get: function () { - - return uniforms.specular.value; - - }, - set: function ( v ) { - - uniforms.specular.value = v; - - } + get: function () { return uniforms.specular.value; }, + set: function ( v ) { uniforms.specular.value = v; } }, glossiness: { - get: function () { - - return uniforms.glossiness.value; - - }, - set: function ( v ) { - - uniforms.glossiness.value = v; - - } + get: function () { return uniforms.glossiness.value; }, + set: function ( v ) { uniforms.glossiness.value = v; } }, glossinessMap: { - get: function () { - - return uniforms.glossinessMap.value; - - }, + get: function () { return uniforms.glossinessMap.value; }, set: function ( v ) { uniforms.glossinessMap.value = v; @@ -770,15 +743,16 @@ THREE.GLTFLoader = ( function () { } } ); + /*eslint-enable*/ this.setValues( params ); } - MeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype ); - MeshStandardSGMaterial.prototype.constructor = MeshStandardSGMaterial; + GLTFMeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype ); + GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial; - MeshStandardSGMaterial.prototype.copy = function ( source ) { + GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) { THREE.MeshStandardMaterial.prototype.copy.call( this, source ); this.specularMap = source.specularMap; @@ -823,7 +797,7 @@ THREE.GLTFLoader = ( function () { getMaterialType: function () { - return MeshStandardSGMaterial; + return GLTFMeshStandardSGMaterial; }, @@ -875,7 +849,7 @@ THREE.GLTFLoader = ( function () { createMaterial: function ( params ) { - var material = new MeshStandardSGMaterial( params ); + var material = new GLTFMeshStandardSGMaterial( params ); material.fog = true; material.color = params.color; @@ -2303,7 +2277,7 @@ THREE.GLTFLoader = ( function () { var material; - if ( materialType === MeshStandardSGMaterial ) { + if ( materialType === GLTFMeshStandardSGMaterial ) { material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams ); @@ -3062,6 +3036,10 @@ THREE.GLTFLoader = ( function () { node = mesh.clone(); node.name += '_instance_' + instanceNum; + } else { + + node = mesh; + } // if weights are provided on the node, override weights on the mesh.
false
Other
mrdoob
three.js
e45e20ad4b90ca0de7a1a738e7be90bd8abfb226.json
fix names and default values
examples/js/loaders/GLTFLoader.js
@@ -630,7 +630,7 @@ THREE.GLTFLoader = ( function () { * @pailhead */ - function SpecularGlossinessPbrMaterial( params ) { + function MeshStandardSGMaterial( params ) { THREE.MeshStandardMaterial.call( this ); @@ -677,8 +677,8 @@ THREE.GLTFLoader = ( function () { ].join( '\n' ); var uniforms = { - specular: { value: new THREE.Color().setHex( 0x111111 ) }, - glossiness: { value: 0.5 }, + specular: { value: new THREE.Color().setHex( 0xffffff ) }, + glossiness: { value: 1 }, specularMap: { value: null }, glossinessMap: { value: null } }; @@ -775,10 +775,10 @@ THREE.GLTFLoader = ( function () { } - SpecularGlossinessPbrMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype ); - SpecularGlossinessPbrMaterial.prototype.constructor = SpecularGlossinessPbrMaterial; + MeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype ); + MeshStandardSGMaterial.prototype.constructor = MeshStandardSGMaterial; - SpecularGlossinessPbrMaterial.prototype.copy = function ( source ) { + MeshStandardSGMaterial.prototype.copy = function ( source ) { THREE.MeshStandardMaterial.prototype.copy.call( this, source ); this.specularMap = source.specularMap; @@ -823,7 +823,7 @@ THREE.GLTFLoader = ( function () { getMaterialType: function () { - return SpecularGlossinessPbrMaterial; + return MeshStandardSGMaterial; }, @@ -875,7 +875,7 @@ THREE.GLTFLoader = ( function () { createMaterial: function ( params ) { - var material = new SpecularGlossinessPbrMaterial( params ); + var material = new MeshStandardSGMaterial( params ); material.fog = true; material.color = params.color; @@ -2333,7 +2333,7 @@ THREE.GLTFLoader = ( function () { var material; - if ( materialType === SpecularGlossinessPbrMaterial ) { + if ( materialType === MeshStandardSGMaterial ) { material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
false
Other
mrdoob
three.js
1b68f9458240a7e1a5918cfc194e8ddf43a186d2.json
fix timeScale argument
examples/js/nodes/utils/TimerNode.js
@@ -12,7 +12,7 @@ function TimerNode( scale, scope, timeScale ) { this.scale = scale !== undefined ? scale : 1; this.scope = scope || TimerNode.GLOBAL; - this.timeScale = timeScale !== undefined ? timeScale : this.scale !== 1; + this.timeScale = timeScale !== undefined ? timeScale : scale !== 1; }
false
Other
mrdoob
three.js
acf2f66efc2babf35bf2cc7f533bc273447312c0.json
add fire animate
examples/webgl_materials_nodes.html
@@ -1335,8 +1335,6 @@ var threshold = new THREE.FloatNode( .1 ); var borderSize = new THREE.FloatNode( .2 ); - // animate uv - var tex = new THREE.TextureNode( getTexture( "cloud" ) ); var texArea = new THREE.SwitchNode( tex, 'w' ); @@ -1398,15 +1396,29 @@ mtl = new THREE.StandardNodeMaterial(); var color = new THREE.ColorNode( 0xEEEEEE ); - var fireStartColor = new THREE.ColorNode( 0xFFD245 ); + var fireStartColor = new THREE.ColorNode( 0xF7CA78 ); var fireEndColor = new THREE.ColorNode( 0xFF0000 ); var burnedColor = new THREE.ColorNode( 0x000000 ); var burnedFinalColor = new THREE.ColorNode( 0x000000 ); var threshold = new THREE.FloatNode( .1 ); var fireSize = new THREE.FloatNode( .16 ); var burnedSize = new THREE.FloatNode( .4 ); + var timer = new THREE.TimerNode( 0.8 ); + + var sinCycleInSecs = new THREE.OperatorNode( + timer, + new THREE.ConstNode( THREE.ConstNode.PI2 ), + THREE.OperatorNode.MUL + ); + + var cycle = new THREE.Math1Node( sinCycleInSecs, THREE.Math1Node.SIN ); + + // round sin to 0 at 1 + cycle = new THREE.OperatorNode( cycle, new THREE.FloatNode( 1 ), THREE.OperatorNode.ADD ); + cycle = new THREE.OperatorNode( cycle, new THREE.FloatNode( 2 ), THREE.OperatorNode.DIV ); - // animate uv + // offset to +.9 + cycle = new THREE.OperatorNode( cycle, new THREE.FloatNode( .9 ), THREE.OperatorNode.ADD ); var tex = new THREE.TextureNode( getTexture( "cloud" ) ); var texArea = new THREE.SwitchNode( tex, 'w' ); @@ -1418,9 +1430,21 @@ THREE.Math3Node.SMOOTHSTEP ); + var fireStartAnimatedColor = new THREE.ColorAdjustmentNode( + fireStartColor, + cycle, + THREE.ColorAdjustmentNode.SATURATION + ); + + var fireEndAnimatedColor = new THREE.ColorAdjustmentNode( + fireEndColor, + cycle, + THREE.ColorAdjustmentNode.SATURATION + ); + var fireColor = new THREE.Math3Node( - fireEndColor, - fireStartColor, + fireEndAnimatedColor, + fireStartAnimatedColor, thresholdBorder, THREE.Math3Node.MIX ); @@ -1499,6 +1523,12 @@ }, true ); + addGui( 'timeScale', timer.scale, function ( val ) { + + timer.scale = val; + + }, false, 0, 2 ); + break; case 'smoke':
false
Other
mrdoob
three.js
8fce3031cfca80183dd2a256598d42c6765aebf0.json
Add color option to gui
examples/webgl_materials_matcap.html
@@ -54,6 +54,7 @@ var image; var API = { + color : 0xffffff, exposure : 1.0 } @@ -106,6 +107,7 @@ mesh.material = new THREE.MeshMatcapMaterial( { + color: API.color, matcap: matcap } ); @@ -117,6 +119,10 @@ // gui var gui = new dat.GUI(); + gui.addColor( API, 'color' ) + .listen() + .onChange( function() { mesh.material.color.set( API.color ); render(); } ); + gui.add( API, 'exposure', 0, 2 ) .onChange( function() { renderer.toneMappingExposure = API.exposure; render(); } ) @@ -173,6 +179,9 @@ matcap.needsUpdate = true; + API.color = 0xffffff; + mesh.material.color.set( API.color ); + render(); image.src = matcap.image.src; // corner div
false
Other
mrdoob
three.js
f2187c0faf0cee40e9776a69226f1d3dc76c3e36.json
Add readme, credits
examples/textures/matcaps/readme.txt
@@ -0,0 +1,5 @@ + +matcap-porcelain-white.jpg courtesy of Milos Paripovic + +https://milosparipovic.com/blog/matcaps-collection +
false
Other
mrdoob
three.js
3d10eb7792e7c77565f1d388b99810870d13cce2.json
update spriteCanvasMaterial doc
docs/examples/SpriteCanvasMaterial.html
@@ -23,14 +23,18 @@ <h3>[name]( [param:Object parameters] )</h3> parameters is an object that can be used to set up the default properties </p> <p> + rotation - the rotation of the sprite<br/> color - the color of the sprite<br/> program - the program used to draw the sprite </p> <h2>Properties</h2> - + <h3>[property:Radians rotation]</h3> + <p> + The rotation of the sprite in radians. Default is 0. + </p> <h3>[property:Color color]</h3> <p>
false
Other
mrdoob
three.js
ace8e6b56d7e621619564ab23da423378f9944fb.json
Adjust code style
examples/js/animation/MMDAnimationHelper.js
@@ -946,7 +946,7 @@ THREE.MMDAnimationHelper = ( function () { if ( this.currentTime < this.delayTime ) return false; - if ((this.currentTime - this.delayTime) > this.audioDuration) return false; + if ( ( this.currentTime - this.delayTime ) > this.audioDuration ) return false; this.audio.startTime = this.currentTime - this.delayTime;
false
Other
mrdoob
three.js
91d7f619f3ff0ca32bad4e79ff3e3a8b2d25f3c6.json
add missing method doc
docs/api/en/core/BufferAttribute.html
@@ -120,6 +120,9 @@ <h2>Methods</h2> <h3>[method:BufferAttribute clone]() </h3> <p>Return a copy of this bufferAttribute.</p> + <h3>[method:BufferAttribute copy]( [param:BufferAttribute bufferAttribute] )</h3> + <p>Copies another BufferAttribute to this BufferAttribute.</p> + <h3>[method:BufferAttribute copyArray]( array ) </h3> <p>Copy the array given here (which can be a normal array or TypedArray) into [page:BufferAttribute.array array].<br /><br />
false
Other
mrdoob
three.js
015573fc37d2e306873a26b6f442bc62591711af.json
return all morph targets
examples/js/loaders/FBXLoader.js
@@ -99,7 +99,7 @@ THREE.FBXLoader = ( function () { } - console.log( fbxTree ); + // console.log( fbxTree ); var textureLoader = new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ).setCrossOrigin( this.crossOrigin ); @@ -743,14 +743,6 @@ THREE.FBXLoader = ( function () { for ( var i = 0; i < relationships.children.length; i ++ ) { - if ( i === 8 ) { - - console.warn( 'FBXLoader: maximum of 8 morph targets supported. Ignoring additional targets.' ); - - break; - - } - var child = relationships.children[ i ]; var morphTargetNode = deformerNodes[ child.ID ]; @@ -774,8 +766,6 @@ THREE.FBXLoader = ( function () { } ); - console.log('rawMorphTarget', rawMorphTarget); - rawMorphTargets.push( rawMorphTarget ); } @@ -2705,8 +2695,6 @@ THREE.FBXLoader = ( function () { } ); - console.log('rawTracks', rawTracks.morphName); - var morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ]; return new THREE.NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values ); @@ -2896,7 +2884,7 @@ THREE.FBXLoader = ( function () { parse: function ( text ) { this.currentIndent = 0; - console.log("FBXTree: ", FBXTree); + this.allNodes = new FBXTree(); this.nodeStack = []; this.currentProp = [];
false
Other
mrdoob
three.js
1c9b1109bf9c8a7ba6c0e591f7ce03b809f8c491.json
fix more example links
examples/webgl_animation_skinning_morph.html
@@ -40,7 +40,7 @@ <div id="info"> <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - clip system - - knight by <a href="http://vimeo.com/36113323">apendua</a> + - knight by <a href="https://vimeo.com/36113323" target="_blank" rel="noopener">apendua</a> <div id="meminfo"></div> </div>
true
Other
mrdoob
three.js
1c9b1109bf9c8a7ba6c0e591f7ce03b809f8c491.json
fix more example links
examples/webgl_geometry_teapot.html
@@ -32,7 +32,7 @@ <body> <div id="info"> <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - the Utah Teapot<br /> - from <a href="https://www.udacity.com/course/interactive-3d-graphics--cs291">Udacity Interactive 3D Graphics</a> + from <a href="https://www.udacity.com/course/interactive-3d-graphics--cs291" target="_blank" rel="noopener">Udacity Interactive 3D Graphics</a> </div> <script src="../build/three.js"></script>
true
Other
mrdoob
three.js
1c9b1109bf9c8a7ba6c0e591f7ce03b809f8c491.json
fix more example links
examples/webgl_loader_assimp2json.html
@@ -31,7 +31,7 @@ <div id="info"> <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - Jeep by Psionic, interior from - <a href="http://assimp.sf.net" target="_blank" rel="noopener">Assimp</a> + <a href="http://www.assimp.org/" target="_blank" rel="noopener">Assimp</a> </div> <script src="../build/three.js"></script>
true
Other
mrdoob
three.js
1c9b1109bf9c8a7ba6c0e591f7ce03b809f8c491.json
fix more example links
examples/webgl_loader_ctm.html
@@ -31,7 +31,7 @@ <div id="info"> <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - <a href="http://openctm.sourceforge.net/" target="_blank" rel="noopener">CTM format</a> loader test - - using <a href="http://code.google.com/p/js-openctm/">js-openctm</a> - + using <a href="https://github.com/jcmellado/js-openctm" target="_blank" rel="noopener">js-openctm</a> - models from <a href="http://www.sci.utah.edu/~wald/animrep/" target="_blank" rel="noopener">The Utah 3D Animation Repository</a>, <a href="http://graphics.cs.williams.edu/data/meshes.xml#14" target="_blank" rel="noopener">Lee Perry-Smith</a>, <a href="http://davidoreilly.com/post/18087489343/disneyhead" target="_blank" rel="noopener">David OReilly</a>
true
Other
mrdoob
three.js
1c9b1109bf9c8a7ba6c0e591f7ce03b809f8c491.json
fix more example links
examples/webgl_loader_ctm_materials.html
@@ -34,7 +34,7 @@ <body> <div id="info"> <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - - using <a href="http://code.google.com/p/js-openctm/">js-openctm</a> - + using <a href="https://github.com/jcmellado/js-openctm" target="_blank" rel="noopener">js-openctm</a> - camaro by <a href="http://www.turbosquid.com/3d-models/blender-camaro/411348" target="_blank" rel="noopener">dskfnwn</a> - skybox by <a href="http://ict.debevec.org/~debevec/" target="_blank" rel="noopener">Paul Debevec</a> </div>
true
Other
mrdoob
three.js
1c9b1109bf9c8a7ba6c0e591f7ce03b809f8c491.json
fix more example links
examples/webgl_loader_ply.html
@@ -39,7 +39,7 @@ <body> <div id="info"> <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - - PLY loader test by <a href="https://github.com/menway">Wei Meng</a>. Image from <a href="http://people.sc.fsu.edu/~jburkardt/data/ply/ply.html">John Burkardt</a> + PLY loader test by <a href="https://github.com/menway" target="_blank" rel="noopener">Wei Meng</a>. Image from <a href="http://people.sc.fsu.edu/~jburkardt/data/ply/ply.html">John Burkardt</a> </div> <script src="../build/three.js"></script>
true
Other
mrdoob
three.js
1c9b1109bf9c8a7ba6c0e591f7ce03b809f8c491.json
fix more example links
examples/webgl_loader_stl.html
@@ -39,7 +39,7 @@ <body> <div id="info"> <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - - STL loader test by <a href="https://github.com/aleeper">aleeper</a>. PR2 head from <a href="http://www.ros.org/wiki/pr2_description">www.ros.org</a> + STL loader test by <a href="https://github.com/aleeper" target="_blank" rel="noopener">aleeper</a>. PR2 head from <a href="http://www.ros.org/wiki/pr2_description">www.ros.org</a> </div> <script src="../build/three.js"></script>
true
Other
mrdoob
three.js
83787b69943f1988bd6bf5230c8e502b7b721563.json
Use BoxLineGeometry in webvr examples.
examples/webvr_ballshooter.html
@@ -24,6 +24,8 @@ <script src="../build/three.js"></script> <script src="js/vr/WebVR.js"></script> + <script src="js/geometries/BoxLineGeometry.js"></script> + <script> var container; @@ -57,9 +59,9 @@ camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 10 ); - room = new THREE.Mesh( - new THREE.BoxBufferGeometry( 6, 6, 6, 8, 8, 8 ), - new THREE.MeshBasicMaterial( { color: 0x808080, wireframe: true } ) + room = new THREE.LineSegments( + new THREE.BoxLineGeometry( 6, 6, 6, 10, 10, 10 ), + new THREE.LineBasicMaterial( { color: 0x808080 } ) ); room.geometry.translate( 0, 3, 0 ); scene.add( room );
true
Other
mrdoob
three.js
83787b69943f1988bd6bf5230c8e502b7b721563.json
Use BoxLineGeometry in webvr examples.
examples/webvr_cubes.html
@@ -22,9 +22,10 @@ <body> <script src="../build/three.js"></script> - <script src="js/vr/WebVR.js"></script> + <script src="js/geometries/BoxLineGeometry.js"></script> + <script> var clock = new THREE.Clock(); @@ -71,9 +72,9 @@ crosshair.position.z = - 2; camera.add( crosshair ); - room = new THREE.Mesh( - new THREE.BoxBufferGeometry( 6, 6, 6, 8, 8, 8 ), - new THREE.MeshBasicMaterial( { color: 0x404040, wireframe: true } ) + room = new THREE.LineSegments( + new THREE.BoxLineGeometry( 6, 6, 6, 10, 10, 10 ), + new THREE.LineBasicMaterial( { color: 0x808080 } ) ); room.position.y = 3; scene.add( room );
true
Other
mrdoob
three.js
ee95e9180ddaad69c19979f4a52e4c3d95831ce9.json
add example to docs
docs/api/en/core/Layers.html
@@ -21,6 +21,11 @@ <h1>[name]</h1> All classes that inherit from [page:Object3D] have an [page:Object3D.layers] property which is an instance of this class. </p> + <h2>Examples</h2> + + <p> + [example:webgl_layers WebGL / layers] + </p> <h2>Constructor</h2>
false
Other
mrdoob
three.js
f3689f2321c42eeddb67ab1ee85fa2ab5050ad8a.json
add example to menu
examples/files.js
@@ -59,6 +59,7 @@ var files = { "webgl_interactive_raycasting_points", "webgl_interactive_voxelpainter", "webgl_kinect", + "webgl_layers", "webgl_lensflares", "webgl_lights_hemisphere", "webgl_lights_physical",
false
Other
mrdoob
three.js
b469a5a0d98c83392de073247b7a061818889afd.json
add layers example
examples/webgl_layers.html
@@ -0,0 +1,156 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <title>three.js webgl - layers</title> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> + <style> + body { + font-family: Monospace; + background-color: #f0f0f0; + margin: 0px; + overflow: hidden; + } + </style> + </head> + <body> + + <script src="../build/three.js"></script> + + <script src="js/libs/stats.min.js"></script> + <script src='js/libs/dat.gui.min.js'></script> + + <script> + + var container, stats; + var camera, scene, renderer; + + var radius = 100, theta = 0; + + init(); + animate(); + + function init() { + + container = document.createElement( 'div' ); + document.body.appendChild( container ); + + var info = document.createElement( 'div' ); + info.style.position = 'absolute'; + info.style.top = '10px'; + info.style.width = '100%'; + info.style.textAlign = 'center'; + info.innerHTML = '<a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - layers'; + container.appendChild( info ); + + var bgTexture = new THREE.TextureLoader().load( 'textures/brick_diffuse.jpg' ); + var bgColor = new THREE.Color( 0xf0f0f0 ); + + camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 ); + camera.layers.enable( 0 ); + camera.layers.enable( 1 ); + camera.layers.enable( 2 ); + + scene = new THREE.Scene(); + scene.background = bgColor; + + var light = new THREE.DirectionalLight( 0xffffff, 1 ); + light.position.set( 1, 1, 1 ).normalize(); + light.layers.enable( 0 ); + light.layers.enable( 1 ); + light.layers.enable( 2 ); + + scene.add( light ); + + var colors = [ 0xff0000, 0x00ff00, 0x0000ff ]; + var geometry = new THREE.BoxBufferGeometry( 20, 20, 20 ); + var layer; + + for ( var i = 0; i < 300; i ++ ) { + + layer = ( i % 3 ); + + var object = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: colors[ layer ] } ) ); + + object.position.x = Math.random() * 800 - 400; + object.position.y = Math.random() * 800 - 400; + object.position.z = Math.random() * 800 - 400; + + object.rotation.x = Math.random() * 2 * Math.PI; + object.rotation.y = Math.random() * 2 * Math.PI; + object.rotation.z = Math.random() * 2 * Math.PI; + + object.scale.x = Math.random() + 0.5; + object.scale.y = Math.random() + 0.5; + object.scale.z = Math.random() + 0.5; + + object.layers.set( layer ); + + scene.add( object ); + + } + + raycaster = new THREE.Raycaster(); + + renderer = new THREE.WebGLRenderer(); + renderer.setPixelRatio( window.devicePixelRatio ); + renderer.setSize( window.innerWidth, window.innerHeight ); + container.appendChild(renderer.domElement); + + stats = new Stats(); + container.appendChild( stats.dom ); + + var layers = { red: true, green: true, blue: true, background: false }; + + // + // Init gui + var gui = new dat.GUI(); + gui.add( layers, 'red' ).onChange( function () { camera.layers.toggle( 0 ); } ); + gui.add( layers, 'green' ).onChange( function () { camera.layers.toggle( 1 ); } ); + gui.add( layers, 'blue' ).onChange( function () { camera.layers.toggle( 2 ); } ); + + gui.add( layers, 'background' ).onChange( function ( value ) { scene.background = value ? bgTexture : bgColor; } ); + + window.addEventListener( 'resize', onWindowResize, false ); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize( window.innerWidth, window.innerHeight ); + + } + + // + + function animate() { + + requestAnimationFrame( animate ); + + render(); + stats.update(); + + } + + function render() { + + theta += 0.1; + + camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) ); + camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) ); + camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) ); + camera.lookAt( scene.position ); + + camera.updateMatrixWorld(); + + renderer.render( scene, camera ); + + } + + </script> + + </body> +</html>
false
Other
mrdoob
three.js
25b9b81c995da187e666d96cf3dd2963acdfdaa4.json
update use of Texture3D constructor
examples/webgl_materials_texture3d_volume1.html
@@ -115,7 +115,9 @@ // THREEJS will select R32F (33326) based on the RedFormat and FloatType. // Also see https://www.khronos.org/registry/webgl/specs/latest/2.0/#TEXTURE_TYPES_FORMATS_FROM_DOM_ELEMENTS_TABLE // TODO: look the dtype up in the volume metadata - var texture = new THREE.Texture3D(volume.data, volume.xLength, volume.yLength, volume.zLength, THREE.RedFormat, THREE.FloatType); + var texture = new THREE.Texture3D( volume.data, volume.xLength, volume.yLength, volume.zLength ); + texture.format = THREE.RedFormat; + texture.type = THREE.FloatType; texture.minFilter = texture.magFilter = THREE.LinearFilter; texture.unpackAlignment = 1; texture.needsUpdate = true;
false
Other
mrdoob
three.js
c8bbc3708ab3bebaa6006461a36c1df77bf271f0.json
increase scope of sceneGraph
examples/js/loaders/FBXLoader.js
@@ -23,6 +23,7 @@ THREE.FBXLoader = ( function () { var FBXTree; var connections; + var sceneGraph = new THREE.Group(); function FBXLoader( manager ) { @@ -131,7 +132,9 @@ THREE.FBXLoader = ( function () { var deformers = this.parseDeformers(); var geometryMap = new GeometryParser().parse( deformers ); - return this.parseScene( deformers, geometryMap, materials ); + this.parseScene( deformers, geometryMap, materials ); + + return sceneGraph; }, @@ -766,8 +769,6 @@ THREE.FBXLoader = ( function () { // create the main THREE.Group() to be returned by the loader parseScene: function ( deformers, geometryMap, materialMap ) { - var sceneGraph = new THREE.Group(); - var modelMap = this.parseModels( deformers.skeletons, geometryMap, materialMap ); var modelNodes = FBXTree.Objects.Model; @@ -776,7 +777,7 @@ THREE.FBXLoader = ( function () { modelMap.forEach( function ( model ) { var modelNode = modelNodes[ model.ID ]; - self.setLookAtProperties( model, modelNode, sceneGraph ); + self.setLookAtProperties( model, modelNode ); var parentConnections = connections.get( model.ID ).parents; @@ -798,24 +799,22 @@ THREE.FBXLoader = ( function () { this.bindSkeleton( deformers.skeletons, geometryMap, modelMap ); - this.createAmbientLight( sceneGraph ); + this.createAmbientLight(); - this.setupMorphMaterials( sceneGraph ); + this.setupMorphMaterials(); - var animations = new AnimationParser().parse( sceneGraph ); + var animations = new AnimationParser().parse(); // if all the models where already combined in a single group, just return that if ( sceneGraph.children.length === 1 && sceneGraph.children[ 0 ].isGroup ) { sceneGraph.children[ 0 ].animations = animations; - return sceneGraph.children[ 0 ]; + sceneGraph = sceneGraph.children[ 0 ]; } sceneGraph.animations = animations; - return sceneGraph; - }, // parse nodes in FBXTree.Objects.Model @@ -1233,7 +1232,7 @@ THREE.FBXLoader = ( function () { }, - setLookAtProperties: function ( model, modelNode, sceneGraph ) { + setLookAtProperties: function ( model, modelNode ) { if ( 'LookAtProperty' in modelNode ) { @@ -1347,7 +1346,7 @@ THREE.FBXLoader = ( function () { }, // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light - createAmbientLight: function ( sceneGraph ) { + createAmbientLight: function () { if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings ) { @@ -1367,7 +1366,7 @@ THREE.FBXLoader = ( function () { }, - setupMorphMaterials: function ( sceneGraph ) { + setupMorphMaterials: function () { sceneGraph.traverse( function ( child ) { @@ -2243,7 +2242,7 @@ THREE.FBXLoader = ( function () { constructor: AnimationParser, // take raw animation clips and turn them into three.js animation clips - parse: function ( sceneGraph ) { + parse: function () { var animationClips = []; @@ -2256,7 +2255,7 @@ THREE.FBXLoader = ( function () { var rawClip = rawClips[ key ]; - var clip = this.addClip( rawClip, sceneGraph ); + var clip = this.addClip( rawClip ); animationClips.push( clip ); @@ -2539,22 +2538,22 @@ THREE.FBXLoader = ( function () { }, - addClip: function ( rawClip, sceneGraph ) { + addClip: function ( rawClip ) { var tracks = []; var self = this; rawClip.layer.forEach( function ( rawTracks ) { - tracks = tracks.concat( self.generateTracks( rawTracks, sceneGraph ) ); + tracks = tracks.concat( self.generateTracks( rawTracks ) ); } ); return new THREE.AnimationClip( rawClip.name, - 1, tracks ); }, - generateTracks: function ( rawTracks, sceneGraph ) { + generateTracks: function ( rawTracks ) { var tracks = []; @@ -2591,7 +2590,7 @@ THREE.FBXLoader = ( function () { if ( rawTracks.DeformPercent !== undefined ) { - var morphTrack = this.generateMorphTrack( rawTracks, sceneGraph ); + var morphTrack = this.generateMorphTrack( rawTracks ); if ( morphTrack !== undefined ) tracks.push( morphTrack ); } @@ -2675,7 +2674,7 @@ THREE.FBXLoader = ( function () { }, - generateMorphTrack: function ( rawTracks, sceneGraph ) { + generateMorphTrack: function ( rawTracks ) { var curves = rawTracks.DeformPercent.curves.morph; var values = curves.values.map( function ( val ) {
false
Other
mrdoob
three.js
9a970e016f5066dbb2ef79db1962888ad2a992ce.json
move all animation parsing to animation parser
examples/js/loaders/FBXLoader.js
@@ -763,7 +763,6 @@ THREE.FBXLoader = ( function () { }, - // create the main THREE.Group() to be returned by the loader parseScene: function ( deformers, geometryMap, materialMap ) { @@ -798,20 +797,23 @@ THREE.FBXLoader = ( function () { } ); this.bindSkeleton( deformers.skeletons, geometryMap, modelMap ); - this.addAnimations( sceneGraph ); this.createAmbientLight( sceneGraph ); this.setupMorphMaterials( sceneGraph ); + var animations = new AnimationParser().parse( sceneGraph ); + // if all the models where already combined in a single group, just return that if ( sceneGraph.children.length === 1 && sceneGraph.children[ 0 ].isGroup ) { - sceneGraph.children[ 0 ].animations = sceneGraph.animations; + sceneGraph.children[ 0 ].animations = animations; return sceneGraph.children[ 0 ]; } + sceneGraph.animations = animations; + return sceneGraph; }, @@ -1344,1476 +1346,1479 @@ THREE.FBXLoader = ( function () { }, - // take raw animation clips and turn them into three.js animation clips - addAnimations: function ( sceneGraph ) { - - sceneGraph.animations = []; - - var rawClips = new AnimationParser( connections ).parse(); + // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light + createAmbientLight: function ( sceneGraph ) { - if ( rawClips === undefined ) return; + if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings ) { - for ( var key in rawClips ) { + var ambientColor = FBXTree.GlobalSettings.AmbientColor.value; + var r = ambientColor[ 0 ]; + var g = ambientColor[ 1 ]; + var b = ambientColor[ 2 ]; - var rawClip = rawClips[ key ]; + if ( r !== 0 || g !== 0 || b !== 0 ) { - var clip = this.addClip( rawClip, sceneGraph ); + var color = new THREE.Color( r, g, b ); + sceneGraph.add( new THREE.AmbientLight( color, 1 ) ); - sceneGraph.animations.push( clip ); + } } }, - addClip: function ( rawClip, sceneGraph ) { - - var tracks = []; + setupMorphMaterials: function ( sceneGraph ) { - var self = this; - rawClip.layer.forEach( function ( rawTracks ) { + sceneGraph.traverse( function ( child ) { - tracks = tracks.concat( self.generateTracks( rawTracks, sceneGraph ) ); + if ( child.isMesh ) { - } ); + if ( child.geometry.morphAttributes.position || child.geometry.morphAttributes.normal ) { - return new THREE.AnimationClip( rawClip.name, - 1, tracks ); + var uuid = child.uuid; + var matUuid = child.material.uuid; - }, + // if a geometry has morph targets, it cannot share the material with other geometries + var sharedMat = false; - generateTracks: function ( rawTracks, sceneGraph ) { + sceneGraph.traverse( function ( child ) { - var tracks = []; + if ( child.isMesh ) { - var initialPosition = new THREE.Vector3(); - var initialRotation = new THREE.Quaternion(); - var initialScale = new THREE.Vector3(); + if ( child.material.uuid === matUuid && child.uuid !== uuid ) sharedMat = true; - if ( rawTracks.transform ) rawTracks.transform.decompose( initialPosition, initialRotation, initialScale ); + } - initialPosition = initialPosition.toArray(); - initialRotation = new THREE.Euler().setFromQuaternion( initialRotation ).toArray(); // todo: euler order - initialScale = initialScale.toArray(); + } ); - if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) { + if ( sharedMat === true ) child.material = child.material.clone(); - var positionTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position' ); - if ( positionTrack !== undefined ) tracks.push( positionTrack ); + child.material.morphTargets = true; - } + } - if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) { + } - var rotationTrack = this.generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotations, rawTracks.postRotations ); - if ( rotationTrack !== undefined ) tracks.push( rotationTrack ); + } ); - } + }, - if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) { + }; - var scaleTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale' ); - if ( scaleTrack !== undefined ) tracks.push( scaleTrack ); + // parse Geometry data from FBXTree and return map of BufferGeometries + function GeometryParser() {} - } + GeometryParser.prototype = { - if ( rawTracks.DeformPercent !== undefined ) { + constructor: GeometryParser, - var morphTrack = this.generateMorphTrack( rawTracks, sceneGraph ); - if ( morphTrack !== undefined ) tracks.push( morphTrack ); + // Parse nodes in FBXTree.Objects.Geometry + parse: function ( deformers ) { - } + var geometryMap = new Map(); - return tracks; + if ( 'Geometry' in FBXTree.Objects ) { - }, + var geoNodes = FBXTree.Objects.Geometry; - generateVectorTrack: function ( modelName, curves, initialValue, type ) { + for ( var nodeID in geoNodes ) { - var times = this.getTimesForAllAxes( curves ); - var values = this.getKeyframeTrackValues( times, curves, initialValue ); + var relationships = connections.get( parseInt( nodeID ) ); + var geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers ); - return new THREE.VectorKeyframeTrack( modelName + '.' + type, times, values ); + geometryMap.set( parseInt( nodeID ), geo ); - }, + } - generateRotationTrack: function ( modelName, curves, initialValue, preRotations, postRotations ) { + } - if ( curves.x !== undefined ) { + return geometryMap; - this.interpolateRotations( curves.x ); - curves.x.values = curves.x.values.map( THREE.Math.degToRad ); + }, - } - if ( curves.y !== undefined ) { + // Parse single node in FBXTree.Objects.Geometry + parseGeometry: function ( relationships, geoNode, deformers ) { - this.interpolateRotations( curves.y ); - curves.y.values = curves.y.values.map( THREE.Math.degToRad ); + switch ( geoNode.attrType ) { - } - if ( curves.z !== undefined ) { + case 'Mesh': + return this.parseMeshGeometry( relationships, geoNode, deformers ); + break; - this.interpolateRotations( curves.z ); - curves.z.values = curves.z.values.map( THREE.Math.degToRad ); + case 'NurbsCurve': + return this.parseNurbsGeometry( geoNode ); + break; } - var times = this.getTimesForAllAxes( curves ); - var values = this.getKeyframeTrackValues( times, curves, initialValue ); - - if ( preRotations !== undefined ) { + }, - preRotations = preRotations.map( THREE.Math.degToRad ); - preRotations.push( 'ZYX' ); + // Parse single node mesh geometry in FBXTree.Objects.Geometry + parseMeshGeometry: function ( relationships, geoNode, deformers ) { - preRotations = new THREE.Euler().fromArray( preRotations ); - preRotations = new THREE.Quaternion().setFromEuler( preRotations ); + var skeletons = deformers.skeletons; + var morphTargets = deformers.morphTargets; - } + var modelNodes = relationships.parents.map( function ( parent ) { - if ( postRotations !== undefined ) { + return FBXTree.Objects.Model[ parent.ID ]; - postRotations = postRotations.map( THREE.Math.degToRad ); - postRotations.push( 'ZYX' ); + } ); - postRotations = new THREE.Euler().fromArray( postRotations ); - postRotations = new THREE.Quaternion().setFromEuler( postRotations ).inverse(); + // don't create geometry if it is not associated with any models + if ( modelNodes.length === 0 ) return; - } + var skeleton = relationships.children.reduce( function ( skeleton, child ) { - var quaternion = new THREE.Quaternion(); - var euler = new THREE.Euler(); + if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ]; - var quaternionValues = []; + return skeleton; - for ( var i = 0; i < values.length; i += 3 ) { + }, null ); - euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], 'ZYX' ); + var morphTarget = relationships.children.reduce( function ( morphTarget, child ) { - quaternion.setFromEuler( euler ); + if ( morphTargets[ child.ID ] !== undefined ) morphTarget = morphTargets[ child.ID ]; - if ( preRotations !== undefined ) quaternion.premultiply( preRotations ); - if ( postRotations !== undefined ) quaternion.multiply( postRotations ); + return morphTarget; - quaternion.toArray( quaternionValues, ( i / 3 ) * 4 ); + }, null ); - } + // TODO: if there is more than one model associated with the geometry, AND the models have + // different geometric transforms, then this will cause problems + // if ( modelNodes.length > 1 ) { } - return new THREE.QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues ); + // For now just assume one model and get the preRotations from that + var modelNode = modelNodes[ 0 ]; - }, + var transformData = {}; - generateMorphTrack: function ( rawTracks, sceneGraph ) { + if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = modelNode.RotationOrder.value; + if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value; + if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value; + if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value; - var curves = rawTracks.DeformPercent.curves.morph; - var values = curves.values.map( function ( val ) { + var transform = generateTransform( transformData ); - return val / 100; + return this.genGeometry( geoNode, skeleton, morphTarget, transform ); - } ); + }, - var morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ]; + // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry + genGeometry: function ( geoNode, skeleton, morphTarget, preTransform ) { - return new THREE.NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values ); + var geo = new THREE.BufferGeometry(); + if ( geoNode.attrName ) geo.name = geoNode.attrName; - }, + var geoInfo = this.parseGeoNode( geoNode, skeleton ); + var buffers = this.genBuffers( geoInfo ); - // For all animated objects, times are defined separately for each axis - // Here we'll combine the times into one sorted array without duplicates - getTimesForAllAxes: function ( curves ) { + var positionAttribute = new THREE.Float32BufferAttribute( buffers.vertex, 3 ); - var times = []; + preTransform.applyToBufferAttribute( positionAttribute ); - // first join together the times for each axis, if defined - if ( curves.x !== undefined ) times = times.concat( curves.x.times ); - if ( curves.y !== undefined ) times = times.concat( curves.y.times ); - if ( curves.z !== undefined ) times = times.concat( curves.z.times ); + geo.addAttribute( 'position', positionAttribute ); - // then sort them and remove duplicates - times = times.sort( function ( a, b ) { + if ( buffers.colors.length > 0 ) { - return a - b; + geo.addAttribute( 'color', new THREE.Float32BufferAttribute( buffers.colors, 3 ) ); - } ).filter( function ( elem, index, array ) { + } - return array.indexOf( elem ) == index; + if ( skeleton ) { - } ); + geo.addAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( buffers.weightsIndices, 4 ) ); - return times; + geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( buffers.vertexWeights, 4 ) ); - }, + // used later to bind the skeleton to the model + geo.FBX_Deformer = skeleton; - getKeyframeTrackValues: function ( times, curves, initialValue ) { + } - var prevValue = initialValue; + if ( buffers.normal.length > 0 ) { - var values = []; + var normalAttribute = new THREE.Float32BufferAttribute( buffers.normal, 3 ); - var xIndex = - 1; - var yIndex = - 1; - var zIndex = - 1; + var normalMatrix = new THREE.Matrix3().getNormalMatrix( preTransform ); + normalMatrix.applyToBufferAttribute( normalAttribute ); - times.forEach( function ( time ) { + geo.addAttribute( 'normal', normalAttribute ); - if ( curves.x ) xIndex = curves.x.times.indexOf( time ); - if ( curves.y ) yIndex = curves.y.times.indexOf( time ); - if ( curves.z ) zIndex = curves.z.times.indexOf( time ); + } - // if there is an x value defined for this frame, use that - if ( xIndex !== - 1 ) { + buffers.uvs.forEach( function ( uvBuffer, i ) { - var xValue = curves.x.values[ xIndex ]; - values.push( xValue ); - prevValue[ 0 ] = xValue; + // subsequent uv buffers are called 'uv1', 'uv2', ... + var name = 'uv' + ( i + 1 ).toString(); - } else { + // the first uv buffer is just called 'uv' + if ( i === 0 ) { - // otherwise use the x value from the previous frame - values.push( prevValue[ 0 ] ); + name = 'uv'; } - if ( yIndex !== - 1 ) { + geo.addAttribute( name, new THREE.Float32BufferAttribute( buffers.uvs[ i ], 2 ) ); - var yValue = curves.y.values[ yIndex ]; - values.push( yValue ); - prevValue[ 1 ] = yValue; + } ); - } else { + if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { - values.push( prevValue[ 1 ] ); + // Convert the material indices of each vertex into rendering groups on the geometry. + var prevMaterialIndex = buffers.materialIndex[ 0 ]; + var startIndex = 0; - } + buffers.materialIndex.forEach( function ( currentIndex, i ) { - if ( zIndex !== - 1 ) { + if ( currentIndex !== prevMaterialIndex ) { - var zValue = curves.z.values[ zIndex ]; - values.push( zValue ); - prevValue[ 2 ] = zValue; + geo.addGroup( startIndex, i - startIndex, prevMaterialIndex ); - } else { + prevMaterialIndex = currentIndex; + startIndex = i; - values.push( prevValue[ 2 ] ); + } - } + } ); - } ); + // the loop above doesn't add the last group, do that here. + if ( geo.groups.length > 0 ) { - return values; + var lastGroup = geo.groups[ geo.groups.length - 1 ]; + var lastIndex = lastGroup.start + lastGroup.count; - }, + if ( lastIndex !== buffers.materialIndex.length ) { - // Rotations are defined as Euler angles which can have values of any size - // These will be converted to quaternions which don't support values greater than - // PI, so we'll interpolate large rotations - interpolateRotations: function ( curve ) { + geo.addGroup( lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex ); - for ( var i = 1; i < curve.values.length; i ++ ) { + } - var initialValue = curve.values[ i - 1 ]; - var valuesSpan = curve.values[ i ] - initialValue; + } - var absoluteSpan = Math.abs( valuesSpan ); + // case where there are multiple materials but the whole geometry is only + // using one of them + if ( geo.groups.length === 0 ) { - if ( absoluteSpan >= 180 ) { + geo.addGroup( 0, buffers.materialIndex.length, buffers.materialIndex[ 0 ] ); - var numSubIntervals = absoluteSpan / 180; + } - var step = valuesSpan / numSubIntervals; - var nextValue = initialValue + step; + } - var initialTime = curve.times[ i - 1 ]; - var timeSpan = curve.times[ i ] - initialTime; - var interval = timeSpan / numSubIntervals; - var nextTime = initialTime + interval; + this.addMorphTargets( geo, geoNode, morphTarget, preTransform ); - var interpolatedTimes = []; - var interpolatedValues = []; + return geo; - while ( nextTime < curve.times[ i ] ) { + }, - interpolatedTimes.push( nextTime ); - nextTime += interval; + parseGeoNode: function ( geoNode, skeleton ) { - interpolatedValues.push( nextValue ); - nextValue += step; + var geoInfo = {}; - } + geoInfo.vertexPositions = ( geoNode.Vertices !== undefined ) ? geoNode.Vertices.a : []; + geoInfo.vertexIndices = ( geoNode.PolygonVertexIndex !== undefined ) ? geoNode.PolygonVertexIndex.a : []; - curve.times = inject( curve.times, i, interpolatedTimes ); - curve.values = inject( curve.values, i, interpolatedValues ); + if ( geoNode.LayerElementColor ) { - } + geoInfo.color = this.parseVertexColors( geoNode.LayerElementColor[ 0 ] ); } - }, + if ( geoNode.LayerElementMaterial ) { - // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light - createAmbientLight: function ( sceneGraph ) { + geoInfo.material = this.parseMaterialIndices( geoNode.LayerElementMaterial[ 0 ] ); - if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings ) { + } - var ambientColor = FBXTree.GlobalSettings.AmbientColor.value; - var r = ambientColor[ 0 ]; - var g = ambientColor[ 1 ]; - var b = ambientColor[ 2 ]; + if ( geoNode.LayerElementNormal ) { - if ( r !== 0 || g !== 0 || b !== 0 ) { + geoInfo.normal = this.parseNormals( geoNode.LayerElementNormal[ 0 ] ); - var color = new THREE.Color( r, g, b ); - sceneGraph.add( new THREE.AmbientLight( color, 1 ) ); + } - } + if ( geoNode.LayerElementUV ) { - } + geoInfo.uv = []; - }, + var i = 0; + while ( geoNode.LayerElementUV[ i ] ) { - setupMorphMaterials: function ( sceneGraph ) { + geoInfo.uv.push( this.parseUVs( geoNode.LayerElementUV[ i ] ) ); + i ++; - sceneGraph.traverse( function ( child ) { + } - if ( child.isMesh ) { + } - if ( child.geometry.morphAttributes.position || child.geometry.morphAttributes.normal ) { + geoInfo.weightTable = {}; - var uuid = child.uuid; - var matUuid = child.material.uuid; + if ( skeleton !== null ) { - // if a geometry has morph targets, it cannot share the material with other geometries - var sharedMat = false; + geoInfo.skeleton = skeleton; - sceneGraph.traverse( function ( child ) { + skeleton.rawBones.forEach( function ( rawBone, i ) { - if ( child.isMesh ) { + // loop over the bone's vertex indices and weights + rawBone.indices.forEach( function ( index, j ) { - if ( child.material.uuid === matUuid && child.uuid !== uuid ) sharedMat = true; + if ( geoInfo.weightTable[ index ] === undefined ) geoInfo.weightTable[ index ] = []; - } + geoInfo.weightTable[ index ].push( { - } ); + id: i, + weight: rawBone.weights[ j ], - if ( sharedMat === true ) child.material = child.material.clone(); + } ); - child.material.morphTargets = true; + } ); - } + } ); - } + } - } ); + return geoInfo; }, - }; + genBuffers: function ( geoInfo ) { - // parse Geometry data from FBXTree and return map of BufferGeometries and nurbs curves - function GeometryParser() {} + var buffers = { + vertex: [], + normal: [], + colors: [], + uvs: [], + materialIndex: [], + vertexWeights: [], + weightsIndices: [], + }; - GeometryParser.prototype = { + var polygonIndex = 0; + var faceLength = 0; + var displayedWeightsWarning = false; - constructor: GeometryParser, + // these will hold data for a single face + var facePositionIndexes = []; + var faceNormals = []; + var faceColors = []; + var faceUVs = []; + var faceWeights = []; + var faceWeightIndices = []; - // Parse nodes in FBXTree.Objects.Geometry - parse: function ( deformers ) { + var self = this; + geoInfo.vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) { - var geometryMap = new Map(); + var endOfFace = false; - if ( 'Geometry' in FBXTree.Objects ) { + // Face index and vertex index arrays are combined in a single array + // A cube with quad faces looks like this: + // PolygonVertexIndex: *24 { + // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5 + // } + // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3 + // to find index of last vertex bit shift the index: ^ - 1 + if ( vertexIndex < 0 ) { - var geoNodes = FBXTree.Objects.Geometry; + vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1 + endOfFace = true; - for ( var nodeID in geoNodes ) { + } - var relationships = connections.get( parseInt( nodeID ) ); - var geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers ); + var weightIndices = []; + var weights = []; - geometryMap.set( parseInt( nodeID ), geo ); + facePositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 ); - } + if ( geoInfo.color ) { - } + var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color ); - return geometryMap; + faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] ); - }, + } - // Parse single node in FBXTree.Objects.Geometry - parseGeometry: function ( relationships, geoNode, deformers ) { + if ( geoInfo.skeleton ) { - switch ( geoNode.attrType ) { + if ( geoInfo.weightTable[ vertexIndex ] !== undefined ) { - case 'Mesh': - return this.parseMeshGeometry( relationships, geoNode, deformers ); - break; + geoInfo.weightTable[ vertexIndex ].forEach( function ( wt ) { - case 'NurbsCurve': - return this.parseNurbsGeometry( geoNode ); - break; + weights.push( wt.weight ); + weightIndices.push( wt.id ); - } + } ); - }, - // Parse single node mesh geometry in FBXTree.Objects.Geometry - parseMeshGeometry: function ( relationships, geoNode, deformers ) { + } - var skeletons = deformers.skeletons; - var morphTargets = deformers.morphTargets; + if ( weights.length > 4 ) { - var modelNodes = relationships.parents.map( function ( parent ) { + if ( ! displayedWeightsWarning ) { - return FBXTree.Objects.Model[ parent.ID ]; + console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' ); + displayedWeightsWarning = true; - } ); + } - // don't create geometry if it is not associated with any models - if ( modelNodes.length === 0 ) return; + var wIndex = [ 0, 0, 0, 0 ]; + var Weight = [ 0, 0, 0, 0 ]; - var skeleton = relationships.children.reduce( function ( skeleton, child ) { + weights.forEach( function ( weight, weightIndex ) { - if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ]; + var currentWeight = weight; + var currentIndex = weightIndices[ weightIndex ]; - return skeleton; + Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) { - }, null ); + if ( currentWeight > comparedWeight ) { - var morphTarget = relationships.children.reduce( function ( morphTarget, child ) { + comparedWeightArray[ comparedWeightIndex ] = currentWeight; + currentWeight = comparedWeight; - if ( morphTargets[ child.ID ] !== undefined ) morphTarget = morphTargets[ child.ID ]; + var tmp = wIndex[ comparedWeightIndex ]; + wIndex[ comparedWeightIndex ] = currentIndex; + currentIndex = tmp; - return morphTarget; + } - }, null ); + } ); - // TODO: if there is more than one model associated with the geometry, AND the models have - // different geometric transforms, then this will cause problems - // if ( modelNodes.length > 1 ) { } + } ); - // For now just assume one model and get the preRotations from that - var modelNode = modelNodes[ 0 ]; + weightIndices = wIndex; + weights = Weight; - var transformData = {}; + } - if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = modelNode.RotationOrder.value; - if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value; - if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value; - if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value; + // if the weight array is shorter than 4 pad with 0s + while ( weights.length < 4 ) { - var transform = generateTransform( transformData ); + weights.push( 0 ); + weightIndices.push( 0 ); - return this.genGeometry( geoNode, skeleton, morphTarget, transform ); + } - }, + for ( var i = 0; i < 4; ++ i ) { - // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry - genGeometry: function ( geoNode, skeleton, morphTarget, preTransform ) { + faceWeights.push( weights[ i ] ); + faceWeightIndices.push( weightIndices[ i ] ); - var geo = new THREE.BufferGeometry(); - if ( geoNode.attrName ) geo.name = geoNode.attrName; + } - var geoInfo = this.parseGeoNode( geoNode, skeleton ); - var buffers = this.genBuffers( geoInfo ); + } - var positionAttribute = new THREE.Float32BufferAttribute( buffers.vertex, 3 ); + if ( geoInfo.normal ) { - preTransform.applyToBufferAttribute( positionAttribute ); + var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal ); - geo.addAttribute( 'position', positionAttribute ); + faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] ); - if ( buffers.colors.length > 0 ) { + } - geo.addAttribute( 'color', new THREE.Float32BufferAttribute( buffers.colors, 3 ) ); + if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { - } + var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material )[ 0 ]; - if ( skeleton ) { + } - geo.addAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( buffers.weightsIndices, 4 ) ); + if ( geoInfo.uv ) { - geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( buffers.vertexWeights, 4 ) ); + geoInfo.uv.forEach( function ( uv, i ) { - // used later to bind the skeleton to the model - geo.FBX_Deformer = skeleton; + var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv ); - } + if ( faceUVs[ i ] === undefined ) { - if ( buffers.normal.length > 0 ) { + faceUVs[ i ] = []; - var normalAttribute = new THREE.Float32BufferAttribute( buffers.normal, 3 ); + } - var normalMatrix = new THREE.Matrix3().getNormalMatrix( preTransform ); - normalMatrix.applyToBufferAttribute( normalAttribute ); + faceUVs[ i ].push( data[ 0 ] ); + faceUVs[ i ].push( data[ 1 ] ); - geo.addAttribute( 'normal', normalAttribute ); + } ); - } + } - buffers.uvs.forEach( function ( uvBuffer, i ) { + faceLength ++; - // subsequent uv buffers are called 'uv1', 'uv2', ... - var name = 'uv' + ( i + 1 ).toString(); + if ( endOfFace ) { - // the first uv buffer is just called 'uv' - if ( i === 0 ) { + self.genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ); - name = 'uv'; + polygonIndex ++; + faceLength = 0; - } + // reset arrays for the next face + facePositionIndexes = []; + faceNormals = []; + faceColors = []; + faceUVs = []; + faceWeights = []; + faceWeightIndices = []; - geo.addAttribute( name, new THREE.Float32BufferAttribute( buffers.uvs[ i ], 2 ) ); + } } ); - if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { - - // Convert the material indices of each vertex into rendering groups on the geometry. - var prevMaterialIndex = buffers.materialIndex[ 0 ]; - var startIndex = 0; - - buffers.materialIndex.forEach( function ( currentIndex, i ) { + return buffers; - if ( currentIndex !== prevMaterialIndex ) { + }, - geo.addGroup( startIndex, i - startIndex, prevMaterialIndex ); + // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris + genFace: function ( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) { - prevMaterialIndex = currentIndex; - startIndex = i; + for ( var i = 2; i < faceLength; i ++ ) { - } + buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] ); + buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] ); + buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] ); - } ); + buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] ); + buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] ); + buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] ); - // the loop above doesn't add the last group, do that here. - if ( geo.groups.length > 0 ) { + buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] ); + buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] ); + buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] ); - var lastGroup = geo.groups[ geo.groups.length - 1 ]; - var lastIndex = lastGroup.start + lastGroup.count; + if ( geoInfo.skeleton ) { - if ( lastIndex !== buffers.materialIndex.length ) { + buffers.vertexWeights.push( faceWeights[ 0 ] ); + buffers.vertexWeights.push( faceWeights[ 1 ] ); + buffers.vertexWeights.push( faceWeights[ 2 ] ); + buffers.vertexWeights.push( faceWeights[ 3 ] ); - geo.addGroup( lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex ); + buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] ); + buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] ); + buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] ); + buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] ); - } + buffers.vertexWeights.push( faceWeights[ i * 4 ] ); + buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] ); + buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] ); + buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] ); - } + buffers.weightsIndices.push( faceWeightIndices[ 0 ] ); + buffers.weightsIndices.push( faceWeightIndices[ 1 ] ); + buffers.weightsIndices.push( faceWeightIndices[ 2 ] ); + buffers.weightsIndices.push( faceWeightIndices[ 3 ] ); - // case where there are multiple materials but the whole geometry is only - // using one of them - if ( geo.groups.length === 0 ) { + buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] ); + buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] ); + buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] ); + buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] ); - geo.addGroup( 0, buffers.materialIndex.length, buffers.materialIndex[ 0 ] ); + buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] ); + buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] ); + buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] ); + buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] ); } - } + if ( geoInfo.color ) { - this.addMorphTargets( geo, geoNode, morphTarget, preTransform ); + buffers.colors.push( faceColors[ 0 ] ); + buffers.colors.push( faceColors[ 1 ] ); + buffers.colors.push( faceColors[ 2 ] ); - return geo; + buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] ); + buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] ); + buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] ); - }, + buffers.colors.push( faceColors[ i * 3 ] ); + buffers.colors.push( faceColors[ i * 3 + 1 ] ); + buffers.colors.push( faceColors[ i * 3 + 2 ] ); - parseGeoNode: function ( geoNode, skeleton ) { + } - var geoInfo = {}; + if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { - geoInfo.vertexPositions = ( geoNode.Vertices !== undefined ) ? geoNode.Vertices.a : []; - geoInfo.vertexIndices = ( geoNode.PolygonVertexIndex !== undefined ) ? geoNode.PolygonVertexIndex.a : []; + buffers.materialIndex.push( materialIndex ); + buffers.materialIndex.push( materialIndex ); + buffers.materialIndex.push( materialIndex ); - if ( geoNode.LayerElementColor ) { + } - geoInfo.color = this.parseVertexColors( geoNode.LayerElementColor[ 0 ] ); + if ( geoInfo.normal ) { - } + buffers.normal.push( faceNormals[ 0 ] ); + buffers.normal.push( faceNormals[ 1 ] ); + buffers.normal.push( faceNormals[ 2 ] ); - if ( geoNode.LayerElementMaterial ) { + buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] ); + buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] ); + buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] ); - geoInfo.material = this.parseMaterialIndices( geoNode.LayerElementMaterial[ 0 ] ); + buffers.normal.push( faceNormals[ i * 3 ] ); + buffers.normal.push( faceNormals[ i * 3 + 1 ] ); + buffers.normal.push( faceNormals[ i * 3 + 2 ] ); - } + } - if ( geoNode.LayerElementNormal ) { + if ( geoInfo.uv ) { - geoInfo.normal = this.parseNormals( geoNode.LayerElementNormal[ 0 ] ); + geoInfo.uv.forEach( function ( uv, j ) { - } + if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = []; - if ( geoNode.LayerElementUV ) { + buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] ); + buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] ); - geoInfo.uv = []; + buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] ); + buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] ); - var i = 0; - while ( geoNode.LayerElementUV[ i ] ) { + buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] ); + buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] ); - geoInfo.uv.push( this.parseUVs( geoNode.LayerElementUV[ i ] ) ); - i ++; + } ); } } - geoInfo.weightTable = {}; + }, - if ( skeleton !== null ) { + addMorphTargets: function ( parentGeo, parentGeoNode, morphTarget, preTransform ) { - geoInfo.skeleton = skeleton; + if ( morphTarget === null ) return; - skeleton.rawBones.forEach( function ( rawBone, i ) { + parentGeo.morphAttributes.position = []; + parentGeo.morphAttributes.normal = []; - // loop over the bone's vertex indices and weights - rawBone.indices.forEach( function ( index, j ) { + var self = this; + morphTarget.rawTargets.forEach( function ( rawTarget ) { - if ( geoInfo.weightTable[ index ] === undefined ) geoInfo.weightTable[ index ] = []; + var morphGeoNode = FBXTree.Objects.Geometry[ rawTarget.geoID ]; - geoInfo.weightTable[ index ].push( { + if ( morphGeoNode !== undefined ) { - id: i, - weight: rawBone.weights[ j ], + self.genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform ); - } ); + } - } ); + } ); - } ); + }, - } + // a morph geometry node is similar to a standard node, and the node is also contained + // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal + // and a special attribute Index defining which vertices of the original geometry are affected + // Normal and position attributes only have data for the vertices that are affected by the morph + genMorphGeometry: function ( parentGeo, parentGeoNode, morphGeoNode, preTransform ) { - return geoInfo; + var morphGeo = new THREE.BufferGeometry(); + if ( morphGeoNode.attrName ) morphGeo.name = morphGeoNode.attrName; - }, + var vertexIndices = ( parentGeoNode.PolygonVertexIndex !== undefined ) ? parentGeoNode.PolygonVertexIndex.a : []; - genBuffers: function ( geoInfo ) { + // make a copy of the parent's vertex positions + var vertexPositions = ( parentGeoNode.Vertices !== undefined ) ? parentGeoNode.Vertices.a.slice() : []; - var buffers = { - vertex: [], - normal: [], - colors: [], - uvs: [], - materialIndex: [], - vertexWeights: [], - weightsIndices: [], - }; + var morphPositions = ( morphGeoNode.Vertices !== undefined ) ? morphGeoNode.Vertices.a : []; + var indices = ( morphGeoNode.Indexes !== undefined ) ? morphGeoNode.Indexes.a : []; - var polygonIndex = 0; - var faceLength = 0; - var displayedWeightsWarning = false; + for ( var i = 0; i < indices.length; i ++ ) { - // these will hold data for a single face - var facePositionIndexes = []; - var faceNormals = []; - var faceColors = []; - var faceUVs = []; - var faceWeights = []; - var faceWeightIndices = []; + var morphIndex = indices[ i ] * 3; - var self = this; - geoInfo.vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) { + // FBX format uses blend shapes rather than morph targets. This can be converted + // by additively combining the blend shape positions with the original geometry's positions + vertexPositions[ morphIndex ] += morphPositions[ i * 3 ]; + vertexPositions[ morphIndex + 1 ] += morphPositions[ i * 3 + 1 ]; + vertexPositions[ morphIndex + 2 ] += morphPositions[ i * 3 + 2 ]; - var endOfFace = false; + } - // Face index and vertex index arrays are combined in a single array - // A cube with quad faces looks like this: - // PolygonVertexIndex: *24 { - // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5 - // } - // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3 - // to find index of last vertex bit shift the index: ^ - 1 - if ( vertexIndex < 0 ) { + // TODO: add morph normal support + var morphGeoInfo = { + vertexIndices: vertexIndices, + vertexPositions: vertexPositions, + }; - vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1 - endOfFace = true; + var morphBuffers = this.genBuffers( morphGeoInfo ); - } + var positionAttribute = new THREE.Float32BufferAttribute( morphBuffers.vertex, 3 ); + positionAttribute.name = morphGeoNode.attrName; - var weightIndices = []; - var weights = []; + preTransform.applyToBufferAttribute( positionAttribute ); - facePositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 ); + parentGeo.morphAttributes.position.push( positionAttribute ); - if ( geoInfo.color ) { + }, - var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color ); + // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists + parseNormals: function ( NormalNode ) { - faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] ); + var mappingType = NormalNode.MappingInformationType; + var referenceType = NormalNode.ReferenceInformationType; + var buffer = NormalNode.Normals.a; + var indexBuffer = []; + if ( referenceType === 'IndexToDirect' ) { - } + if ( 'NormalIndex' in NormalNode ) { - if ( geoInfo.skeleton ) { + indexBuffer = NormalNode.NormalIndex.a; - if ( geoInfo.weightTable[ vertexIndex ] !== undefined ) { + } else if ( 'NormalsIndex' in NormalNode ) { - geoInfo.weightTable[ vertexIndex ].forEach( function ( wt ) { + indexBuffer = NormalNode.NormalsIndex.a; - weights.push( wt.weight ); - weightIndices.push( wt.id ); + } - } ); + } + return { + dataSize: 3, + buffer: buffer, + indices: indexBuffer, + mappingType: mappingType, + referenceType: referenceType + }; - } + }, - if ( weights.length > 4 ) { + // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists + parseUVs: function ( UVNode ) { - if ( ! displayedWeightsWarning ) { + var mappingType = UVNode.MappingInformationType; + var referenceType = UVNode.ReferenceInformationType; + var buffer = UVNode.UV.a; + var indexBuffer = []; + if ( referenceType === 'IndexToDirect' ) { - console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' ); - displayedWeightsWarning = true; + indexBuffer = UVNode.UVIndex.a; - } + } - var wIndex = [ 0, 0, 0, 0 ]; - var Weight = [ 0, 0, 0, 0 ]; + return { + dataSize: 2, + buffer: buffer, + indices: indexBuffer, + mappingType: mappingType, + referenceType: referenceType + }; - weights.forEach( function ( weight, weightIndex ) { + }, - var currentWeight = weight; - var currentIndex = weightIndices[ weightIndex ]; + // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists + parseVertexColors: function ( ColorNode ) { - Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) { + var mappingType = ColorNode.MappingInformationType; + var referenceType = ColorNode.ReferenceInformationType; + var buffer = ColorNode.Colors.a; + var indexBuffer = []; + if ( referenceType === 'IndexToDirect' ) { - if ( currentWeight > comparedWeight ) { + indexBuffer = ColorNode.ColorIndex.a; - comparedWeightArray[ comparedWeightIndex ] = currentWeight; - currentWeight = comparedWeight; + } - var tmp = wIndex[ comparedWeightIndex ]; - wIndex[ comparedWeightIndex ] = currentIndex; - currentIndex = tmp; + return { + dataSize: 4, + buffer: buffer, + indices: indexBuffer, + mappingType: mappingType, + referenceType: referenceType + }; - } + }, - } ); + // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists + parseMaterialIndices: function ( MaterialNode ) { - } ); + var mappingType = MaterialNode.MappingInformationType; + var referenceType = MaterialNode.ReferenceInformationType; - weightIndices = wIndex; - weights = Weight; + if ( mappingType === 'NoMappingInformation' ) { - } + return { + dataSize: 1, + buffer: [ 0 ], + indices: [ 0 ], + mappingType: 'AllSame', + referenceType: referenceType + }; - // if the weight array is shorter than 4 pad with 0s - while ( weights.length < 4 ) { + } - weights.push( 0 ); - weightIndices.push( 0 ); + var materialIndexBuffer = MaterialNode.Materials.a; - } + // Since materials are stored as indices, there's a bit of a mismatch between FBX and what + // we expect.So we create an intermediate buffer that points to the index in the buffer, + // for conforming with the other functions we've written for other data. + var materialIndices = []; - for ( var i = 0; i < 4; ++ i ) { + for ( var i = 0; i < materialIndexBuffer.length; ++ i ) { - faceWeights.push( weights[ i ] ); - faceWeightIndices.push( weightIndices[ i ] ); + materialIndices.push( i ); - } + } - } + return { + dataSize: 1, + buffer: materialIndexBuffer, + indices: materialIndices, + mappingType: mappingType, + referenceType: referenceType + }; - if ( geoInfo.normal ) { + }, - var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal ); + // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry + parseNurbsGeometry: function ( geoNode ) { - faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] ); + if ( THREE.NURBSCurve === undefined ) { - } + console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' ); + return new THREE.BufferGeometry(); - if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { + } - var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material )[ 0 ]; + var order = parseInt( geoNode.Order ); - } + if ( isNaN( order ) ) { - if ( geoInfo.uv ) { + console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id ); + return new THREE.BufferGeometry(); - geoInfo.uv.forEach( function ( uv, i ) { + } - var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv ); + var degree = order - 1; - if ( faceUVs[ i ] === undefined ) { + var knots = geoNode.KnotVector.a; + var controlPoints = []; + var pointsValues = geoNode.Points.a; - faceUVs[ i ] = []; + for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) { - } + controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) ); - faceUVs[ i ].push( data[ 0 ] ); - faceUVs[ i ].push( data[ 1 ] ); + } - } ); + var startKnot, endKnot; - } + if ( geoNode.Form === 'Closed' ) { - faceLength ++; + controlPoints.push( controlPoints[ 0 ] ); - if ( endOfFace ) { + } else if ( geoNode.Form === 'Periodic' ) { - self.genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ); + startKnot = degree; + endKnot = knots.length - 1 - startKnot; - polygonIndex ++; - faceLength = 0; + for ( var i = 0; i < degree; ++ i ) { - // reset arrays for the next face - facePositionIndexes = []; - faceNormals = []; - faceColors = []; - faceUVs = []; - faceWeights = []; - faceWeightIndices = []; + controlPoints.push( controlPoints[ i ] ); } - } ); - - return buffers; - - }, - - // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris - genFace: function ( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) { - - for ( var i = 2; i < faceLength; i ++ ) { + } - buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] ); - buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] ); - buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] ); + var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot ); + var vertices = curve.getPoints( controlPoints.length * 7 ); - buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] ); - buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] ); - buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] ); + var positions = new Float32Array( vertices.length * 3 ); - buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] ); - buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] ); - buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] ); + vertices.forEach( function ( vertex, i ) { - if ( geoInfo.skeleton ) { + vertex.toArray( positions, i * 3 ); - buffers.vertexWeights.push( faceWeights[ 0 ] ); - buffers.vertexWeights.push( faceWeights[ 1 ] ); - buffers.vertexWeights.push( faceWeights[ 2 ] ); - buffers.vertexWeights.push( faceWeights[ 3 ] ); + } ); - buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] ); - buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] ); - buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] ); - buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] ); + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); - buffers.vertexWeights.push( faceWeights[ i * 4 ] ); - buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] ); - buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] ); - buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] ); + return geometry; - buffers.weightsIndices.push( faceWeightIndices[ 0 ] ); - buffers.weightsIndices.push( faceWeightIndices[ 1 ] ); - buffers.weightsIndices.push( faceWeightIndices[ 2 ] ); - buffers.weightsIndices.push( faceWeightIndices[ 3 ] ); + }, - buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] ); - buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] ); - buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] ); - buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] ); + }; - buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] ); - buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] ); - buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] ); - buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] ); + // parse animation data from FBXTree + function AnimationParser() {} - } + AnimationParser.prototype = { - if ( geoInfo.color ) { + constructor: AnimationParser, - buffers.colors.push( faceColors[ 0 ] ); - buffers.colors.push( faceColors[ 1 ] ); - buffers.colors.push( faceColors[ 2 ] ); + // take raw animation clips and turn them into three.js animation clips + parse: function ( sceneGraph ) { - buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] ); - buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] ); - buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] ); + var animationClips = []; - buffers.colors.push( faceColors[ i * 3 ] ); - buffers.colors.push( faceColors[ i * 3 + 1 ] ); - buffers.colors.push( faceColors[ i * 3 + 2 ] ); - } + var rawClips = this.parseClips(); - if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { + if ( rawClips === undefined ) return; - buffers.materialIndex.push( materialIndex ); - buffers.materialIndex.push( materialIndex ); - buffers.materialIndex.push( materialIndex ); + for ( var key in rawClips ) { - } + var rawClip = rawClips[ key ]; - if ( geoInfo.normal ) { + var clip = this.addClip( rawClip, sceneGraph ); - buffers.normal.push( faceNormals[ 0 ] ); - buffers.normal.push( faceNormals[ 1 ] ); - buffers.normal.push( faceNormals[ 2 ] ); + animationClips.push( clip ); - buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] ); - buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] ); - buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] ); + } - buffers.normal.push( faceNormals[ i * 3 ] ); - buffers.normal.push( faceNormals[ i * 3 + 1 ] ); - buffers.normal.push( faceNormals[ i * 3 + 2 ] ); + return animationClips; - } + }, - if ( geoInfo.uv ) { + parseClips: function () { - geoInfo.uv.forEach( function ( uv, j ) { + // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve, + // if this is undefined we can safely assume there are no animations + if ( FBXTree.Objects.AnimationCurve === undefined ) return undefined; - if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = []; + var curveNodesMap = this.parseAnimationCurveNodes(); - buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] ); - buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] ); + this.parseAnimationCurves( curveNodesMap ); - buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] ); - buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] ); + var layersMap = this.parseAnimationLayers( curveNodesMap ); + var rawClips = this.parseAnimStacks( layersMap ); - buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] ); - buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] ); + return rawClips; - } ); + }, - } + // parse nodes in FBXTree.Objects.AnimationCurveNode + // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation ) + // and is referenced by an AnimationLayer + parseAnimationCurveNodes: function () { - } + var rawCurveNodes = FBXTree.Objects.AnimationCurveNode; - }, + var curveNodesMap = new Map(); - addMorphTargets: function ( parentGeo, parentGeoNode, morphTarget, preTransform ) { + for ( var nodeID in rawCurveNodes ) { - if ( morphTarget === null ) return; + var rawCurveNode = rawCurveNodes[ nodeID ]; - parentGeo.morphAttributes.position = []; - parentGeo.morphAttributes.normal = []; + if ( rawCurveNode.attrName.match( /S|R|T|DeformPercent/ ) !== null ) { - var self = this; - morphTarget.rawTargets.forEach( function ( rawTarget ) { + var curveNode = { - var morphGeoNode = FBXTree.Objects.Geometry[ rawTarget.geoID ]; + id: rawCurveNode.id, + attr: rawCurveNode.attrName, + curves: {}, - if ( morphGeoNode !== undefined ) { + }; - self.genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform ); + curveNodesMap.set( curveNode.id, curveNode ); } - } ); - - }, + } - // a morph geometry node is similar to a standard node, and the node is also contained - // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal - // and a special attribute Index defining which vertices of the original geometry are affected - // Normal and position attributes only have data for the vertices that are affected by the morph - genMorphGeometry: function ( parentGeo, parentGeoNode, morphGeoNode, preTransform ) { + return curveNodesMap; - var morphGeo = new THREE.BufferGeometry(); - if ( morphGeoNode.attrName ) morphGeo.name = morphGeoNode.attrName; + }, - var vertexIndices = ( parentGeoNode.PolygonVertexIndex !== undefined ) ? parentGeoNode.PolygonVertexIndex.a : []; + // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to + // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated + // axis ( e.g. times and values of x rotation) + parseAnimationCurves: function ( curveNodesMap ) { - // make a copy of the parent's vertex positions - var vertexPositions = ( parentGeoNode.Vertices !== undefined ) ? parentGeoNode.Vertices.a.slice() : []; + var rawCurves = FBXTree.Objects.AnimationCurve; - var morphPositions = ( morphGeoNode.Vertices !== undefined ) ? morphGeoNode.Vertices.a : []; - var indices = ( morphGeoNode.Indexes !== undefined ) ? morphGeoNode.Indexes.a : []; + // TODO: Many values are identical up to roundoff error, but won't be optimised + // e.g. position times: [0, 0.4, 0. 8] + // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809] + // clearly, this should be optimised to + // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809] + // this shows up in nearly every FBX file, and generally time array is length > 100 - for ( var i = 0; i < indices.length; i ++ ) { + for ( var nodeID in rawCurves ) { - var morphIndex = indices[ i ] * 3; + var animationCurve = { - // FBX format uses blend shapes rather than morph targets. This can be converted - // by additively combining the blend shape positions with the original geometry's positions - vertexPositions[ morphIndex ] += morphPositions[ i * 3 ]; - vertexPositions[ morphIndex + 1 ] += morphPositions[ i * 3 + 1 ]; - vertexPositions[ morphIndex + 2 ] += morphPositions[ i * 3 + 2 ]; + id: rawCurves[ nodeID ].id, + times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ), + values: rawCurves[ nodeID ].KeyValueFloat.a, - } + }; - // TODO: add morph normal support - var morphGeoInfo = { - vertexIndices: vertexIndices, - vertexPositions: vertexPositions, - }; + var relationships = connections.get( animationCurve.id ); - var morphBuffers = this.genBuffers( morphGeoInfo ); + if ( relationships !== undefined ) { - var positionAttribute = new THREE.Float32BufferAttribute( morphBuffers.vertex, 3 ); - positionAttribute.name = morphGeoNode.attrName; + var animationCurveID = relationships.parents[ 0 ].ID; + var animationCurveRelationship = relationships.parents[ 0 ].relationship; - preTransform.applyToBufferAttribute( positionAttribute ); + if ( animationCurveRelationship.match( /X/ ) ) { - parentGeo.morphAttributes.position.push( positionAttribute ); + curveNodesMap.get( animationCurveID ).curves[ 'x' ] = animationCurve; - }, + } else if ( animationCurveRelationship.match( /Y/ ) ) { - // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists - parseNormals: function ( NormalNode ) { + curveNodesMap.get( animationCurveID ).curves[ 'y' ] = animationCurve; - var mappingType = NormalNode.MappingInformationType; - var referenceType = NormalNode.ReferenceInformationType; - var buffer = NormalNode.Normals.a; - var indexBuffer = []; - if ( referenceType === 'IndexToDirect' ) { + } else if ( animationCurveRelationship.match( /Z/ ) ) { - if ( 'NormalIndex' in NormalNode ) { + curveNodesMap.get( animationCurveID ).curves[ 'z' ] = animationCurve; - indexBuffer = NormalNode.NormalIndex.a; + } else if ( animationCurveRelationship.match( /d|DeformPercent/ ) && curveNodesMap.has( animationCurveID ) ) { - } else if ( 'NormalsIndex' in NormalNode ) { + curveNodesMap.get( animationCurveID ).curves[ 'morph' ] = animationCurve; - indexBuffer = NormalNode.NormalsIndex.a; + } } } - return { - dataSize: 3, - buffer: buffer, - indices: indexBuffer, - mappingType: mappingType, - referenceType: referenceType - }; - }, - // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists - parseUVs: function ( UVNode ) { - - var mappingType = UVNode.MappingInformationType; - var referenceType = UVNode.ReferenceInformationType; - var buffer = UVNode.UV.a; - var indexBuffer = []; - if ( referenceType === 'IndexToDirect' ) { + // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references + // to various AnimationCurveNodes and is referenced by an AnimationStack node + // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack + parseAnimationLayers: function ( curveNodesMap ) { - indexBuffer = UVNode.UVIndex.a; + var rawLayers = FBXTree.Objects.AnimationLayer; - } + var layersMap = new Map(); - return { - dataSize: 2, - buffer: buffer, - indices: indexBuffer, - mappingType: mappingType, - referenceType: referenceType - }; + for ( var nodeID in rawLayers ) { - }, + var layerCurveNodes = []; - // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists - parseVertexColors: function ( ColorNode ) { + var connection = connections.get( parseInt( nodeID ) ); - var mappingType = ColorNode.MappingInformationType; - var referenceType = ColorNode.ReferenceInformationType; - var buffer = ColorNode.Colors.a; - var indexBuffer = []; - if ( referenceType === 'IndexToDirect' ) { + if ( connection !== undefined ) { - indexBuffer = ColorNode.ColorIndex.a; + // all the animationCurveNodes used in the layer + var children = connection.children; - } + var self = this; + children.forEach( function ( child, i ) { - return { - dataSize: 4, - buffer: buffer, - indices: indexBuffer, - mappingType: mappingType, - referenceType: referenceType - }; + if ( curveNodesMap.has( child.ID ) ) { - }, + var curveNode = curveNodesMap.get( child.ID ); - // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists - parseMaterialIndices: function ( MaterialNode ) { + // check that the curves are defined for at least one axis, otherwise ignore the curveNode + if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) { - var mappingType = MaterialNode.MappingInformationType; - var referenceType = MaterialNode.ReferenceInformationType; + if ( layerCurveNodes[ i ] === undefined ) { - if ( mappingType === 'NoMappingInformation' ) { + var modelID; - return { - dataSize: 1, - buffer: [ 0 ], - indices: [ 0 ], - mappingType: 'AllSame', - referenceType: referenceType - }; + connections.get( child.ID ).parents.forEach( function ( parent ) { - } + if ( parent.relationship !== undefined ) modelID = parent.ID; - var materialIndexBuffer = MaterialNode.Materials.a; + } ); - // Since materials are stored as indices, there's a bit of a mismatch between FBX and what - // we expect.So we create an intermediate buffer that points to the index in the buffer, - // for conforming with the other functions we've written for other data. - var materialIndices = []; + var rawModel = FBXTree.Objects.Model[ modelID.toString() ]; - for ( var i = 0; i < materialIndexBuffer.length; ++ i ) { + var node = { - materialIndices.push( i ); + modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ), + initialPosition: [ 0, 0, 0 ], + initialRotation: [ 0, 0, 0 ], + initialScale: [ 1, 1, 1 ], + transform: self.getModelAnimTransform( rawModel ), - } + }; - return { - dataSize: 1, - buffer: materialIndexBuffer, - indices: materialIndices, - mappingType: mappingType, - referenceType: referenceType - }; + // if the animated model is pre rotated, we'll have to apply the pre rotations to every + // animation value as well + if ( 'PreRotation' in rawModel ) node.preRotations = rawModel.PreRotation.value; + if ( 'PostRotation' in rawModel ) node.postRotations = rawModel.PostRotation.value; - }, + layerCurveNodes[ i ] = node; - // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry - parseNurbsGeometry: function ( geoNode ) { + } - if ( THREE.NURBSCurve === undefined ) { + layerCurveNodes[ i ][ curveNode.attr ] = curveNode; - console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' ); - return new THREE.BufferGeometry(); + } else if ( curveNode.curves.morph !== undefined ) { - } + if ( layerCurveNodes[ i ] === undefined ) { - var order = parseInt( geoNode.Order ); + var deformerID; - if ( isNaN( order ) ) { + connections.get( child.ID ).parents.forEach( function ( parent ) { - console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id ); - return new THREE.BufferGeometry(); + if ( parent.relationship !== undefined ) deformerID = parent.ID; - } + } ); - var degree = order - 1; + var morpherID = connections.get( deformerID ).parents[ 0 ].ID; + var geoID = connections.get( morpherID ).parents[ 0 ].ID; - var knots = geoNode.KnotVector.a; - var controlPoints = []; - var pointsValues = geoNode.Points.a; + // assuming geometry is not used in more than one model + var modelID = connections.get( geoID ).parents[ 0 ].ID; - for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) { + var rawModel = FBXTree.Objects.Model[ modelID ]; - controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) ); + var node = { - } + modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ), + morphName: FBXTree.Objects.Deformer[ deformerID ].attrName, - var startKnot, endKnot; + }; - if ( geoNode.Form === 'Closed' ) { + layerCurveNodes[ i ] = node; - controlPoints.push( controlPoints[ 0 ] ); + } - } else if ( geoNode.Form === 'Periodic' ) { + layerCurveNodes[ i ][ curveNode.attr ] = curveNode; - startKnot = degree; - endKnot = knots.length - 1 - startKnot; + } - for ( var i = 0; i < degree; ++ i ) { + } - controlPoints.push( controlPoints[ i ] ); + } ); + + layersMap.set( parseInt( nodeID ), layerCurveNodes ); } } - var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot ); - var vertices = curve.getPoints( controlPoints.length * 7 ); + return layersMap; - var positions = new Float32Array( vertices.length * 3 ); + }, - vertices.forEach( function ( vertex, i ) { + getModelAnimTransform: function ( modelNode ) { - vertex.toArray( positions, i * 3 ); + var transformData = {}; - } ); + if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = parseInt( modelNode.RotationOrder.value ); - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + if ( 'Lcl_Translation' in modelNode ) transformData.translation = modelNode.Lcl_Translation.value; + if ( 'RotationOffset' in modelNode ) transformData.rotationOffset = modelNode.RotationOffset.value; - return geometry; + if ( 'Lcl_Rotation' in modelNode ) transformData.rotation = modelNode.Lcl_Rotation.value; + if ( 'PreRotation' in modelNode ) transformData.preRotation = modelNode.PreRotation.value; + + if ( 'PostRotation' in modelNode ) transformData.postRotation = modelNode.PostRotation.value; + + if ( 'Lcl_Scaling' in modelNode ) transformData.scale = modelNode.Lcl_Scaling.value; + + return generateTransform( transformData ); }, - }; + // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation + // hierarchy. Each Stack node will be used to create a THREE.AnimationClip + parseAnimStacks: function ( layersMap ) { - // parse animation data from FBXTree - function AnimationParser() {} + var rawStacks = FBXTree.Objects.AnimationStack; - AnimationParser.prototype = { + // connect the stacks (clips) up to the layers + var rawClips = {}; - constructor: AnimationParser, + for ( var nodeID in rawStacks ) { - parse: function () { + var children = connections.get( parseInt( nodeID ) ).children; - // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve, - // if this is undefined we can safely assume there are no animations - if ( FBXTree.Objects.AnimationCurve === undefined ) return undefined; + if ( children.length > 1 ) { - var curveNodesMap = this.parseAnimationCurveNodes(); + // it seems like stacks will always be associated with a single layer. But just in case there are files + // where there are multiple layers per stack, we'll display a warning + console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' ); - this.parseAnimationCurves( curveNodesMap ); + } - var layersMap = this.parseAnimationLayers( curveNodesMap ); - var rawClips = this.parseAnimStacks( layersMap ); + var layer = layersMap.get( children[ 0 ].ID ); + + rawClips[ nodeID ] = { + + name: rawStacks[ nodeID ].attrName, + layer: layer, + + }; + + } return rawClips; }, - // parse nodes in FBXTree.Objects.AnimationCurveNode - // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation ) - // and is referenced by an AnimationLayer - parseAnimationCurveNodes: function () { + addClip: function ( rawClip, sceneGraph ) { - var rawCurveNodes = FBXTree.Objects.AnimationCurveNode; + var tracks = []; - var curveNodesMap = new Map(); + var self = this; + rawClip.layer.forEach( function ( rawTracks ) { - for ( var nodeID in rawCurveNodes ) { + tracks = tracks.concat( self.generateTracks( rawTracks, sceneGraph ) ); - var rawCurveNode = rawCurveNodes[ nodeID ]; + } ); - if ( rawCurveNode.attrName.match( /S|R|T|DeformPercent/ ) !== null ) { + return new THREE.AnimationClip( rawClip.name, - 1, tracks ); - var curveNode = { + }, - id: rawCurveNode.id, - attr: rawCurveNode.attrName, - curves: {}, + generateTracks: function ( rawTracks, sceneGraph ) { - }; + var tracks = []; - curveNodesMap.set( curveNode.id, curveNode ); + var initialPosition = new THREE.Vector3(); + var initialRotation = new THREE.Quaternion(); + var initialScale = new THREE.Vector3(); - } + if ( rawTracks.transform ) rawTracks.transform.decompose( initialPosition, initialRotation, initialScale ); + + initialPosition = initialPosition.toArray(); + initialRotation = new THREE.Euler().setFromQuaternion( initialRotation ).toArray(); // todo: euler order + initialScale = initialScale.toArray(); + + if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) { + + var positionTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position' ); + if ( positionTrack !== undefined ) tracks.push( positionTrack ); } - return curveNodesMap; + if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) { - }, + var rotationTrack = this.generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotations, rawTracks.postRotations ); + if ( rotationTrack !== undefined ) tracks.push( rotationTrack ); - // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to - // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated - // axis ( e.g. times and values of x rotation) - parseAnimationCurves: function ( curveNodesMap ) { + } - var rawCurves = FBXTree.Objects.AnimationCurve; + if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) { - // TODO: Many values are identical up to roundoff error, but won't be optimised - // e.g. position times: [0, 0.4, 0. 8] - // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809] - // clearly, this should be optimised to - // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809] - // this shows up in nearly every FBX file, and generally time array is length > 100 + var scaleTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale' ); + if ( scaleTrack !== undefined ) tracks.push( scaleTrack ); - for ( var nodeID in rawCurves ) { + } - var animationCurve = { + if ( rawTracks.DeformPercent !== undefined ) { - id: rawCurves[ nodeID ].id, - times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ), - values: rawCurves[ nodeID ].KeyValueFloat.a, + var morphTrack = this.generateMorphTrack( rawTracks, sceneGraph ); + if ( morphTrack !== undefined ) tracks.push( morphTrack ); - }; + } - var relationships = connections.get( animationCurve.id ); + return tracks; - if ( relationships !== undefined ) { + }, - var animationCurveID = relationships.parents[ 0 ].ID; - var animationCurveRelationship = relationships.parents[ 0 ].relationship; + generateVectorTrack: function ( modelName, curves, initialValue, type ) { - if ( animationCurveRelationship.match( /X/ ) ) { + var times = this.getTimesForAllAxes( curves ); + var values = this.getKeyframeTrackValues( times, curves, initialValue ); - curveNodesMap.get( animationCurveID ).curves[ 'x' ] = animationCurve; + return new THREE.VectorKeyframeTrack( modelName + '.' + type, times, values ); - } else if ( animationCurveRelationship.match( /Y/ ) ) { + }, - curveNodesMap.get( animationCurveID ).curves[ 'y' ] = animationCurve; + generateRotationTrack: function ( modelName, curves, initialValue, preRotations, postRotations ) { - } else if ( animationCurveRelationship.match( /Z/ ) ) { + if ( curves.x !== undefined ) { - curveNodesMap.get( animationCurveID ).curves[ 'z' ] = animationCurve; + this.interpolateRotations( curves.x ); + curves.x.values = curves.x.values.map( THREE.Math.degToRad ); - } else if ( animationCurveRelationship.match( /d|DeformPercent/ ) && curveNodesMap.has( animationCurveID ) ) { + } + if ( curves.y !== undefined ) { - curveNodesMap.get( animationCurveID ).curves[ 'morph' ] = animationCurve; + this.interpolateRotations( curves.y ); + curves.y.values = curves.y.values.map( THREE.Math.degToRad ); - } + } + if ( curves.z !== undefined ) { - } + this.interpolateRotations( curves.z ); + curves.z.values = curves.z.values.map( THREE.Math.degToRad ); } - }, + var times = this.getTimesForAllAxes( curves ); + var values = this.getKeyframeTrackValues( times, curves, initialValue ); - // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references - // to various AnimationCurveNodes and is referenced by an AnimationStack node - // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack - parseAnimationLayers: function ( curveNodesMap ) { + if ( preRotations !== undefined ) { - var rawLayers = FBXTree.Objects.AnimationLayer; + preRotations = preRotations.map( THREE.Math.degToRad ); + preRotations.push( 'ZYX' ); - var layersMap = new Map(); + preRotations = new THREE.Euler().fromArray( preRotations ); + preRotations = new THREE.Quaternion().setFromEuler( preRotations ); - for ( var nodeID in rawLayers ) { + } - var layerCurveNodes = []; + if ( postRotations !== undefined ) { - var connection = connections.get( parseInt( nodeID ) ); + postRotations = postRotations.map( THREE.Math.degToRad ); + postRotations.push( 'ZYX' ); - if ( connection !== undefined ) { + postRotations = new THREE.Euler().fromArray( postRotations ); + postRotations = new THREE.Quaternion().setFromEuler( postRotations ).inverse(); - // all the animationCurveNodes used in the layer - var children = connection.children; + } - var self = this; - children.forEach( function ( child, i ) { + var quaternion = new THREE.Quaternion(); + var euler = new THREE.Euler(); - if ( curveNodesMap.has( child.ID ) ) { + var quaternionValues = []; - var curveNode = curveNodesMap.get( child.ID ); + for ( var i = 0; i < values.length; i += 3 ) { - // check that the curves are defined for at least one axis, otherwise ignore the curveNode - if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) { + euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], 'ZYX' ); - if ( layerCurveNodes[ i ] === undefined ) { + quaternion.setFromEuler( euler ); - var modelID; + if ( preRotations !== undefined ) quaternion.premultiply( preRotations ); + if ( postRotations !== undefined ) quaternion.multiply( postRotations ); - connections.get( child.ID ).parents.forEach( function ( parent ) { + quaternion.toArray( quaternionValues, ( i / 3 ) * 4 ); - if ( parent.relationship !== undefined ) modelID = parent.ID; + } - } ); + return new THREE.QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues ); - var rawModel = FBXTree.Objects.Model[ modelID.toString() ]; + }, - var node = { + generateMorphTrack: function ( rawTracks, sceneGraph ) { - modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ), - initialPosition: [ 0, 0, 0 ], - initialRotation: [ 0, 0, 0 ], - initialScale: [ 1, 1, 1 ], - transform: self.getModelAnimTransform( rawModel ), + var curves = rawTracks.DeformPercent.curves.morph; + var values = curves.values.map( function ( val ) { - }; + return val / 100; - // if the animated model is pre rotated, we'll have to apply the pre rotations to every - // animation value as well - if ( 'PreRotation' in rawModel ) node.preRotations = rawModel.PreRotation.value; - if ( 'PostRotation' in rawModel ) node.postRotations = rawModel.PostRotation.value; + } ); - layerCurveNodes[ i ] = node; + var morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ]; - } + return new THREE.NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values ); - layerCurveNodes[ i ][ curveNode.attr ] = curveNode; + }, - } else if ( curveNode.curves.morph !== undefined ) { + // For all animated objects, times are defined separately for each axis + // Here we'll combine the times into one sorted array without duplicates + getTimesForAllAxes: function ( curves ) { - if ( layerCurveNodes[ i ] === undefined ) { + var times = []; - var deformerID; + // first join together the times for each axis, if defined + if ( curves.x !== undefined ) times = times.concat( curves.x.times ); + if ( curves.y !== undefined ) times = times.concat( curves.y.times ); + if ( curves.z !== undefined ) times = times.concat( curves.z.times ); - connections.get( child.ID ).parents.forEach( function ( parent ) { + // then sort them and remove duplicates + times = times.sort( function ( a, b ) { - if ( parent.relationship !== undefined ) deformerID = parent.ID; + return a - b; - } ); + } ).filter( function ( elem, index, array ) { - var morpherID = connections.get( deformerID ).parents[ 0 ].ID; - var geoID = connections.get( morpherID ).parents[ 0 ].ID; + return array.indexOf( elem ) == index; - // assuming geometry is not used in more than one model - var modelID = connections.get( geoID ).parents[ 0 ].ID; + } ); - var rawModel = FBXTree.Objects.Model[ modelID ]; + return times; - var node = { + }, - modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ), - morphName: FBXTree.Objects.Deformer[ deformerID ].attrName, + getKeyframeTrackValues: function ( times, curves, initialValue ) { - }; + var prevValue = initialValue; - layerCurveNodes[ i ] = node; + var values = []; - } + var xIndex = - 1; + var yIndex = - 1; + var zIndex = - 1; - layerCurveNodes[ i ][ curveNode.attr ] = curveNode; + times.forEach( function ( time ) { - } + if ( curves.x ) xIndex = curves.x.times.indexOf( time ); + if ( curves.y ) yIndex = curves.y.times.indexOf( time ); + if ( curves.z ) zIndex = curves.z.times.indexOf( time ); - } + // if there is an x value defined for this frame, use that + if ( xIndex !== - 1 ) { - } ); + var xValue = curves.x.values[ xIndex ]; + values.push( xValue ); + prevValue[ 0 ] = xValue; - layersMap.set( parseInt( nodeID ), layerCurveNodes ); + } else { + + // otherwise use the x value from the previous frame + values.push( prevValue[ 0 ] ); } - } + if ( yIndex !== - 1 ) { - return layersMap; + var yValue = curves.y.values[ yIndex ]; + values.push( yValue ); + prevValue[ 1 ] = yValue; - }, + } else { - getModelAnimTransform: function ( modelNode ) { + values.push( prevValue[ 1 ] ); - var transformData = {}; + } - if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = parseInt( modelNode.RotationOrder.value ); + if ( zIndex !== - 1 ) { - if ( 'Lcl_Translation' in modelNode ) transformData.translation = modelNode.Lcl_Translation.value; - if ( 'RotationOffset' in modelNode ) transformData.rotationOffset = modelNode.RotationOffset.value; + var zValue = curves.z.values[ zIndex ]; + values.push( zValue ); + prevValue[ 2 ] = zValue; - if ( 'Lcl_Rotation' in modelNode ) transformData.rotation = modelNode.Lcl_Rotation.value; - if ( 'PreRotation' in modelNode ) transformData.preRotation = modelNode.PreRotation.value; + } else { - if ( 'PostRotation' in modelNode ) transformData.postRotation = modelNode.PostRotation.value; + values.push( prevValue[ 2 ] ); - if ( 'Lcl_Scaling' in modelNode ) transformData.scale = modelNode.Lcl_Scaling.value; + } - return generateTransform( transformData ); + } ); + + return values; }, - // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation - // hierarchy. Each Stack node will be used to create a THREE.AnimationClip - parseAnimStacks: function ( layersMap ) { + // Rotations are defined as Euler angles which can have values of any size + // These will be converted to quaternions which don't support values greater than + // PI, so we'll interpolate large rotations + interpolateRotations: function ( curve ) { - var rawStacks = FBXTree.Objects.AnimationStack; + for ( var i = 1; i < curve.values.length; i ++ ) { - // connect the stacks (clips) up to the layers - var rawClips = {}; + var initialValue = curve.values[ i - 1 ]; + var valuesSpan = curve.values[ i ] - initialValue; - for ( var nodeID in rawStacks ) { + var absoluteSpan = Math.abs( valuesSpan ); - var children = connections.get( parseInt( nodeID ) ).children; + if ( absoluteSpan >= 180 ) { - if ( children.length > 1 ) { + var numSubIntervals = absoluteSpan / 180; - // it seems like stacks will always be associated with a single layer. But just in case there are files - // where there are multiple layers per stack, we'll display a warning - console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' ); + var step = valuesSpan / numSubIntervals; + var nextValue = initialValue + step; - } + var initialTime = curve.times[ i - 1 ]; + var timeSpan = curve.times[ i ] - initialTime; + var interval = timeSpan / numSubIntervals; + var nextTime = initialTime + interval; - var layer = layersMap.get( children[ 0 ].ID ); + var interpolatedTimes = []; + var interpolatedValues = []; - rawClips[ nodeID ] = { + while ( nextTime < curve.times[ i ] ) { - name: rawStacks[ nodeID ].attrName, - layer: layer, + interpolatedTimes.push( nextTime ); + nextTime += interval; - }; + interpolatedValues.push( nextValue ); + nextValue += step; - } + } - return rawClips; + curve.times = inject( curve.times, i, interpolatedTimes ); + curve.values = inject( curve.values, i, interpolatedValues ); + + } + + } },
false
Other
mrdoob
three.js
24e47535ac79f77744f737109ab3d0082a74bdd3.json
increase scope of connections variable
examples/js/loaders/FBXLoader.js
@@ -22,6 +22,7 @@ THREE.FBXLoader = ( function () { var FBXTree; + var connections; function FBXLoader( manager ) { @@ -122,13 +123,13 @@ THREE.FBXLoader = ( function () { parse: function () { - this.connections = this.parseConnections(); + connections = this.parseConnections(); var images = this.parseImages(); var textures = this.parseTextures( images ); var materials = this.parseMaterials( textures ); var deformers = this.parseDeformers(); - var geometryMap = new GeometryParser( this.connections ).parse( deformers ); + var geometryMap = new GeometryParser().parse( deformers ); return this.parseScene( deformers, geometryMap, materials ); @@ -371,7 +372,7 @@ THREE.FBXLoader = ( function () { var currentPath = this.textureLoader.path; - var children = this.connections.get( textureNode.id ).children; + var children = connections.get( textureNode.id ).children; if ( children !== undefined && children.length > 0 && images[ children[ 0 ].ID ] !== undefined ) { @@ -443,7 +444,7 @@ THREE.FBXLoader = ( function () { } // Ignore unused materials which don't have any connections. - if ( ! this.connections.has( ID ) ) return null; + if ( ! connections.has( ID ) ) return null; var parameters = this.parseParameters( materialNode, textureMap, ID ); @@ -544,7 +545,7 @@ THREE.FBXLoader = ( function () { } var self = this; - this.connections.get( ID ).children.forEach( function ( child ) { + connections.get( ID ).children.forEach( function ( child ) { var type = child.relationship; @@ -608,7 +609,7 @@ THREE.FBXLoader = ( function () { if ( 'LayeredTexture' in FBXTree.Objects && id in FBXTree.Objects.LayeredTexture ) { console.warn( 'THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.' ); - id = this.connections.get( id ).children[ 0 ].ID; + id = connections.get( id ).children[ 0 ].ID; } @@ -632,7 +633,7 @@ THREE.FBXLoader = ( function () { var deformerNode = DeformerNodes[ nodeID ]; - var relationships = this.connections.get( parseInt( nodeID ) ); + var relationships = connections.get( parseInt( nodeID ) ); if ( deformerNode.attrType === 'Skin' ) { @@ -746,7 +747,7 @@ THREE.FBXLoader = ( function () { if ( morphTargetNode.attrType !== 'BlendShapeChannel' ) return; - var targetRelationships = this.connections.get( parseInt( child.ID ) ); + var targetRelationships = connections.get( parseInt( child.ID ) ); targetRelationships.children.forEach( function ( child ) { @@ -778,7 +779,7 @@ THREE.FBXLoader = ( function () { var modelNode = modelNodes[ model.ID ]; self.setLookAtProperties( model, modelNode, sceneGraph ); - var parentConnections = self.connections.get( model.ID ).parents; + var parentConnections = connections.get( model.ID ).parents; parentConnections.forEach( function ( connection ) { @@ -825,7 +826,7 @@ THREE.FBXLoader = ( function () { var id = parseInt( nodeID ); var node = modelNodes[ nodeID ]; - var relationships = this.connections.get( id ); + var relationships = connections.get( id ); var model = this.buildSkeleton( relationships, skeletons, id, node.attrName ); @@ -1234,7 +1235,7 @@ THREE.FBXLoader = ( function () { if ( 'LookAtProperty' in modelNode ) { - var children = this.connections.get( model.ID ).children; + var children = connections.get( model.ID ).children; children.forEach( function ( child ) { @@ -1276,15 +1277,14 @@ THREE.FBXLoader = ( function () { var skeleton = skeletons[ ID ]; - var parents = this.connections.get( parseInt( skeleton.ID ) ).parents; + var parents = connections.get( parseInt( skeleton.ID ) ).parents; - var self = this; parents.forEach( function ( parent ) { if ( geometryMap.has( parent.ID ) ) { var geoID = parent.ID; - var geoRelationships = self.connections.get( geoID ); + var geoRelationships = connections.get( geoID ); geoRelationships.parents.forEach( function ( geoConnParent ) { @@ -1349,7 +1349,7 @@ THREE.FBXLoader = ( function () { sceneGraph.animations = []; - var rawClips = new AnimationParser( this.connections ).parse(); + var rawClips = new AnimationParser( connections ).parse(); if ( rawClips === undefined ) return; @@ -1708,11 +1708,7 @@ THREE.FBXLoader = ( function () { }; // parse Geometry data from FBXTree and return map of BufferGeometries and nurbs curves - function GeometryParser( connections ) { - - this.connections = connections; - - } + function GeometryParser() {} GeometryParser.prototype = { @@ -1729,7 +1725,7 @@ THREE.FBXLoader = ( function () { for ( var nodeID in geoNodes ) { - var relationships = this.connections.get( parseInt( nodeID ) ); + var relationships = connections.get( parseInt( nodeID ) ); var geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers ); geometryMap.set( parseInt( nodeID ), geo ); @@ -2542,11 +2538,7 @@ THREE.FBXLoader = ( function () { }; // parse animation data from FBXTree - function AnimationParser( connections ) { - - this.connections = connections; - - } + function AnimationParser() {} AnimationParser.prototype = { @@ -2626,7 +2618,7 @@ THREE.FBXLoader = ( function () { }; - var relationships = this.connections.get( animationCurve.id ); + var relationships = connections.get( animationCurve.id ); if ( relationships !== undefined ) { @@ -2670,7 +2662,7 @@ THREE.FBXLoader = ( function () { var layerCurveNodes = []; - var connection = this.connections.get( parseInt( nodeID ) ); + var connection = connections.get( parseInt( nodeID ) ); if ( connection !== undefined ) { @@ -2691,7 +2683,7 @@ THREE.FBXLoader = ( function () { var modelID; - self.connections.get( child.ID ).parents.forEach( function ( parent ) { + connections.get( child.ID ).parents.forEach( function ( parent ) { if ( parent.relationship !== undefined ) modelID = parent.ID; @@ -2726,17 +2718,17 @@ THREE.FBXLoader = ( function () { var deformerID; - self.connections.get( child.ID ).parents.forEach( function ( parent ) { + connections.get( child.ID ).parents.forEach( function ( parent ) { if ( parent.relationship !== undefined ) deformerID = parent.ID; } ); - var morpherID = self.connections.get( deformerID ).parents[ 0 ].ID; - var geoID = self.connections.get( morpherID ).parents[ 0 ].ID; + var morpherID = connections.get( deformerID ).parents[ 0 ].ID; + var geoID = connections.get( morpherID ).parents[ 0 ].ID; // assuming geometry is not used in more than one model - var modelID = self.connections.get( geoID ).parents[ 0 ].ID; + var modelID = connections.get( geoID ).parents[ 0 ].ID; var rawModel = FBXTree.Objects.Model[ modelID ]; @@ -2800,7 +2792,7 @@ THREE.FBXLoader = ( function () { for ( var nodeID in rawStacks ) { - var children = this.connections.get( parseInt( nodeID ) ).children; + var children = connections.get( parseInt( nodeID ) ).children; if ( children.length > 1 ) { @@ -3997,4 +3989,4 @@ THREE.FBXLoader = ( function () { return FBXLoader; -} )(); \ No newline at end of file +} )();
false
Other
mrdoob
three.js
45dc88e930acd883ded7efe93ba375e1e3dd1849.json
increase scope of FBXTree variable
examples/js/loaders/FBXLoader.js
@@ -21,6 +21,8 @@ THREE.FBXLoader = ( function () { + var FBXTree; + function FBXLoader( manager ) { this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; @@ -73,8 +75,6 @@ THREE.FBXLoader = ( function () { parse: function ( FBXBuffer, resourceDirectory ) { - var FBXTree; - if ( isFbxFormatBinary( FBXBuffer ) ) { FBXTree = new BinaryParser().parse( FBXBuffer ); @@ -120,16 +120,15 @@ THREE.FBXLoader = ( function () { constructor: FBXTreeParser, - parse: function ( FBXTree ) { + parse: function () { - this.FBXTree = FBXTree; this.connections = this.parseConnections(); var images = this.parseImages(); var textures = this.parseTextures( images ); var materials = this.parseMaterials( textures ); var deformers = this.parseDeformers(); - var geometryMap = new GeometryParser( this.FBXTree, this.connections ).parse( deformers ); + var geometryMap = new GeometryParser( this.connections ).parse( deformers ); return this.parseScene( deformers, geometryMap, materials ); @@ -141,9 +140,9 @@ THREE.FBXLoader = ( function () { var connectionMap = new Map(); - if ( 'Connections' in this.FBXTree ) { + if ( 'Connections' in FBXTree ) { - var rawConnections = this.FBXTree.Connections.connections; + var rawConnections = FBXTree.Connections.connections; rawConnections.forEach( function ( rawConnection ) { @@ -191,9 +190,9 @@ THREE.FBXLoader = ( function () { var images = {}; var blobs = {}; - if ( 'Video' in this.FBXTree.Objects ) { + if ( 'Video' in FBXTree.Objects ) { - var videoNodes = this.FBXTree.Objects.Video; + var videoNodes = FBXTree.Objects.Video; for ( var nodeID in videoNodes ) { @@ -315,9 +314,9 @@ THREE.FBXLoader = ( function () { var textureMap = new Map(); - if ( 'Texture' in this.FBXTree.Objects ) { + if ( 'Texture' in FBXTree.Objects ) { - var textureNodes = this.FBXTree.Objects.Texture; + var textureNodes = FBXTree.Objects.Texture; for ( var nodeID in textureNodes ) { var texture = this.parseTexture( textureNodes[ nodeID ], images ); @@ -409,9 +408,9 @@ THREE.FBXLoader = ( function () { var materialMap = new Map(); - if ( 'Material' in this.FBXTree.Objects ) { + if ( 'Material' in FBXTree.Objects ) { - var materialNodes = this.FBXTree.Objects.Material; + var materialNodes = FBXTree.Objects.Material; for ( var nodeID in materialNodes ) { @@ -606,7 +605,7 @@ THREE.FBXLoader = ( function () { getTexture: function ( textureMap, id ) { // if the texture is a layered texture, just use the first layer and issue a warning - if ( 'LayeredTexture' in this.FBXTree.Objects && id in this.FBXTree.Objects.LayeredTexture ) { + if ( 'LayeredTexture' in FBXTree.Objects && id in FBXTree.Objects.LayeredTexture ) { console.warn( 'THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.' ); id = this.connections.get( id ).children[ 0 ].ID; @@ -625,9 +624,9 @@ THREE.FBXLoader = ( function () { var skeletons = {}; var morphTargets = {}; - if ( 'Deformer' in this.FBXTree.Objects ) { + if ( 'Deformer' in FBXTree.Objects ) { - var DeformerNodes = this.FBXTree.Objects.Deformer; + var DeformerNodes = FBXTree.Objects.Deformer; for ( var nodeID in DeformerNodes ) { @@ -771,7 +770,7 @@ THREE.FBXLoader = ( function () { var modelMap = this.parseModels( deformers.skeletons, geometryMap, materialMap ); - var modelNodes = this.FBXTree.Objects.Model; + var modelNodes = FBXTree.Objects.Model; var self = this; modelMap.forEach( function ( model ) { @@ -820,7 +819,7 @@ THREE.FBXLoader = ( function () { parseModels: function ( skeletons, geometryMap, materialMap ) { var modelMap = new Map(); - var modelNodes = this.FBXTree.Objects.Model; + var modelNodes = FBXTree.Objects.Model; for ( var nodeID in modelNodes ) { @@ -918,10 +917,9 @@ THREE.FBXLoader = ( function () { var model; var cameraAttribute; - var self = this; relationships.children.forEach( function ( child ) { - var attr = self.FBXTree.Objects.NodeAttribute[ child.ID ]; + var attr = FBXTree.Objects.NodeAttribute[ child.ID ]; if ( attr !== undefined ) { @@ -1010,10 +1008,9 @@ THREE.FBXLoader = ( function () { var model; var lightAttribute; - var self = this; relationships.children.forEach( function ( child ) { - var attr = self.FBXTree.Objects.NodeAttribute[ child.ID ]; + var attr = FBXTree.Objects.NodeAttribute[ child.ID ]; if ( attr !== undefined ) { @@ -1239,12 +1236,11 @@ THREE.FBXLoader = ( function () { var children = this.connections.get( model.ID ).children; - var self = this; children.forEach( function ( child ) { if ( child.relationship === 'LookAtProperty' ) { - var lookAtTarget = self.FBXTree.Objects.Model[ child.ID ]; + var lookAtTarget = FBXTree.Objects.Model[ child.ID ]; if ( 'Lcl_Translation' in lookAtTarget ) { @@ -1314,9 +1310,9 @@ THREE.FBXLoader = ( function () { var bindMatrices = {}; - if ( 'Pose' in this.FBXTree.Objects ) { + if ( 'Pose' in FBXTree.Objects ) { - var BindPoseNode = this.FBXTree.Objects.Pose; + var BindPoseNode = FBXTree.Objects.Pose; for ( var nodeID in BindPoseNode ) { @@ -1353,7 +1349,7 @@ THREE.FBXLoader = ( function () { sceneGraph.animations = []; - var rawClips = new AnimationParser( this.FBXTree, this.connections ).parse(); + var rawClips = new AnimationParser( this.connections ).parse(); if ( rawClips === undefined ) return; @@ -1655,9 +1651,9 @@ THREE.FBXLoader = ( function () { // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light createAmbientLight: function ( sceneGraph ) { - if ( 'GlobalSettings' in this.FBXTree && 'AmbientColor' in this.FBXTree.GlobalSettings ) { + if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings ) { - var ambientColor = this.FBXTree.GlobalSettings.AmbientColor.value; + var ambientColor = FBXTree.GlobalSettings.AmbientColor.value; var r = ambientColor[ 0 ]; var g = ambientColor[ 1 ]; var b = ambientColor[ 2 ]; @@ -1712,9 +1708,8 @@ THREE.FBXLoader = ( function () { }; // parse Geometry data from FBXTree and return map of BufferGeometries and nurbs curves - function GeometryParser( FBXTree, connections ) { + function GeometryParser( connections ) { - this.FBXTree = FBXTree; this.connections = connections; } @@ -1728,9 +1723,9 @@ THREE.FBXLoader = ( function () { var geometryMap = new Map(); - if ( 'Geometry' in this.FBXTree.Objects ) { + if ( 'Geometry' in FBXTree.Objects ) { - var geoNodes = this.FBXTree.Objects.Geometry; + var geoNodes = FBXTree.Objects.Geometry; for ( var nodeID in geoNodes ) { @@ -1770,10 +1765,9 @@ THREE.FBXLoader = ( function () { var skeletons = deformers.skeletons; var morphTargets = deformers.morphTargets; - var self = this; var modelNodes = relationships.parents.map( function ( parent ) { - return self.FBXTree.Objects.Model[ parent.ID ]; + return FBXTree.Objects.Model[ parent.ID ]; } ); @@ -2301,7 +2295,7 @@ THREE.FBXLoader = ( function () { var self = this; morphTarget.rawTargets.forEach( function ( rawTarget ) { - var morphGeoNode = self.FBXTree.Objects.Geometry[ rawTarget.geoID ]; + var morphGeoNode = FBXTree.Objects.Geometry[ rawTarget.geoID ]; if ( morphGeoNode !== undefined ) { @@ -2548,9 +2542,8 @@ THREE.FBXLoader = ( function () { }; // parse animation data from FBXTree - function AnimationParser( FBXTree, connections ) { + function AnimationParser( connections ) { - this.FBXTree = FBXTree; this.connections = connections; } @@ -2563,7 +2556,7 @@ THREE.FBXLoader = ( function () { // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve, // if this is undefined we can safely assume there are no animations - if ( this.FBXTree.Objects.AnimationCurve === undefined ) return undefined; + if ( FBXTree.Objects.AnimationCurve === undefined ) return undefined; var curveNodesMap = this.parseAnimationCurveNodes(); @@ -2581,7 +2574,7 @@ THREE.FBXLoader = ( function () { // and is referenced by an AnimationLayer parseAnimationCurveNodes: function () { - var rawCurveNodes = this.FBXTree.Objects.AnimationCurveNode; + var rawCurveNodes = FBXTree.Objects.AnimationCurveNode; var curveNodesMap = new Map(); @@ -2614,7 +2607,7 @@ THREE.FBXLoader = ( function () { // axis ( e.g. times and values of x rotation) parseAnimationCurves: function ( curveNodesMap ) { - var rawCurves = this.FBXTree.Objects.AnimationCurve; + var rawCurves = FBXTree.Objects.AnimationCurve; // TODO: Many values are identical up to roundoff error, but won't be optimised // e.g. position times: [0, 0.4, 0. 8] @@ -2669,7 +2662,7 @@ THREE.FBXLoader = ( function () { // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack parseAnimationLayers: function ( curveNodesMap ) { - var rawLayers = this.FBXTree.Objects.AnimationLayer; + var rawLayers = FBXTree.Objects.AnimationLayer; var layersMap = new Map(); @@ -2704,7 +2697,7 @@ THREE.FBXLoader = ( function () { } ); - var rawModel = self.FBXTree.Objects.Model[ modelID.toString() ]; + var rawModel = FBXTree.Objects.Model[ modelID.toString() ]; var node = { @@ -2745,12 +2738,12 @@ THREE.FBXLoader = ( function () { // assuming geometry is not used in more than one model var modelID = self.connections.get( geoID ).parents[ 0 ].ID; - var rawModel = self.FBXTree.Objects.Model[ modelID ]; + var rawModel = FBXTree.Objects.Model[ modelID ]; var node = { modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ), - morphName: self.FBXTree.Objects.Deformer[ deformerID ].attrName, + morphName: FBXTree.Objects.Deformer[ deformerID ].attrName, }; @@ -2800,7 +2793,7 @@ THREE.FBXLoader = ( function () { // hierarchy. Each Stack node will be used to create a THREE.AnimationClip parseAnimStacks: function ( layersMap ) { - var rawStacks = this.FBXTree.Objects.AnimationStack; + var rawStacks = FBXTree.Objects.AnimationStack; // connect the stacks (clips) up to the layers var rawClips = {};
false
Other
mrdoob
three.js
64bf35c366700a7731a9cbb99c069fce7ebedd21.json
show preservePosition param
examples/webgl_loader_sea3d_bvh.html
@@ -115,6 +115,7 @@ function bvhToSEA3D( result ) { var clip = THREE.SkeletonUtils.retargetClip( player, result.skeleton, result.clip, { + preservePosition: true, hip: "Base HumanPelvis", names: { "Base HumanPelvis": "hip",
false
Other
mrdoob
three.js
a25321ceb62305ecfc7ded184ebee8739076bf70.json
fix bug: when material is undefined The triangle may not have the material
src/objects/Mesh.js
@@ -162,7 +162,7 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { var intersect; - + if(!material) return null; if ( material.side === BackSide ) { intersect = ray.intersectTriangle( pC, pB, pA, true, point );
false
Other
mrdoob
three.js
a821d1619e4f5cfe58432577c6b69490d6db08b6.json
use hard tabs in Vector2.html
docs/api/math/Vector2.html
@@ -175,9 +175,9 @@ <h3>[method:Float dot]( [param:Vector2 v] )</h3> <p> Calculates the [link:https://en.wikipedia.org/wiki/Dot_product dot product] of this vector and [page:Vector2 v]. - </p> + </p> - <h3>[method:Float cross]( [param:Vector2 v] )</h3> + <h3>[method:Float cross]( [param:Vector2 v] )</h3> <p> Calculates the [link:https://en.wikipedia.org/wiki/Cross_product cross product] of this vector and [page:Vector2 v]. Note that a 'cross-product' in 2D is not well-defined. This function computes a geometric cross-product often used in 2D graphics
false
Other
mrdoob
three.js
b3df276e8de94f3ca57c92f3e7c386bdb4384da6.json
add docs and unit test of Vector2.cross method
docs/api/math/Vector2.html
@@ -175,6 +175,12 @@ <h3>[method:Float dot]( [param:Vector2 v] )</h3> <p> Calculates the [link:https://en.wikipedia.org/wiki/Dot_product dot product] of this vector and [page:Vector2 v]. + </p> + + <h3>[method:Float cross]( [param:Vector2 v] )</h3> + <p> + Calculates the [link:https://en.wikipedia.org/wiki/Cross_product cross product] of this + vector and [page:Vector2 v]. Note that a 'cross-product' in 2D is not well-defined. This function computes a geometric cross-product often used in 2D graphics </p> <h3>[method:Boolean equals]( [param:Vector2 v] )</h3>
true
Other
mrdoob
three.js
b3df276e8de94f3ca57c92f3e7c386bdb4384da6.json
add docs and unit test of Vector2.cross method
test/unit/src/math/Vector2.tests.js
@@ -9,7 +9,8 @@ import { Matrix3 } from '../../../../src/math/Matrix3'; import { BufferAttribute } from '../../../../src/core/BufferAttribute'; import { x, - y + y, + eps } from './Constants.tests'; export default QUnit.module( 'Maths', () => { @@ -306,6 +307,17 @@ export default QUnit.module( 'Maths', () => { } ); + QUnit.test( "cross", ( assert ) => { + + var a = new Vector2( x, y ); + var b = new Vector2( 2 * x, - y ); + var answer = - 18; + var crossed = a.cross( b ); + + assert.ok( Math.abs( answer - crossed ) <= eps, "Check cross" ); + + } ); + QUnit.todo( "lengthSq", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); @@ -337,7 +349,6 @@ export default QUnit.module( 'Maths', () => { var a = new Vector2( x, 0 ); var b = new Vector2( 0, - y ); - var c = new Vector2(); a.normalize(); assert.ok( a.length() == 1, "Passed!" );
true
Other
mrdoob
three.js
ceef48eedc496698a2f92106bd01070983c13112.json
add cross method to Vector2
src/math/Vector2.js
@@ -353,6 +353,12 @@ Object.assign( Vector2.prototype, { }, + cross: function ( v ) { + + return this.x * v.y - this.y * v.x; + + }, + lengthSq: function () { return this.x * this.x + this.y * this.y;
false
Other
mrdoob
three.js
770b4296c0f2ceca60632eed7f0b96c726524f1c.json
Fix the VRMLLoader `this` scope.
examples/js/loaders/VRMLLoader.js
@@ -50,6 +50,7 @@ THREE.VRMLLoader.prototype = { parse: function ( data ) { + var scope = this; var texturePath = this.texturePath || ''; var textureLoader = new THREE.TextureLoader( this.manager ); @@ -204,34 +205,34 @@ THREE.VRMLLoader.prototype = { case 'skyAngle': case 'groundAngle': - this.recordingFieldname = fieldName; - this.isRecordingAngles = true; - this.angles = []; + scope.recordingFieldname = fieldName; + scope.isRecordingAngles = true; + scope.angles = []; break; case 'skyColor': case 'groundColor': - this.recordingFieldname = fieldName; - this.isRecordingColors = true; - this.colors = []; + scope.recordingFieldname = fieldName; + scope.isRecordingColors = true; + scope.colors = []; break; case 'point': - this.recordingFieldname = fieldName; - this.isRecordingPoints = true; - this.points = []; + scope.recordingFieldname = fieldName; + scope.isRecordingPoints = true; + scope.points = []; break; case 'coordIndex': case 'texCoordIndex': - this.recordingFieldname = fieldName; - this.isRecordingFaces = true; - this.indexes = []; + scope.recordingFieldname = fieldName; + scope.isRecordingFaces = true; + scope.indexes = []; break; } - if ( this.isRecordingFaces ) { + if ( scope.isRecordingFaces ) { // the parts hold the indexes as strings if ( parts.length > 0 ) { @@ -250,7 +251,7 @@ THREE.VRMLLoader.prototype = { if ( index.length > 0 ) { - this.indexes.push( index ); + scope.indexes.push( index ); } @@ -272,19 +273,19 @@ THREE.VRMLLoader.prototype = { if ( index.length > 0 ) { - this.indexes.push( index ); + scope.indexes.push( index ); } // start new one index = []; - this.isRecordingFaces = false; - node[ this.recordingFieldname ] = this.indexes; + scope.isRecordingFaces = false; + node[ scope.recordingFieldname ] = scope.indexes; } - } else if ( this.isRecordingPoints ) { + } else if ( scope.isRecordingPoints ) { if ( node.nodeType == 'Coordinate' ) { @@ -296,7 +297,7 @@ THREE.VRMLLoader.prototype = { z: parseFloat( parts[ 3 ] ) }; - this.points.push( point ); + scope.points.push( point ); } @@ -311,7 +312,7 @@ THREE.VRMLLoader.prototype = { y: parseFloat( parts[ 2 ] ) }; - this.points.push( point ); + scope.points.push( point ); } @@ -320,12 +321,12 @@ THREE.VRMLLoader.prototype = { // end if ( /]/.exec( line ) ) { - this.isRecordingPoints = false; - node.points = this.points; + scope.isRecordingPoints = false; + node.points = scope.points; } - } else if ( this.isRecordingAngles ) { + } else if ( scope.isRecordingAngles ) { // the parts hold the angles as strings if ( parts.length > 0 ) { @@ -339,7 +340,7 @@ THREE.VRMLLoader.prototype = { } - this.angles.push( parseFloat( parts[ ind ] ) ); + scope.angles.push( parseFloat( parts[ ind ] ) ); } @@ -348,12 +349,12 @@ THREE.VRMLLoader.prototype = { // end if ( /]/.exec( line ) ) { - this.isRecordingAngles = false; - node[ this.recordingFieldname ] = this.angles; + scope.isRecordingAngles = false; + node[ scope.recordingFieldname ] = scope.angles; } - } else if ( this.isRecordingColors ) { + } else if ( scope.isRecordingColors ) { while ( null !== ( parts = float3_pattern.exec( line ) ) ) { @@ -363,15 +364,15 @@ THREE.VRMLLoader.prototype = { b: parseFloat( parts[ 3 ] ) }; - this.colors.push( color ); + scope.colors.push( color ); } // end if ( /]/.exec( line ) ) { - this.isRecordingColors = false; - node[ this.recordingFieldname ] = this.colors; + scope.isRecordingColors = false; + node[ scope.recordingFieldname ] = scope.colors; }
false
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/canvas_geometry_birds.html
@@ -355,10 +355,6 @@ } - </script> - - <script> - var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight, SCREEN_WIDTH_HALF = SCREEN_WIDTH / 2,
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/canvas_geometry_panorama.html
@@ -44,6 +44,8 @@ var texture_placeholder, isUserInteracting = false, onMouseDownMouseX = 0, onMouseDownMouseY = 0, + onPointerDownPointerX = 0, onPointerDownPointerY = 0, + onPointerDownLon = 0, onPointerDownLat = 0, lon = 90, onMouseDownLon = 0, lat = 0, onMouseDownLat = 0, phi = 0, theta = 0,
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/canvas_geometry_panorama_fisheye.html
@@ -44,6 +44,8 @@ var texture_placeholder, isUserInteracting = false, onMouseDownMouseX = 0, onMouseDownMouseY = 0, + onPointerDownPointerX = 0, onPointerDownPointerY = 0, + onPointerDownLon = 0, onPointerDownLat = 0, lon = 90, onMouseDownLon = 0, lat = 0, onMouseDownLat = 0, phi = 0, theta = 0,
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/css2d_label.html
@@ -46,7 +46,7 @@ <script> - var camera, scene, renderer, labelRenderer; + var camera, scene, scene2, renderer, labelRenderer; var controls; var clock = new THREE.Clock(); var textureLoader = new THREE.TextureLoader();
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/css3d_panorama_deviceorientation.html
@@ -39,6 +39,7 @@ <script> var camera, scene, renderer; + var controls; var geometry, material, mesh; init();
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/software_lines_splines.html
@@ -59,7 +59,7 @@ windowHalfX = window.innerWidth / 2, windowHalfY = window.innerHeight / 2, - camera, scene, renderer, material; + camera, scene, renderer, material, stats; init(); animate();
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_geometry_spline_editor.html
@@ -53,7 +53,7 @@ }; var container, stats; - var camera, scene, renderer; + var camera, scene, renderer, spotlight; var splineHelperObjects = [], splineOutline; var splinePointsLength = 4; var positions = [];
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_gpgpu_water.html
@@ -531,9 +531,9 @@ var uniforms = heightmapVariable.material.uniforms; if ( mouseMoved ) { - this.raycaster.setFromCamera( mouseCoords, camera ); + raycaster.setFromCamera( mouseCoords, camera ); - var intersects = this.raycaster.intersectObject( meshRay ); + var intersects = raycaster.intersectObject( meshRay ); if ( intersects.length > 0 ) { var point = intersects[ 0 ].point;
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_loader_ctm.html
@@ -64,6 +64,7 @@ var textureLoader = new THREE.TextureLoader(); var cubeTextureLoader = new THREE.CubeTextureLoader(); + var reflectionCube; document.addEventListener('mousemove', onDocumentMouseMove, false);
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_marchingcubes.html
@@ -100,6 +100,8 @@ var effectController; + var controls; + var time = 0; var clock = new THREE.Clock();
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_materials_curvature.html
@@ -79,6 +79,8 @@ var camera, scene, renderer; + var controls; + var ninjaMeshRaw, curvatureAttribute, bufferGeo; init();
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_modifier_subdivision.html
@@ -29,7 +29,7 @@ var camera, controls, scene, renderer; - var cube, mesh, material; + var cube, mesh, material, geometry, smooth, group; // Create new object by parameters
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_modifier_tessellation.html
@@ -90,6 +90,8 @@ var renderer, scene, camera, stats; + var controls; + var mesh, uniforms; var WIDTH = window.innerWidth,
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_nearestneighbour.html
@@ -76,6 +76,7 @@ var amountOfParticles = 500000, maxDistance = Math.pow( 120, 2 ); var positions, alphas, particles, _particleGeom; + var kdtree; var clock = new THREE.Clock();
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_physics_convex_break.html
@@ -300,9 +300,9 @@ var shape = new Ammo.btConvexHullShape(); for ( var i = 0, il = coords.length; i < il; i+= 3 ) { - this.tempBtVec3_1.setValue( coords[ i ], coords[ i + 1 ], coords[ i + 2 ] ); + tempBtVec3_1.setValue( coords[ i ], coords[ i + 1 ], coords[ i + 2 ] ); var lastOne = ( i >= ( il - 3 ) ); - shape.addPoint( this.tempBtVec3_1, lastOne ); + shape.addPoint( tempBtVec3_1, lastOne ); } return shape;
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_physics_terrain.html
@@ -204,7 +204,7 @@ // Create the terrain body - var groundShape = this.createTerrainShape( heightData ); + var groundShape = createTerrainShape( heightData ); var groundTransform = new Ammo.btTransform(); groundTransform.setIdentity(); // Shifts the terrain, since bullet re-centers it on its bounding box.
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_postprocessing_afterimage.html
@@ -32,7 +32,13 @@ var camera, scene, renderer, composer; var mesh, light; - var afterimagePass, enable = true; + var afterimagePass; + + var params = { + + enable: true + + }; init(); createGUI(); @@ -73,7 +79,7 @@ var gui = new dat.GUI( { name: 'Damp setting' } ); gui.add( afterimagePass.uniforms[ "damp" ], 'value', 0, 1 ).step( 0.001 ); - gui.add( this, 'enable' ); + gui.add( params, 'enable' ); } @@ -94,7 +100,7 @@ mesh.rotation.x += 0.005; mesh.rotation.y += 0.01; - if( enable ){ + if( params.enable ){ composer.render();
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_postprocessing_procedural.html
@@ -81,8 +81,10 @@ <script> - var camera, postScene, renderer, postMaterial, noiseRandom1DMaterial, noiseRandon2DMaterial, noiseRandom3DMaterial, postQuad; + var camera, postCamera, postScene, renderer; + var postMaterial, noiseRandom1DMaterial, noiseRandom2DMaterial, noiseRandom3DMaterial, postQuad; var gui, stats, texture; + var index = 0; var params = { procedure: 'noiseRandom3D' }; @@ -149,11 +151,9 @@ function animate() { - this.index = this.index || 0; - requestAnimationFrame( animate ); - this.index ++; + index ++; switch ( params.procedure ) {
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_postprocessing_rgb_halftone.html
@@ -60,7 +60,7 @@ } // setup - var wrapper, renderer, clock, camera, controls, stats; + var wrapper, renderer, clock, camera, controls, stats, rotationSpeed; wrapper = document.createElement( 'div' ); renderer = new THREE.WebGLRenderer();
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_postprocessing_taa.html
@@ -56,6 +56,7 @@ var camera, scene, renderer, composer, copyPass, taaRenderPass, renderPass; var gui, stats, texture; + var index = 0; var param = { TAAEnabled: "1", TAASampleLevel: 0 }; @@ -180,13 +181,11 @@ function animate() { - this.index = this.index || 0; - requestAnimationFrame( animate ); - this.index ++; + index ++; - if( Math.round( this.index / 200 ) % 2 === 0 ) { + if( Math.round( index / 200 ) % 2 === 0 ) { for ( var i = 0; i < scene.children.length; i ++ ) { var child = scene.children[ i ];
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_raycast_texture.html
@@ -73,7 +73,7 @@ <script src="../build/three.js"></script> <script> - CanvasTexture = function ( parentTexture ) { + var CanvasTexture = function ( parentTexture ) { this._canvas = document.createElement( "canvas" ); this._canvas.width = this._canvas.height = 1024; @@ -183,9 +183,6 @@ } - </script> - <script> - var width = window.innerWidth; var height = window.innerHeight;
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_refraction.html
@@ -47,7 +47,7 @@ if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - var scene, camera, clock, renderer, refractor; + var scene, camera, clock, renderer, refractor, controls; init();
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_simple_gi.html
@@ -163,7 +163,7 @@ // - var camera, scene, renderer; + var camera, scene, renderer, controls; init(); animate();
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_tiled_forward.html
@@ -171,7 +171,7 @@ // Screen rectangle bounds from light sphere's world AABB var lightBounds = function () { - v = new THREE.Vector3(); + var v = new THREE.Vector3(); return function ( camera, pos, r ) { var minX = State.width, maxX = 0, minY = State.height, maxY = 0, hw = State.width / 2, hh = State.height / 2; @@ -224,7 +224,7 @@ var stats = new Stats(); container.appendChild( stats.dom ); - controls = new THREE.OrbitControls( camera, renderer.domElement ); + var controls = new THREE.OrbitControls( camera, renderer.domElement ); controls.minDistance = 120; controls.maxDistance = 320;
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_water.html
@@ -49,7 +49,7 @@ if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - var scene, camera, clock, renderer, water; + var scene, camera, clock, renderer, controls, water; var torusKnot;
true
Other
mrdoob
three.js
5cd646f027121af24bc6fe245487dbf4f71c3639.json
fix undefined variable problems
examples/webgl_water_flowmap.html
@@ -49,7 +49,7 @@ if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - var scene, camera, renderer, water; + var scene, camera, renderer, controls, water; init(); animate();
true
Other
mrdoob
three.js
524571cfa1da7a789cadb00637bb69a5431039b1.json
Add normalized arg to constructor
docs/api/en/core/InstancedBufferAttribute.html
@@ -17,7 +17,7 @@ <h1>[name]</h1> </p> <h2>Constructor</h2> - <h3>[name]( [param:TypedArray array], [param:Integer itemSize], [param:Number meshPerAttribute] )</h3> + <h3>[name]( [param:TypedArray array], [param:Integer itemSize], [param:Boolean normalized], [param:Number meshPerAttribute] )</h3> <p> </p>
true
Other
mrdoob
three.js
524571cfa1da7a789cadb00637bb69a5431039b1.json
Add normalized arg to constructor
src/core/InstancedBufferAttribute.js
@@ -4,9 +4,19 @@ import { BufferAttribute } from './BufferAttribute.js'; * @author benaadams / https://twitter.com/ben_a_adams */ -function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) { +function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) { - BufferAttribute.call( this, array, itemSize ); + if ( typeof ( normalized ) === 'number' ) { + + meshPerAttribute = normalized; + + normalized = false; + + console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' ); + + } + + BufferAttribute.call( this, array, itemSize, normalized ); this.meshPerAttribute = meshPerAttribute || 1;
true
Other
mrdoob
three.js
8be4a88a71ca0abc8dab720f261c86e4f91ee6ea.json
Save animations of MD2 files
editor/js/Loader.js
@@ -347,6 +347,7 @@ var Loader = function ( editor ) { var mesh = new THREE.Mesh( geometry, material ); mesh.mixer = new THREE.AnimationMixer( mesh ); mesh.name = filename; + editor.addAnimation( mesh, geometry.animations ); editor.execute( new AddObjectCommand( mesh ) );
false
Other
mrdoob
three.js
0b3150de61ba4f6642dcad26572b338e84297bc2.json
Add vertexTangents to docs and typings.
docs/api/en/materials/Material.html
@@ -261,6 +261,13 @@ <h3>[property:Integer vertexColors]</h3> Other options are [page:Materials THREE.VertexColors] and [page:Materials THREE.FaceColors]. </p> + <h3>[property:Boolean vertexTangents]</h3> + <p> + Defines whether precomputed vertex tangents, which must be provided in a vec4 "tangent" attribute, + are used. When disabled, tangents are derived automatically. Using precomputed tangents will give + more accurate normal map details in some cases, such as with mirrored UVs. Default is false. + </p> + <h3>[property:Boolean visible]</h3> <p> Defines whether this material is visible. Default is *true*.
true
Other
mrdoob
three.js
0b3150de61ba4f6642dcad26572b338e84297bc2.json
Add vertexTangents to docs and typings.
src/materials/Material.d.ts
@@ -44,6 +44,7 @@ export interface MaterialParameters { side?: Side; transparent?: boolean; vertexColors?: Colors; + vertexTangents?: boolean; visible?: boolean; } @@ -234,6 +235,11 @@ export class Material extends EventDispatcher { */ vertexColors: Colors; + /** + * Defines whether precomputed vertex tangents are used. Default is false. + */ + vertexTangents: boolean; + /** * Defines whether this material is visible. Default is true. */
true