提交 6067f895 编写于 作者: M Mugen87

Merge branch 'dev' into quickhull

......@@ -15514,43 +15514,46 @@
}
Camera.prototype = Object.create( Object3D.prototype );
Camera.prototype.constructor = Camera;
Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
Camera.prototype.isCamera = true;
constructor: Camera,
Camera.prototype.getWorldDirection = function () {
isCamera: true,
var quaternion = new Quaternion();
copy: function ( source ) {
return function getWorldDirection( optionalTarget ) {
Object3D.prototype.copy.call( this, source );
var result = optionalTarget || new Vector3();
this.matrixWorldInverse.copy( source.matrixWorldInverse );
this.projectionMatrix.copy( source.projectionMatrix );
this.getWorldQuaternion( quaternion );
return this;
return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
},
};
getWorldDirection: function () {
}();
var quaternion = new Quaternion();
Camera.prototype.clone = function () {
return function getWorldDirection( optionalTarget ) {
return new this.constructor().copy( this );
var result = optionalTarget || new Vector3();
};
this.getWorldQuaternion( quaternion );
Camera.prototype.copy = function ( source ) {
return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
Object3D.prototype.copy.call( this, source );
};
this.matrixWorldInverse.copy( source.matrixWorldInverse );
this.projectionMatrix.copy( source.projectionMatrix );
}(),
return this;
clone: function () {
};
return new this.constructor().copy( this );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
......@@ -15711,7 +15714,7 @@
},
clearViewOffset: function() {
clearViewOffset: function () {
this.view = null;
this.updateProjectionMatrix();
......@@ -20815,6 +20818,8 @@
// update camera matrices and frustum
camera.onBeforeRender( _this );
if ( camera.parent === null ) camera.updateMatrixWorld();
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
......@@ -20963,6 +20968,7 @@
// opaque pass (front-to-back order)
state.setBlending( NoBlending );
if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
// transparent pass (back-to-front order)
......@@ -20990,6 +20996,14 @@
state.buffers.depth.setMask( true );
state.buffers.color.setMask( true );
if ( camera.isArrayCamera && camera.enabled ) {
_this.setScissorTest( false );
}
camera.onAfterRender( _this );
// _gl.finish();
};
......@@ -21156,22 +21170,30 @@
object.onBeforeRender( _this, scene, camera, geometry, material, group );
object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
if ( camera.isArrayCamera && camera.enabled ) {
if ( object.isImmediateRenderObject ) {
var cameras = camera.cameras;
state.setMaterial( material );
for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
var program = setProgram( camera, scene.fog, material, object );
var camera2 = cameras[ j ];
var bounds = camera2.bounds;
_this.setViewport(
bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
);
_this.setScissor(
bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
);
_this.setScissorTest( true );
renderObject( object, scene, camera2, geometry, material, group );
_currentGeometryProgram = '';
renderObjectImmediate( object, program, material );
}
} else {
_this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
renderObject( object, scene, camera, geometry, material, group );
}
......@@ -21181,6 +21203,29 @@
}
function renderObject( object, scene, camera, geometry, material, group ) {
object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
if ( object.isImmediateRenderObject ) {
state.setMaterial( material );
var program = setProgram( camera, scene.fog, material, object );
_currentGeometryProgram = '';
renderObjectImmediate( object, program, material );
} else {
_this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
}
}
function initMaterial( material, fog, object ) {
var materialProperties = properties.get( material );
......@@ -23261,8 +23306,6 @@
Mesh.call( this, geometry, material );
if ( this.material.skinning === false ) console.warn( 'THREE.SkinnedMesh: Material must have skinning set to true.', this.material );
this.type = 'SkinnedMesh';
this.bindMode = 'attached';
......@@ -26762,11 +26805,9 @@
}
if (options.extrudeMaterial !== undefined){
scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
}
scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
}
......@@ -35717,6 +35758,27 @@
CubeCamera.prototype = Object.create( Object3D.prototype );
CubeCamera.prototype.constructor = CubeCamera;
/**
* @author mrdoob / http://mrdoob.com/
*/
function ArrayCamera( array ) {
PerspectiveCamera.call( this );
this.enabled = false;
this.cameras = array || [];
}
ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
constructor: ArrayCamera,
isArrayCamera: true
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
......@@ -39485,6 +39547,7 @@
if ( this.autoStart && ! this.running ) {
this.start();
return 0;
}
......@@ -43112,6 +43175,7 @@
exports.PerspectiveCamera = PerspectiveCamera;
exports.OrthographicCamera = OrthographicCamera;
exports.CubeCamera = CubeCamera;
exports.ArrayCamera = ArrayCamera;
exports.Camera = Camera;
exports.AudioListener = AudioListener;
exports.PositionalAudio = PositionalAudio;
......
此差异已折叠。
......@@ -15508,43 +15508,46 @@ function Camera() {
}
Camera.prototype = Object.create( Object3D.prototype );
Camera.prototype.constructor = Camera;
Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
Camera.prototype.isCamera = true;
constructor: Camera,
Camera.prototype.getWorldDirection = function () {
isCamera: true,
var quaternion = new Quaternion();
copy: function ( source ) {
return function getWorldDirection( optionalTarget ) {
Object3D.prototype.copy.call( this, source );
var result = optionalTarget || new Vector3();
this.matrixWorldInverse.copy( source.matrixWorldInverse );
this.projectionMatrix.copy( source.projectionMatrix );
this.getWorldQuaternion( quaternion );
return this;
return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
},
};
getWorldDirection: function () {
}();
var quaternion = new Quaternion();
Camera.prototype.clone = function () {
return function getWorldDirection( optionalTarget ) {
return new this.constructor().copy( this );
var result = optionalTarget || new Vector3();
};
this.getWorldQuaternion( quaternion );
Camera.prototype.copy = function ( source ) {
return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
Object3D.prototype.copy.call( this, source );
};
this.matrixWorldInverse.copy( source.matrixWorldInverse );
this.projectionMatrix.copy( source.projectionMatrix );
}(),
return this;
clone: function () {
};
return new this.constructor().copy( this );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
......@@ -15705,7 +15708,7 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ),
},
clearViewOffset: function() {
clearViewOffset: function () {
this.view = null;
this.updateProjectionMatrix();
......@@ -20809,6 +20812,8 @@ function WebGLRenderer( parameters ) {
// update camera matrices and frustum
camera.onBeforeRender( _this );
if ( camera.parent === null ) camera.updateMatrixWorld();
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
......@@ -20957,6 +20962,7 @@ function WebGLRenderer( parameters ) {
// opaque pass (front-to-back order)
state.setBlending( NoBlending );
if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
// transparent pass (back-to-front order)
......@@ -20984,6 +20990,14 @@ function WebGLRenderer( parameters ) {
state.buffers.depth.setMask( true );
state.buffers.color.setMask( true );
if ( camera.isArrayCamera && camera.enabled ) {
_this.setScissorTest( false );
}
camera.onAfterRender( _this );
// _gl.finish();
};
......@@ -21150,22 +21164,30 @@ function WebGLRenderer( parameters ) {
object.onBeforeRender( _this, scene, camera, geometry, material, group );
object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
if ( camera.isArrayCamera && camera.enabled ) {
if ( object.isImmediateRenderObject ) {
var cameras = camera.cameras;
state.setMaterial( material );
for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
var program = setProgram( camera, scene.fog, material, object );
var camera2 = cameras[ j ];
var bounds = camera2.bounds;
_this.setViewport(
bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
);
_this.setScissor(
bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
);
_this.setScissorTest( true );
renderObject( object, scene, camera2, geometry, material, group );
_currentGeometryProgram = '';
renderObjectImmediate( object, program, material );
}
} else {
_this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
renderObject( object, scene, camera, geometry, material, group );
}
......@@ -21175,6 +21197,29 @@ function WebGLRenderer( parameters ) {
}
function renderObject( object, scene, camera, geometry, material, group ) {
object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
if ( object.isImmediateRenderObject ) {
state.setMaterial( material );
var program = setProgram( camera, scene.fog, material, object );
_currentGeometryProgram = '';
renderObjectImmediate( object, program, material );
} else {
_this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
}
}
function initMaterial( material, fog, object ) {
var materialProperties = properties.get( material );
......@@ -23255,8 +23300,6 @@ function SkinnedMesh( geometry, material ) {
Mesh.call( this, geometry, material );
if ( this.material.skinning === false ) console.warn( 'THREE.SkinnedMesh: Material must have skinning set to true.', this.material );
this.type = 'SkinnedMesh';
this.bindMode = 'attached';
......@@ -26756,11 +26799,9 @@ ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
}
if (options.extrudeMaterial !== undefined){
scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
}
scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
}
......@@ -35711,6 +35752,27 @@ function CubeCamera( near, far, cubeResolution ) {
CubeCamera.prototype = Object.create( Object3D.prototype );
CubeCamera.prototype.constructor = CubeCamera;
/**
* @author mrdoob / http://mrdoob.com/
*/
function ArrayCamera( array ) {
PerspectiveCamera.call( this );
this.enabled = false;
this.cameras = array || [];
}
ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
constructor: ArrayCamera,
isArrayCamera: true
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
......@@ -39479,6 +39541,7 @@ Object.assign( Clock.prototype, {
if ( this.autoStart && ! this.running ) {
this.start();
return 0;
}
......@@ -43047,4 +43110,4 @@ function CanvasRenderer() {
}
export { WebGLRenderTargetCube, WebGLRenderTarget, WebGLRenderer, ShaderLib, UniformsLib, UniformsUtils, ShaderChunk, FogExp2, Fog, Scene, LensFlare, Sprite, LOD, SkinnedMesh, Skeleton, Bone, Mesh, LineSegments, LineLoop, Line, Points, Group, VideoTexture, DataTexture, CompressedTexture, CubeTexture, CanvasTexture, DepthTexture, Texture, CompressedTextureLoader, DataTextureLoader, CubeTextureLoader, TextureLoader, ObjectLoader, MaterialLoader, BufferGeometryLoader, DefaultLoadingManager, LoadingManager, JSONLoader, ImageLoader, FontLoader, FileLoader, Loader, Cache, AudioLoader, SpotLightShadow, SpotLight, PointLight, RectAreaLight, HemisphereLight, DirectionalLightShadow, DirectionalLight, AmbientLight, LightShadow, Light, StereoCamera, PerspectiveCamera, OrthographicCamera, CubeCamera, Camera, AudioListener, PositionalAudio, AudioContext, AudioAnalyser, Audio, VectorKeyframeTrack, StringKeyframeTrack, QuaternionKeyframeTrack, NumberKeyframeTrack, ColorKeyframeTrack, BooleanKeyframeTrack, PropertyMixer, PropertyBinding, KeyframeTrack, AnimationUtils, AnimationObjectGroup, AnimationMixer, AnimationClip, Uniform, InstancedBufferGeometry, BufferGeometry, GeometryIdCount, Geometry, InterleavedBufferAttribute, InstancedInterleavedBuffer, InterleavedBuffer, InstancedBufferAttribute, Face3, Object3D, Raycaster, Layers, EventDispatcher, Clock, QuaternionLinearInterpolant, LinearInterpolant, DiscreteInterpolant, CubicInterpolant, Interpolant, Triangle, _Math as Math, Spherical, Cylindrical, Plane, Frustum, Sphere, Ray, Matrix4, Matrix3, Box3, Box2, Line3, Euler, Vector4, Vector3, Vector2, Quaternion, Color, MorphBlendMesh, ImmediateRenderObject, VertexNormalsHelper, SpotLightHelper, SkeletonHelper, PointLightHelper, RectAreaLightHelper, HemisphereLightHelper, GridHelper, PolarGridHelper, FaceNormalsHelper, DirectionalLightHelper, CameraHelper, BoxHelper, ArrowHelper, AxisHelper, CatmullRomCurve3, CubicBezierCurve3, QuadraticBezierCurve3, LineCurve3, ArcCurve, EllipseCurve, SplineCurve, CubicBezierCurve, QuadraticBezierCurve, LineCurve, Shape, Path, ShapePath, Font, CurvePath, Curve, ShapeUtils, SceneUtils, WireframeGeometry, ParametricGeometry, ParametricBufferGeometry, TetrahedronGeometry, TetrahedronBufferGeometry, OctahedronGeometry, OctahedronBufferGeometry, IcosahedronGeometry, IcosahedronBufferGeometry, DodecahedronGeometry, DodecahedronBufferGeometry, PolyhedronGeometry, PolyhedronBufferGeometry, TubeGeometry, TubeBufferGeometry, TorusKnotGeometry, TorusKnotBufferGeometry, TorusGeometry, TorusBufferGeometry, TextGeometry, TextBufferGeometry, SphereGeometry, SphereBufferGeometry, RingGeometry, RingBufferGeometry, PlaneGeometry, PlaneBufferGeometry, LatheGeometry, LatheBufferGeometry, ShapeGeometry, ShapeBufferGeometry, ExtrudeGeometry, ExtrudeBufferGeometry, EdgesGeometry, ConeGeometry, ConeBufferGeometry, CylinderGeometry, CylinderBufferGeometry, CircleGeometry, CircleBufferGeometry, BoxGeometry, BoxBufferGeometry, ShadowMaterial, SpriteMaterial, RawShaderMaterial, ShaderMaterial, PointsMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshPhongMaterial, MeshToonMaterial, MeshNormalMaterial, MeshLambertMaterial, MeshDepthMaterial, MeshBasicMaterial, LineDashedMaterial, LineBasicMaterial, Material, Float64BufferAttribute, Float32BufferAttribute, Uint32BufferAttribute, Int32BufferAttribute, Uint16BufferAttribute, Int16BufferAttribute, Uint8ClampedBufferAttribute, Uint8BufferAttribute, Int8BufferAttribute, BufferAttribute, REVISION, MOUSE, CullFaceNone, CullFaceBack, CullFaceFront, CullFaceFrontBack, FrontFaceDirectionCW, FrontFaceDirectionCCW, BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, FrontSide, BackSide, DoubleSide, FlatShading, SmoothShading, NoColors, FaceColors, VertexColors, NoBlending, NormalBlending, AdditiveBlending, SubtractiveBlending, MultiplyBlending, CustomBlending, AddEquation, SubtractEquation, ReverseSubtractEquation, MinEquation, MaxEquation, ZeroFactor, OneFactor, SrcColorFactor, OneMinusSrcColorFactor, SrcAlphaFactor, OneMinusSrcAlphaFactor, DstAlphaFactor, OneMinusDstAlphaFactor, DstColorFactor, OneMinusDstColorFactor, SrcAlphaSaturateFactor, NeverDepth, AlwaysDepth, LessDepth, LessEqualDepth, EqualDepth, GreaterEqualDepth, GreaterDepth, NotEqualDepth, MultiplyOperation, MixOperation, AddOperation, NoToneMapping, LinearToneMapping, ReinhardToneMapping, Uncharted2ToneMapping, CineonToneMapping, UVMapping, CubeReflectionMapping, CubeRefractionMapping, EquirectangularReflectionMapping, EquirectangularRefractionMapping, SphericalReflectionMapping, CubeUVReflectionMapping, CubeUVRefractionMapping, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter, LinearFilter, LinearMipMapNearestFilter, LinearMipMapLinearFilter, UnsignedByteType, ByteType, ShortType, UnsignedShortType, IntType, UnsignedIntType, FloatType, HalfFloatType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedInt248Type, AlphaFormat, RGBFormat, RGBAFormat, LuminanceFormat, LuminanceAlphaFormat, RGBEFormat, DepthFormat, DepthStencilFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, LoopOnce, LoopRepeat, LoopPingPong, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, ZeroCurvatureEnding, ZeroSlopeEnding, WrapAroundEnding, TrianglesDrawMode, TriangleStripDrawMode, TriangleFanDrawMode, LinearEncoding, sRGBEncoding, GammaEncoding, RGBEEncoding, LogLuvEncoding, RGBM7Encoding, RGBM16Encoding, RGBDEncoding, BasicDepthPacking, RGBADepthPacking, BoxGeometry as CubeGeometry, Face4, LineStrip, LinePieces, MeshFaceMaterial, MultiMaterial, PointCloud, Particle, ParticleSystem, PointCloudMaterial, ParticleBasicMaterial, ParticleSystemMaterial, Vertex, DynamicBufferAttribute, Int8Attribute, Uint8Attribute, Uint8ClampedAttribute, Int16Attribute, Uint16Attribute, Int32Attribute, Uint32Attribute, Float32Attribute, Float64Attribute, ClosedSplineCurve3, SplineCurve3, Spline, BoundingBoxHelper, EdgesHelper, WireframeHelper, XHRLoader, BinaryTextureLoader, GeometryUtils, ImageUtils, Projector, CanvasRenderer };
export { WebGLRenderTargetCube, WebGLRenderTarget, WebGLRenderer, ShaderLib, UniformsLib, UniformsUtils, ShaderChunk, FogExp2, Fog, Scene, LensFlare, Sprite, LOD, SkinnedMesh, Skeleton, Bone, Mesh, LineSegments, LineLoop, Line, Points, Group, VideoTexture, DataTexture, CompressedTexture, CubeTexture, CanvasTexture, DepthTexture, Texture, CompressedTextureLoader, DataTextureLoader, CubeTextureLoader, TextureLoader, ObjectLoader, MaterialLoader, BufferGeometryLoader, DefaultLoadingManager, LoadingManager, JSONLoader, ImageLoader, FontLoader, FileLoader, Loader, Cache, AudioLoader, SpotLightShadow, SpotLight, PointLight, RectAreaLight, HemisphereLight, DirectionalLightShadow, DirectionalLight, AmbientLight, LightShadow, Light, StereoCamera, PerspectiveCamera, OrthographicCamera, CubeCamera, ArrayCamera, Camera, AudioListener, PositionalAudio, AudioContext, AudioAnalyser, Audio, VectorKeyframeTrack, StringKeyframeTrack, QuaternionKeyframeTrack, NumberKeyframeTrack, ColorKeyframeTrack, BooleanKeyframeTrack, PropertyMixer, PropertyBinding, KeyframeTrack, AnimationUtils, AnimationObjectGroup, AnimationMixer, AnimationClip, Uniform, InstancedBufferGeometry, BufferGeometry, GeometryIdCount, Geometry, InterleavedBufferAttribute, InstancedInterleavedBuffer, InterleavedBuffer, InstancedBufferAttribute, Face3, Object3D, Raycaster, Layers, EventDispatcher, Clock, QuaternionLinearInterpolant, LinearInterpolant, DiscreteInterpolant, CubicInterpolant, Interpolant, Triangle, _Math as Math, Spherical, Cylindrical, Plane, Frustum, Sphere, Ray, Matrix4, Matrix3, Box3, Box2, Line3, Euler, Vector4, Vector3, Vector2, Quaternion, Color, MorphBlendMesh, ImmediateRenderObject, VertexNormalsHelper, SpotLightHelper, SkeletonHelper, PointLightHelper, RectAreaLightHelper, HemisphereLightHelper, GridHelper, PolarGridHelper, FaceNormalsHelper, DirectionalLightHelper, CameraHelper, BoxHelper, ArrowHelper, AxisHelper, CatmullRomCurve3, CubicBezierCurve3, QuadraticBezierCurve3, LineCurve3, ArcCurve, EllipseCurve, SplineCurve, CubicBezierCurve, QuadraticBezierCurve, LineCurve, Shape, Path, ShapePath, Font, CurvePath, Curve, ShapeUtils, SceneUtils, WireframeGeometry, ParametricGeometry, ParametricBufferGeometry, TetrahedronGeometry, TetrahedronBufferGeometry, OctahedronGeometry, OctahedronBufferGeometry, IcosahedronGeometry, IcosahedronBufferGeometry, DodecahedronGeometry, DodecahedronBufferGeometry, PolyhedronGeometry, PolyhedronBufferGeometry, TubeGeometry, TubeBufferGeometry, TorusKnotGeometry, TorusKnotBufferGeometry, TorusGeometry, TorusBufferGeometry, TextGeometry, TextBufferGeometry, SphereGeometry, SphereBufferGeometry, RingGeometry, RingBufferGeometry, PlaneGeometry, PlaneBufferGeometry, LatheGeometry, LatheBufferGeometry, ShapeGeometry, ShapeBufferGeometry, ExtrudeGeometry, ExtrudeBufferGeometry, EdgesGeometry, ConeGeometry, ConeBufferGeometry, CylinderGeometry, CylinderBufferGeometry, CircleGeometry, CircleBufferGeometry, BoxGeometry, BoxBufferGeometry, ShadowMaterial, SpriteMaterial, RawShaderMaterial, ShaderMaterial, PointsMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshPhongMaterial, MeshToonMaterial, MeshNormalMaterial, MeshLambertMaterial, MeshDepthMaterial, MeshBasicMaterial, LineDashedMaterial, LineBasicMaterial, Material, Float64BufferAttribute, Float32BufferAttribute, Uint32BufferAttribute, Int32BufferAttribute, Uint16BufferAttribute, Int16BufferAttribute, Uint8ClampedBufferAttribute, Uint8BufferAttribute, Int8BufferAttribute, BufferAttribute, REVISION, MOUSE, CullFaceNone, CullFaceBack, CullFaceFront, CullFaceFrontBack, FrontFaceDirectionCW, FrontFaceDirectionCCW, BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, FrontSide, BackSide, DoubleSide, FlatShading, SmoothShading, NoColors, FaceColors, VertexColors, NoBlending, NormalBlending, AdditiveBlending, SubtractiveBlending, MultiplyBlending, CustomBlending, AddEquation, SubtractEquation, ReverseSubtractEquation, MinEquation, MaxEquation, ZeroFactor, OneFactor, SrcColorFactor, OneMinusSrcColorFactor, SrcAlphaFactor, OneMinusSrcAlphaFactor, DstAlphaFactor, OneMinusDstAlphaFactor, DstColorFactor, OneMinusDstColorFactor, SrcAlphaSaturateFactor, NeverDepth, AlwaysDepth, LessDepth, LessEqualDepth, EqualDepth, GreaterEqualDepth, GreaterDepth, NotEqualDepth, MultiplyOperation, MixOperation, AddOperation, NoToneMapping, LinearToneMapping, ReinhardToneMapping, Uncharted2ToneMapping, CineonToneMapping, UVMapping, CubeReflectionMapping, CubeRefractionMapping, EquirectangularReflectionMapping, EquirectangularRefractionMapping, SphericalReflectionMapping, CubeUVReflectionMapping, CubeUVRefractionMapping, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter, LinearFilter, LinearMipMapNearestFilter, LinearMipMapLinearFilter, UnsignedByteType, ByteType, ShortType, UnsignedShortType, IntType, UnsignedIntType, FloatType, HalfFloatType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedInt248Type, AlphaFormat, RGBFormat, RGBAFormat, LuminanceFormat, LuminanceAlphaFormat, RGBEFormat, DepthFormat, DepthStencilFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, LoopOnce, LoopRepeat, LoopPingPong, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, ZeroCurvatureEnding, ZeroSlopeEnding, WrapAroundEnding, TrianglesDrawMode, TriangleStripDrawMode, TriangleFanDrawMode, LinearEncoding, sRGBEncoding, GammaEncoding, RGBEEncoding, LogLuvEncoding, RGBM7Encoding, RGBM16Encoding, RGBDEncoding, BasicDepthPacking, RGBADepthPacking, BoxGeometry as CubeGeometry, Face4, LineStrip, LinePieces, MeshFaceMaterial, MultiMaterial, PointCloud, Particle, ParticleSystem, PointCloudMaterial, ParticleBasicMaterial, ParticleSystemMaterial, Vertex, DynamicBufferAttribute, Int8Attribute, Uint8Attribute, Uint8ClampedAttribute, Int16Attribute, Uint16Attribute, Int32Attribute, Uint32Attribute, Float32Attribute, Float64Attribute, ClosedSplineCurve3, SplineCurve3, Spline, BoundingBoxHelper, EdgesHelper, WireframeHelper, XHRLoader, BinaryTextureLoader, GeometryUtils, ImageUtils, Projector, CanvasRenderer };
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<base href="../../" />
<script src="list.js"></script>
<script src="page.js"></script>
<link type="text/css" rel="stylesheet" href="page.css" />
</head>
<body>
[page:BufferGeometry] &rarr;
<h1>[name]</h1>
<div class="desc">Creates extruded BufferGeometry from a path shape.</div>
<iframe id="scene" src="scenes/geometry-browser.html#ExtrudeBufferGeometry"></iframe>
<script>
// iOS iframe auto-resize workaround
if ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) {
var scene = document.getElementById( 'scene' );
scene.style.width = getComputedStyle( scene ).width;
scene.style.height = getComputedStyle( scene ).height;
scene.setAttribute( 'scrolling', 'no' );
}
</script>
<h2>Example</h2>
<code>
var length = 12, width = 8;
var shape = new THREE.Shape();
shape.moveTo( 0,0 );
shape.lineTo( 0, width );
shape.lineTo( length, width );
shape.lineTo( length, 0 );
shape.lineTo( 0, 0 );
var extrudeSettings = {
steps: 2,
amount: 16,
bevelEnabled: true,
bevelThickness: 1,
bevelSize: 1,
bevelSegments: 1
};
var geometry = new THREE.ExtrudeBufferGeometry( shape, extrudeSettings );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var mesh = new THREE.Mesh( geometry, material ) ;
scene.add( mesh );
</code>
<h2>Constructor</h2>
<h3>[name]([page:Array shapes], [page:Object options])</h3>
<div>
shapes — Shape or an array of shapes. <br />
options — Object that can contain the following parameters.
<ul>
<li>curveSegments — int. Number of points on the curves. Default is 12.</li>
<li>steps — int. Number of points used for subdividing segments along the depth of the extruded spline. Default is 1.</li>
<li>amount — int. Depth to extrude the shape. Default is 100.</li>
<li>bevelEnabled — bool. Apply beveling to the shape. Default is true.</li>
<li>bevelThickness — float. How deep into the original shape the bevel goes. Default is 6.</li>
<li>bevelSize — float. Distance from the shape outline that the bevel extends. Default is bevelThickness - 2.</li>
<li>bevelSegments — int. Number of bevel layers. Default is 3.</li>
<li>extrudePath — THREE.CurvePath. A 3D spline path along which the shape should be extruded (creates Frames if frames aren't defined).</li>
<li>frames — An instance of THREE.TubeGeometry.FrenetFrames containing arrays of tangents, normals, binormals for each step along the extrudePath. </li>
<li>UVGenerator — Object. object that provides UV generator functions</li>
</ul>
</div>
<div>
This object extrudes a 2D shape to a 3D geometry.
</div>
<div>
When creating a Mesh with this geometry, if you'd like to have a separate material used for its face
and its extruded sides, you can use an instance of THREE.MultiMaterial. The first material will be
applied to the face; the second material will be applied to the sides.
</div>
<h2>Properties</h2>
<h2>Methods</h2>
<h3>[method:null addShapeList]([page:Array shapes], [page:Object options])</h3>
<div>
shapes — An Array of shapes to add. <br />
options — Object that can contain the following parameters.
<ul>
<li>curveSegments — int. Number of points on the curves. Default is 12.</li>
<li>steps — int. Number of points used for subdividing segments along the depth of the extruded spline. Default is 1.</li>
<li>amount — int. Depth to extrude the shape. Default is 100.</li>
<li>bevelEnabled — bool. Apply beveling to the shape. Default is true.</li>
<li>bevelThickness — float. How deep into the original shape the bevel goes. Default is 6.</li>
<li>bevelSize — float. Distance from the shape outline that the bevel extends. Default is bevelThickness - 2.</li>
<li>bevelSegments — int. Number of bevel layers. Default is 3.</li>
<li>extrudePath — THREE.CurvePath. A 3D spline path along which the shape should be extruded (creates Frames if frames aren't defined).</li>
<li>frames — An instance of THREE.TubeGeometry.FrenetFrames containing arrays of tangents, normals, binormals for each step along the extrudePath. </li>
<li>UVGenerator — Object. object that provides UV generator functions</li>
</ul>
</div>
<div>Adds the shapes to the list to extrude.</div>
<h3>[method:null addShape]([page:Shape shape], [page:Object options])</h3>
<div>
shape — A shape to add. <br />
options — Object that can contain the following parameters.
<ul>
<li>curveSegments — int. Number of points on the curves. Default is 12.</li>
<li>steps — int. Number of points used for subdividing segments along the depth of the extruded spline. Default is 1.</li>
<li>amount — int. Depth to extrude the shape. Default is 100.</li>
<li>bevelEnabled — bool. Apply beveling to the shape. Default is true.</li>
<li>bevelThickness — float. How deep into the original shape the bevel goes. Default is 6.</li>
<li>bevelSize — float. Distance from the shape outline that the bevel extends. Default is bevelThickness - 2.</li>
<li>bevelSegments — int. Number of bevel layers. Default is 3.</li>
<li>extrudePath — THREE.CurvePath. A 3D spline path along which the shape should be extruded (creates Frames if frames aren't defined).</li>
<li>frames — An instance of THREE.TubeGeometry.FrenetFrames containing arrays of tangents, normals, binormals for each step along the extrudePath. </li>
<li>UVGenerator — Object. object that provides UV generator functions</li>
</ul>
</div>
<div>Add the shape to the list to extrude.</div>
<h2>Source</h2>
[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]
</body>
</html>
......@@ -15,7 +15,7 @@
<div class="desc">
A material for shiny surfaces with specular highlights.<br /><br />
The uses a non-physically based [link:https://en.wikipedia.org/wiki/LBlinn-Phong_shading_model Blinn-Phong]
The uses a non-physically based [link:https://en.wikipedia.org/wiki/Blinn-Phong_shading_model Blinn-Phong]
model for calculating reflectance. Unlike the Lambertian model used in the [page:MeshLambertMaterial]
this can simulate shiny surfaces with specular highlights (such as varnished wood).<br /><br />
......
......@@ -12,22 +12,41 @@
<h1>[name]</h1>
<div class="desc">
A loader for loading a *gltf* resource in JSON format.
A loader for *glTF* 2.0 resources.
<br /><br />
The <a href="https://www.khronos.org/gltf">glTF file format</a> is a JSON file format to enable rapid delivery and loading of 3D content.
<a href="https://www.khronos.org/gltf">glTF</a> (GL Transmission Format) is an open format
specification for efficient delivery and loading of 3D content. Assets may be provided either
in JSON (.gltf) or binary (.glb) format. External files store textures (.jpg, .png, ...) and
additional binary data (.bin). A glTF asset may deliver one or more scenes, including meshes,
materials, textures, shaders, skins, skeletons, animations, lights, and/or cameras. Morph target
animations are not yet finalized in the
<a href="https://github.com/KhronosGroup/glTF/tree/master/specification">glTF specification</a>.
</div>
<h2>Notes</h2>
<h2>Extensions</h2>
<div>
When using custom shaders provided within a glTF file [page:THREE.GLTFLoader.Shaders] should be updated on each render loop. See [example:webgl_loader_gltf] demo source code for example usage.
GLTF2Loader supports the following glTF extensions:
</div>
<ul>
<li>
<a target="_blank" href="https://github.com/KhronosGroup/glTF/blob/master/extensions/Khronos/KHR_binary_glTF">
KHR_binary_glTF
</a>
</li>
<li>
<a target="_blank" href="https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_common">
KHR_materials_common
</a>
</li>
</ul>
<h2>Example</h2>
<code>
// Instantiate a loader
var loader = new THREE.GLTFLoader();
var loader = new THREE.GLTF2Loader();
// Load a glTF resource
loader.load( 'models/gltf/duck/duck.gltf', function ( gltf ) {
......@@ -40,7 +59,7 @@
} );
</code>
[example:webgl_loader_gltf]
[example:webgl_loader_gltf2]
<h2>Constructor</h2>
......@@ -88,11 +107,11 @@
[page:String path] — The base path from which to find subsequent glTF resources such as textures, GLSL shaders and .bin data files.<br />
</div>
<div>
Parse a glTF-based <em>JSON</em> structure and fire [page:Function callback] when complete. The argument to [page:Function callback] will be an [page:object] that contains loaded parts: .[page:Scene scene], .[page:Array cameras], .[page:Array animations] and .[page:Array shaders]
Parse a glTF-based <em>JSON</em> structure and fire [page:Function callback] when complete. The argument to [page:Function callback] will be an [page:object] that contains loaded parts: .[page:Scene scene], .[page:Array scenes], .[page:Array cameras], and .[page:Array animations].
</div>
<h2>Source</h2>
[link:https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/GLTFLoader.js examples/js/loaders/GLTFLoader.js]
[link:https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/GLTF2Loader.js examples/js/loaders/GLTF2Loader.js]
</body>
</html>
......@@ -147,6 +147,7 @@ var list = {
[ "DodecahedronGeometry", "api/geometries/DodecahedronGeometry" ],
[ "EdgesGeometry", "api/geometries/EdgesGeometry" ],
[ "ExtrudeGeometry", "api/geometries/ExtrudeGeometry" ],
[ "ExtrudeBufferGeometry", "api/geometries/ExtrudeBufferGeometry" ],
[ "IcosahedronBufferGeometry", "api/geometries/IcosahedronBufferGeometry" ],
[ "IcosahedronGeometry", "api/geometries/IcosahedronGeometry" ],
[ "LatheBufferGeometry", "api/geometries/LatheBufferGeometry" ],
......@@ -349,7 +350,7 @@ var list = {
"Loaders": [
[ "BabylonLoader", "examples/loaders/BabylonLoader" ],
[ "ColladaLoader", "examples/loaders/ColladaLoader" ],
[ "GLTFLoader", "examples/loaders/GLTFLoader" ],
[ "GLTF2Loader", "examples/loaders/GLTF2Loader" ],
[ "MTLLoader", "examples/loaders/MTLLoader" ],
[ "OBJLoader", "examples/loaders/OBJLoader" ],
[ "PCDLoader", "examples/loaders/PCDLoader" ],
......
......@@ -32,7 +32,7 @@ TODO
The key equation to solving this is this formula for the visible height at a given distance:
<code>s
<code>
visible_height = 2 * Math.tan( ( Math.PI / 180 ) * camera.fov / 2 ) * distance_from_camera;
</code>
If we increase the window height by a certain percentage, then what we want is the visible height at all distances
......
......@@ -49,7 +49,7 @@ object.updateMatrix();
You can however update the content of buffers.
</p>
<p>
This means that if you know an attribute of you BufferGeometry will grow, say the number of vertices,
This means that if you know an attribute of your BufferGeometry will grow, say the number of vertices,
you must pre-allocate a buffer large enough to hold any new vertices that may be created. Of
course, this also means that there will be a maximum size for your BufferGeometry - there is
no way to create a BufferGeometry that can efficiently be extended indefinitely.
......@@ -127,10 +127,10 @@ line.geometry.attributes.position.needsUpdate = true; // required after the firs
<h3>[page:Geometry]</h3>
<div>
<p>
The following flag control updating of various geometry attributes. Set flags only
The following flags control updating of various geometry attributes. Set flags only
for attributes that you need to update, updates are costly. Once buffers
change, these flags reset automatically back to false. You need to keep setting them to
true if you wanna keep updating buffers. Note that this applies only to [page:Geometry]
true if you want to keep updating buffers. Note that this applies only to [page:Geometry]
and not to [page:BufferGeometry].
</p>
<code>
......
......@@ -1302,6 +1302,46 @@ var guis = {
},
ExtrudeBufferGeometry: function( mesh ) {
var data = {
steps: 2,
amount: 16,
bevelEnabled: true,
bevelThickness: 1,
bevelSize: 1,
bevelSegments: 1
};
var length = 12, width = 8;
var shape = new THREE.Shape();
shape.moveTo( 0,0 );
shape.lineTo( 0, width );
shape.lineTo( length, width );
shape.lineTo( length, 0 );
shape.lineTo( 0, 0 );
function generateGeometry() {
updateGroupGeometry( mesh,
new THREE.ExtrudeBufferGeometry( shape, data )
);
}
var folder = gui.addFolder( 'THREE.ExtrudeBufferGeometry' );
folder.add( data, 'steps', 1, 10 ).step( 1 ).onChange( generateGeometry );
folder.add( data, 'amount', 1, 20 ).step( 1 ).onChange( generateGeometry );
folder.add( data, 'bevelThickness', 1, 5 ).step( 1 ).onChange( generateGeometry );
folder.add( data, 'bevelSize', 1, 5 ).step( 1 ).onChange( generateGeometry );
folder.add( data, 'bevelSegments', 1, 5 ).step( 1 ).onChange( generateGeometry );
generateGeometry();
},
ConvexGeometry: function( mesh ) {
var data = {
......@@ -1358,6 +1398,7 @@ var guis = {
updateGroupGeometry( mesh,
new THREE.ConvexBufferGeometry( vertices )
);
}
......
......@@ -102,7 +102,7 @@ Sidebar.Script = function ( editor ) {
signals.objectSelected.add( function ( object ) {
if ( object !== null ) {
if ( object !== null && editor.camera !== object ) {
container.setDisplay( 'block' );
......
const electron = require( 'electron' );
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require( 'path' );
const url = require( 'url' );
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow( { webPreferences: {
nodeIntegration: false
} } );
mainWindow.maximize();
mainWindow.setMenu( null );
mainWindow.loadURL( url.format( {
pathname: path.join( __dirname, 'index.html' ),
protocol: 'file:',
slashes: true
} ) );
mainWindow.on( 'closed', function () {
mainWindow = null;
} );
}
app.on( 'ready', createWindow );
app.on( 'window-all-closed', function () {
if ( process.platform !== 'darwin' ) {
app.quit();
}
} );
app.on( 'activate', function () {
if ( mainWindow === null ) {
createWindow();
}
} );
......@@ -89,6 +89,7 @@ var files = {
"webgl_loader_ctm_materials",
"webgl_loader_fbx",
"webgl_loader_gltf",
"webgl_loader_gltf2",
"webgl_loader_json_blender",
"webgl_loader_json_claraio",
"webgl_loader_json_objconverter",
......@@ -117,6 +118,7 @@ var files = {
"webgl_loader_utf8",
"webgl_loader_vrml",
"webgl_loader_vtk",
"webgl_loader_x",
"webgl_lod",
"webgl_marchingcubes",
"webgl_materials",
......
THREE.MirrorRTT = function ( width, height, options ) {
THREE.Mirror.call( this, width, height, options );
this.geometry.setDrawRange( 0, 0 ); // avoid rendering geometry
};
THREE.MirrorRTT.prototype = Object.create( THREE.Mirror.prototype );
......@@ -16,209 +16,211 @@
THREE.Sky = function () {
var skyShader = {
var skyShader = THREE.Sky.SkyShader;
uniforms: {
luminance: { value: 1 },
turbidity: { value: 2 },
rayleigh: { value: 1 },
mieCoefficient: { value: 0.005 },
mieDirectionalG: { value: 0.8 },
sunPosition: { value: new THREE.Vector3() }
},
var skyUniforms = THREE.UniformsUtils.clone( skyShader.uniforms );
vertexShader: [
'uniform vec3 sunPosition;',
'uniform float rayleigh;',
'uniform float turbidity;',
'uniform float mieCoefficient;',
'varying vec3 vWorldPosition;',
'varying vec3 vSunDirection;',
'varying float vSunfade;',
'varying vec3 vBetaR;',
'varying vec3 vBetaM;',
'varying float vSunE;',
'const vec3 up = vec3( 0.0, 1.0, 0.0 );',
// constants for atmospheric scattering
'const float e = 2.71828182845904523536028747135266249775724709369995957;',
'const float pi = 3.141592653589793238462643383279502884197169;',
// wavelength of used primaries, according to preetham
'const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );',
// this pre-calcuation replaces older TotalRayleigh(vec3 lambda) function:
// (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn))
'const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 );',
// mie stuff
// K coefficient for the primaries
'const float v = 4.0;',
'const vec3 K = vec3( 0.686, 0.678, 0.666 );',
// MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K
'const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );',
// earth shadow hack
// cutoffAngle = pi / 1.95;
'const float cutoffAngle = 1.6110731556870734;',
'const float steepness = 1.5;',
'const float EE = 1000.0;',
'float sunIntensity( float zenithAngleCos ) {',
' zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 );',
' return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) );',
'}',
'vec3 totalMie( float T ) {',
' float c = ( 0.2 * T ) * 10E-18;',
' return 0.434 * c * MieConst;',
'}',
'void main() {',
' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );',
' vWorldPosition = worldPosition.xyz;',
' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
' vSunDirection = normalize( sunPosition );',
' vSunE = sunIntensity( dot( vSunDirection, up ) );',
' vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 );',
' float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) );',
// extinction (absorbtion + out scattering)
// rayleigh coefficients
' vBetaR = totalRayleigh * rayleighCoefficient;',
// mie coefficients
' vBetaM = totalMie( turbidity ) * mieCoefficient;',
'}'
].join( '\n' ),
var skyMat = new THREE.ShaderMaterial( {
fragmentShader: skyShader.fragmentShader,
vertexShader: skyShader.vertexShader,
uniforms: skyUniforms,
side: THREE.BackSide
} );
fragmentShader: [
'varying vec3 vWorldPosition;',
'varying vec3 vSunDirection;',
'varying float vSunfade;',
'varying vec3 vBetaR;',
'varying vec3 vBetaM;',
'varying float vSunE;',
var skyGeo = new THREE.SphereBufferGeometry( 450000, 32, 15 );
var skyMesh = new THREE.Mesh( skyGeo, skyMat );
'uniform float luminance;',
'uniform float mieDirectionalG;',
// Expose variables
this.mesh = skyMesh;
this.uniforms = skyUniforms;
'const vec3 cameraPos = vec3( 0.0, 0.0, 0.0 );',
};
// constants for atmospheric scattering
'const float pi = 3.141592653589793238462643383279502884197169;',
THREE.Sky.SkyShader = {
'const float n = 1.0003;', // refractive index of air
'const float N = 2.545E25;', // number of molecules per unit volume for air at
// 288.15K and 1013mb (sea level -45 celsius)
uniforms: {
luminance: { value: 1 },
turbidity: { value: 2 },
rayleigh: { value: 1 },
mieCoefficient: { value: 0.005 },
mieDirectionalG: { value: 0.8 },
sunPosition: { value: new THREE.Vector3() }
},
// optical length at zenith for molecules
'const float rayleighZenithLength = 8.4E3;',
'const float mieZenithLength = 1.25E3;',
'const vec3 up = vec3( 0.0, 1.0, 0.0 );',
// 66 arc seconds -> degrees, and the cosine of that
'const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;',
vertexShader: [
'uniform vec3 sunPosition;',
'uniform float rayleigh;',
'uniform float turbidity;',
'uniform float mieCoefficient;',
// 3.0 / ( 16.0 * pi )
'const float THREE_OVER_SIXTEENPI = 0.05968310365946075;',
// 1.0 / ( 4.0 * pi )
'const float ONE_OVER_FOURPI = 0.07957747154594767;',
'varying vec3 vWorldPosition;',
'varying vec3 vSunDirection;',
'varying float vSunfade;',
'varying vec3 vBetaR;',
'varying vec3 vBetaM;',
'varying float vSunE;',
'const vec3 up = vec3( 0.0, 1.0, 0.0 );',
'float rayleighPhase( float cosTheta ) {',
' return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) );',
'}',
// constants for atmospheric scattering
'const float e = 2.71828182845904523536028747135266249775724709369995957;',
'const float pi = 3.141592653589793238462643383279502884197169;',
// wavelength of used primaries, according to preetham
'const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );',
// this pre-calcuation replaces older TotalRayleigh(vec3 lambda) function:
// (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn))
'const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 );',
// mie stuff
// K coefficient for the primaries
'const float v = 4.0;',
'const vec3 K = vec3( 0.686, 0.678, 0.666 );',
// MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K
'const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );',
// earth shadow hack
// cutoffAngle = pi / 1.95;
'const float cutoffAngle = 1.6110731556870734;',
'const float steepness = 1.5;',
'const float EE = 1000.0;',
'float sunIntensity( float zenithAngleCos ) {',
' zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 );',
' return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) );',
'}',
'vec3 totalMie( float T ) {',
' float c = ( 0.2 * T ) * 10E-18;',
' return 0.434 * c * MieConst;',
'}',
'void main() {',
'float hgPhase( float cosTheta, float g ) {',
' float g2 = pow( g, 2.0 );',
' float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 );',
' return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse );',
'}',
' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );',
' vWorldPosition = worldPosition.xyz;',
// Filmic ToneMapping http://filmicgames.com/archives/75
'const float A = 0.15;',
'const float B = 0.50;',
'const float C = 0.10;',
'const float D = 0.20;',
'const float E = 0.02;',
'const float F = 0.30;',
' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
'const float whiteScale = 1.0748724675633854;', // 1.0 / Uncharted2Tonemap(1000.0)
' vSunDirection = normalize( sunPosition );',
' vSunE = sunIntensity( dot( vSunDirection, up ) );',
' vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 );',
' float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) );',
// extinction (absorbtion + out scattering)
// rayleigh coefficients
' vBetaR = totalRayleigh * rayleighCoefficient;',
'vec3 Uncharted2Tonemap( vec3 x ) {',
' return ( ( x * ( A * x + C * B ) + D * E ) / ( x * ( A * x + B ) + D * F ) ) - E / F;',
'}',
// mie coefficients
' vBetaM = totalMie( turbidity ) * mieCoefficient;',
'}'
].join( '\n' ),
'void main() {',
// optical length
// cutoff angle at 90 to avoid singularity in next formula.
' float zenithAngle = acos( max( 0.0, dot( up, normalize( vWorldPosition - cameraPos ) ) ) );',
' float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) );',
' float sR = rayleighZenithLength * inverse;',
' float sM = mieZenithLength * inverse;',
fragmentShader: [
'varying vec3 vWorldPosition;',
'varying vec3 vSunDirection;',
'varying float vSunfade;',
'varying vec3 vBetaR;',
'varying vec3 vBetaM;',
'varying float vSunE;',
// combined extinction factor
' vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) );',
'uniform float luminance;',
'uniform float mieDirectionalG;',
// in scattering
' float cosTheta = dot( normalize( vWorldPosition - cameraPos ), vSunDirection );',
'const vec3 cameraPos = vec3( 0.0, 0.0, 0.0 );',
' float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 );',
' vec3 betaRTheta = vBetaR * rPhase;',
// constants for atmospheric scattering
'const float pi = 3.141592653589793238462643383279502884197169;',
' float mPhase = hgPhase( cosTheta, mieDirectionalG );',
' vec3 betaMTheta = vBetaM * mPhase;',
'const float n = 1.0003;', // refractive index of air
'const float N = 2.545E25;', // number of molecules per unit volume for air at
// 288.15K and 1013mb (sea level -45 celsius)
' vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) );',
' Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) );',
// optical length at zenith for molecules
'const float rayleighZenithLength = 8.4E3;',
'const float mieZenithLength = 1.25E3;',
'const vec3 up = vec3( 0.0, 1.0, 0.0 );',
// 66 arc seconds -> degrees, and the cosine of that
'const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;',
// nightsky
' vec3 direction = normalize( vWorldPosition - cameraPos );',
' float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2]',
' float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2]',
' vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 );',
' vec3 L0 = vec3( 0.1 ) * Fex;',
// 3.0 / ( 16.0 * pi )
'const float THREE_OVER_SIXTEENPI = 0.05968310365946075;',
// 1.0 / ( 4.0 * pi )
'const float ONE_OVER_FOURPI = 0.07957747154594767;',
// composition + solar disc
' float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta );',
' L0 += ( vSunE * 19000.0 * Fex ) * sundisk;',
'float rayleighPhase( float cosTheta ) {',
' return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) );',
'}',
' vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 );',
'float hgPhase( float cosTheta, float g ) {',
' float g2 = pow( g, 2.0 );',
' float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 );',
' return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse );',
'}',
' vec3 curr = Uncharted2Tonemap( ( log2( 2.0 / pow( luminance, 4.0 ) ) ) * texColor );',
' vec3 color = curr * whiteScale;',
// Filmic ToneMapping http://filmicgames.com/archives/75
'const float A = 0.15;',
'const float B = 0.50;',
'const float C = 0.10;',
'const float D = 0.20;',
'const float E = 0.02;',
'const float F = 0.30;',
' vec3 retColor = pow( color, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) );',
'const float whiteScale = 1.0748724675633854;', // 1.0 / Uncharted2Tonemap(1000.0)
' gl_FragColor = vec4( retColor, 1.0 );',
'vec3 Uncharted2Tonemap( vec3 x ) {',
' return ( ( x * ( A * x + C * B ) + D * E ) / ( x * ( A * x + B ) + D * F ) ) - E / F;',
'}',
'}'
].join( '\n' )
};
'void main() {',
// optical length
// cutoff angle at 90 to avoid singularity in next formula.
' float zenithAngle = acos( max( 0.0, dot( up, normalize( vWorldPosition - cameraPos ) ) ) );',
' float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) );',
' float sR = rayleighZenithLength * inverse;',
' float sM = mieZenithLength * inverse;',
var skyUniforms = THREE.UniformsUtils.clone( skyShader.uniforms );
// combined extinction factor
' vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) );',
var skyMat = new THREE.ShaderMaterial( {
fragmentShader: skyShader.fragmentShader,
vertexShader: skyShader.vertexShader,
uniforms: skyUniforms,
side: THREE.BackSide
} );
// in scattering
' float cosTheta = dot( normalize( vWorldPosition - cameraPos ), vSunDirection );',
var skyGeo = new THREE.SphereBufferGeometry( 450000, 32, 15 );
var skyMesh = new THREE.Mesh( skyGeo, skyMat );
' float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 );',
' vec3 betaRTheta = vBetaR * rPhase;',
// Expose variables
this.mesh = skyMesh;
this.uniforms = skyUniforms;
' float mPhase = hgPhase( cosTheta, mieDirectionalG );',
' vec3 betaMTheta = vBetaM * mPhase;',
' vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) );',
' Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) );',
// nightsky
' vec3 direction = normalize( vWorldPosition - cameraPos );',
' float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2]',
' float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2]',
' vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 );',
' vec3 L0 = vec3( 0.1 ) * Fex;',
// composition + solar disc
' float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta );',
' L0 += ( vSunE * 19000.0 * Fex ) * sundisk;',
' vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 );',
' vec3 curr = Uncharted2Tonemap( ( log2( 2.0 / pow( luminance, 4.0 ) ) ) * texColor );',
' vec3 color = curr * whiteScale;',
' vec3 retColor = pow( color, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) );',
' gl_FragColor = vec4( retColor, 1.0 );',
'}'
].join( '\n' )
};
......@@ -37,7 +37,7 @@ THREE.VRControls = function ( object, onError ) {
if ( navigator.getVRDisplays ) {
navigator.getVRDisplays().then( gotVRDisplays ).catch ( function () {
navigator.getVRDisplays().then( gotVRDisplays ).catch( function () {
console.warn( 'THREE.VRControls: Unable to get VR Displays' );
......
......@@ -27,6 +27,12 @@ THREE.STLExporter.prototype = {
var geometry = object.geometry;
var matrixWorld = object.matrixWorld;
if( geometry instanceof THREE.BufferGeometry ) {
geometry = new THREE.Geometry().fromBufferGeometry( geometry );
}
if ( geometry instanceof THREE.Geometry ) {
var vertices = geometry.vertices;
......
......@@ -55,7 +55,7 @@ THREE.GLTF2Loader = ( function () {
var magic = convertUint8ArrayToString( new Uint8Array( data, 0, 4 ) );
if ( magic === BINARY_EXTENSION_HEADER_DEFAULTS.magic ) {
if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
......@@ -320,63 +320,70 @@ THREE.GLTF2Loader = ( function () {
/* BINARY EXTENSION */
var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
var BINARY_EXTENSION_HEADER_DEFAULTS = { magic: 'glTF', version: 1, contentFormat: 0 };
var BINARY_EXTENSION_HEADER_LENGTH = 20;
var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
var BINARY_EXTENSION_HEADER_LENGTH = 12;
var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
function GLTFBinaryExtension( data ) {
this.name = EXTENSIONS.KHR_BINARY_GLTF;
this.content = null;
this.body = null;
var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
var header = {
this.header = {
magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ),
version: headerView.getUint32( 4, true ),
length: headerView.getUint32( 8, true ),
contentLength: headerView.getUint32( 12, true ),
contentFormat: headerView.getUint32( 16, true )
length: headerView.getUint32( 8, true )
};
for ( var key in BINARY_EXTENSION_HEADER_DEFAULTS ) {
var value = BINARY_EXTENSION_HEADER_DEFAULTS[ key ];
if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
if ( header[ key ] !== value ) {
throw new Error( 'GLTF2Loader: Unsupported glTF-Binary header.' );
throw new Error( 'Unsupported glTF-Binary header: Expected "%s" to be "%s".', key, value );
} else if ( this.header.version < 2.0 ) {
}
throw new Error( 'GLTF2Loader: Legacy binary file detected. Use GLTFLoader instead.' );
}
var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH, header.contentLength );
var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
var chunkIndex = 0;
this.header = header;
this.content = convertUint8ArrayToString( contentArray );
this.body = data.slice( BINARY_EXTENSION_HEADER_LENGTH + header.contentLength, header.length );
while ( chunkIndex < chunkView.byteLength ) {
}
var chunkLength = chunkView.getUint32( chunkIndex, true );
chunkIndex += 4;
GLTFBinaryExtension.prototype.loadShader = function ( shader, bufferViews ) {
var chunkType = chunkView.getUint32( chunkIndex, true );
chunkIndex += 4;
var bufferView = bufferViews[ shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].bufferView ];
var array = new Uint8Array( bufferView );
if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
return convertUint8ArrayToString( array );
var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
this.content = convertUint8ArrayToString( contentArray );
};
} else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
GLTFBinaryExtension.prototype.loadTextureSourceUri = function ( source, bufferViews ) {
var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
this.body = data.slice( byteOffset, byteOffset + chunkLength );
var metadata = source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ];
var bufferView = bufferViews[ metadata.bufferView ];
var stringData = convertUint8ArrayToString( new Uint8Array( bufferView ) );
}
return 'data:' + metadata.mimeType + ';base64,' + btoa( stringData );
// Clients must ignore chunks with unknown types.
};
chunkIndex += chunkLength;
}
if ( this.content === null ) {
throw new Error( 'GLTF2Loader: JSON content not found.' );
}
}
/*********************************/
/********** INTERNALS ************/
......@@ -633,6 +640,13 @@ THREE.GLTF2Loader = ( function () {
}
// Blob URL
if ( /^blob:.*$/i.test( url ) ) {
return url;
}
// Relative URL
return ( path || '' ) + url;
......@@ -894,7 +908,6 @@ THREE.GLTF2Loader = ( function () {
GLTFParser.prototype.loadShaders = function () {
var json = this.json;
var extensions = this.extensions;
var options = this.options;
return this._withDependencies( [
......@@ -905,9 +918,11 @@ THREE.GLTF2Loader = ( function () {
return _each( json.shaders, function ( shader ) {
if ( shader.extensions && shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
if ( shader.bufferView !== undefined ) {
return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadShader( shader, dependencies.bufferViews );
var bufferView = dependencies.bufferViews[ shader.bufferView ];
var array = new Uint8Array( bufferView );
return convertUint8ArrayToString( array );
}
......@@ -937,13 +952,14 @@ THREE.GLTF2Loader = ( function () {
return _each( json.buffers, function ( buffer, name ) {
if ( name === BINARY_EXTENSION_BUFFER_NAME ) {
if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
// If present, GLB container is required to be the first buffer.
if ( buffer.uri === undefined && name === 0 ) {
}
return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
}
return new Promise( function ( resolve ) {
......@@ -1011,11 +1027,13 @@ THREE.GLTF2Loader = ( function () {
var elementBytes = TypedArray.BYTES_PER_ELEMENT;
var itemBytes = elementBytes * itemSize;
var array;
// The buffer is not interleaved if the stride is the item size in bytes.
if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
// Use the full buffer if it's interleaved.
var array = new TypedArray( arraybuffer );
array = new TypedArray( arraybuffer );
// Integer parameters to IB/IBA are in array elements, not bytes.
var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
......@@ -1039,7 +1057,6 @@ THREE.GLTF2Loader = ( function () {
GLTFParser.prototype.loadTextures = function () {
var json = this.json;
var extensions = this.extensions;
var options = this.options;
return this._withDependencies( [
......@@ -1057,9 +1074,14 @@ THREE.GLTF2Loader = ( function () {
var source = json.images[ texture.source ];
var sourceUri = source.uri;
if ( source.extensions && source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
var urlCreator;
if ( source.bufferView !== undefined ) {
sourceUri = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadTextureSourceUri( source, dependencies.bufferViews );
var bufferView = dependencies.bufferViews[ source.bufferView ];
var blob = new Blob( [ bufferView ], { type: source.mimeType } );
urlCreator = window.URL || window.webkitURL;
sourceUri = urlCreator.createObjectURL( blob );
}
......@@ -1075,6 +1097,12 @@ THREE.GLTF2Loader = ( function () {
textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {
if ( urlCreator !== undefined ) {
urlCreator.revokeObjectURL( sourceUri );
}
_texture.flipY = false;
if ( texture.name !== undefined ) _texture.name = texture.name;
......@@ -1190,7 +1218,97 @@ THREE.GLTF2Loader = ( function () {
} else if ( material.technique === undefined ) {
materialType = THREE.MeshPhongMaterial;
if ( material.pbrMetallicRoughness !== undefined ) {
// specification
// https://github.com/sbtron/glTF/blob/30de0b365d1566b1bbd8b9c140f9e995d3203226/specification/2.0/README.md#metallic-roughness-material
materialType = THREE.MeshStandardMaterial;
if ( material.pbrMetallicRoughness !== undefined ) {
var metallicRoughness = material.pbrMetallicRoughness;
materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
materialParams.opacity = 1.0;
if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
var array = metallicRoughness.baseColorFactor;
materialParams.color.fromArray( array );
materialParams.opacity = array[ 3 ];
}
if ( metallicRoughness.baseColorTexture !== undefined ) {
materialParams.map = dependencies.textures[ metallicRoughness.baseColorTexture.index ];
}
if ( materialParams.opacity < 1.0 ||
( materialParams.map !== undefined &&
( materialParams.map.format === THREE.AlphaFormat ||
materialParams.map.format === THREE.RGBAFormat ||
materialParams.map.format === THREE.LuminanceAlphaFormat ) ) ) {
materialParams.transparent = true;
}
materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
// Note that currently metalnessMap would be entirely ignored because
// Three.js and glTF specification use different texture channels for metalness
// (Blue: Three.js, Red: glTF).
// But glTF specification team is discussing if they can change.
// Let's keep an eye on it so far.
//
// https://github.com/KhronosGroup/glTF/issues/857
materialParams.metalnessMap = dependencies.textures[ textureIndex ];
materialParams.roughnessMap = dependencies.textures[ textureIndex ];
}
}
} else {
materialType = THREE.MeshPhongMaterial;
}
if ( material.normalTexture !== undefined ) {
materialParams.normalMap = dependencies.textures[ material.normalTexture.index ];
}
if ( material.occlusionTexture !== undefined ) {
materialParams.aoMap = dependencies.textures[ material.occlusionTexture.index ];
}
if ( material.emissiveTexture !== undefined ) {
materialParams.emissiveMap = dependencies.textures[ material.emissiveTexture.index ];
}
materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
if ( material.emissiveFactor !== undefined ) {
materialParams.emissive.fromArray( material.emissiveFactor );
}
Object.assign( materialValues, material.values );
......
此差异已折叠。
......@@ -25,7 +25,7 @@ THREE.DaydreamController = function () {
var gamepad = gamepads[ i ];
if ( gamepad !== null && ( gamepad.id === 'Daydream Controller' ) ) {
if ( gamepad && ( gamepad.id === 'Daydream Controller' ) ) {
return gamepad;
......
......@@ -18,6 +18,24 @@ var WEBVR = {
},
getVRDisplay: function ( onDisplay ) {
if ( 'getVRDisplays' in navigator ) {
navigator.getVRDisplays()
.then( function ( displays ) {
onDisplay( displays[ 0 ] );
} )
.catch( function () {
// no displays
} );
}
},
getMessage: function () {
var message;
......@@ -65,7 +83,16 @@ var WEBVR = {
},
getButton: function ( effect ) {
getButton: function ( display, canvas ) {
/*
if ( display instanceof VRDisplay === false ) {
console.error( 'WebVR.getButton() now expects a VRDisplay.' );
return;
}
*/
var button = document.createElement( 'button' );
button.style.position = 'absolute';
......@@ -85,13 +112,13 @@ var WEBVR = {
button.textContent = 'ENTER VR';
button.onclick = function () {
effect.isPresenting ? effect.exitPresent() : effect.requestPresent();
display.isPresenting ? display.exitPresent() : display.requestPresent( [ { source: canvas } ] );
};
window.addEventListener( 'vrdisplaypresentchange', function () {
button.textContent = effect.isPresenting ? 'EXIT VR' : 'ENTER VR';
button.textContent = display.isPresenting ? 'EXIT VR' : 'ENTER VR';
}, false );
......
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.WebVRCamera = function ( display, renderer ) {
var scope = this;
var frameData = null;
if ( 'VRFrameData' in window ) {
frameData = new window.VRFrameData();
}
var eyeTranslationL = new THREE.Vector3();
var eyeTranslationR = new THREE.Vector3();
var cameraL = new THREE.PerspectiveCamera();
cameraL.bounds = new THREE.Vector4( 0.0, 0.0, 0.5, 1.0 );
cameraL.layers.enable( 1 );
var cameraR = new THREE.PerspectiveCamera();
cameraR.bounds = new THREE.Vector4( 0.5, 0.0, 0.5, 1.0 );
cameraR.layers.enable( 2 );
//
var currentSize, currentPixelRatio;
function onVRDisplayPresentChange() {
if ( display.isPresenting ) {
var eyeParameters = display.getEyeParameters( 'left' );
var renderWidth = eyeParameters.renderWidth;
var renderHeight = eyeParameters.renderHeight;
currentPixelRatio = renderer.getPixelRatio();
currentSize = renderer.getSize();
renderer.setPixelRatio( 1 );
renderer.setSize( renderWidth * 2, renderHeight, false );
scope.enabled = true;
} else if ( scope.enabled ) {
scope.enabled = false;
renderer.setPixelRatio( currentPixelRatio );
renderer.setSize( currentSize.width, currentSize.height, true );
}
}
window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
//
THREE.ArrayCamera.call( this, [ cameraL, cameraR ] );
//
this.onBeforeRender = function () {
display.depthNear = scope.near;
display.depthFar = scope.far;
display.getFrameData( frameData );
//
var pose = frameData.pose;
if ( pose.orientation !== null ) {
scope.quaternion.fromArray( pose.orientation );
}
if ( pose.position !== null ) {
scope.position.fromArray( pose.position );
} else {
scope.position.set( 0, 0, 0 );
}
//
var eyeParamsL = display.getEyeParameters( 'left' );
var eyeParamsR = display.getEyeParameters( 'right' );
eyeTranslationL.fromArray( eyeParamsL.offset );
eyeTranslationR.fromArray( eyeParamsR.offset );
cameraL.position.copy( scope.position );
cameraL.quaternion.copy( scope.quaternion );
cameraL.scale.copy( scope.scale );
cameraR.position.copy( scope.position );
cameraR.quaternion.copy( scope.quaternion );
cameraR.scale.copy( scope.scale );
cameraL.translateOnAxis( eyeTranslationL, cameraL.scale.x );
cameraR.translateOnAxis( eyeTranslationR, cameraR.scale.x );
cameraL.updateMatrixWorld();
cameraL.matrixWorldInverse.getInverse( cameraL.matrixWorld );
cameraR.updateMatrixWorld();
cameraR.matrixWorldInverse.getInverse( cameraR.matrixWorld );
cameraL.projectionMatrix.elements = frameData.leftProjectionMatrix;
cameraR.projectionMatrix.elements = frameData.rightProjectionMatrix;
// HACK @mrdoob
// Ideally we'll merge both projection matrices so we can frustum cull
scope.projectionMatrix.copy( cameraL.projectionMatrix );
//
var layers = display.getLayers();
if ( layers.length ) {
var layer = layers[ 0 ];
if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
cameraL.bounds.fromArray( layer.leftBounds );
}
if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
cameraR.bounds.fromArray( layer.rightBounds );
}
}
};
this.onAfterRender = function () {
if ( display.isPresenting ) display.submitFrame();
};
};
THREE.WebVRCamera.prototype = Object.assign( Object.create( THREE.ArrayCamera.prototype ), {
constructor: THREE.WebVRCamera,
isWebVRCamera: true
} );
# Boom Box
## Screenshot
![screenshot](screenshot/screenshot.jpg)
## License Information
Donated by Microsoft for glTF testing.
\ No newline at end of file
{
"accessors": [
{
"bufferView": 0,
"byteOffset": 0,
"componentType": 5126,
"count": 3575,
"type": "VEC2",
"max": [
0.9999003,
-0.0221377648
],
"min": [
0.0006585993,
-0.996773958
]
},
{
"bufferView": 1,
"byteOffset": 0,
"componentType": 5126,
"count": 3575,
"type": "VEC3",
"max": [
1.0,
1.0,
0.9999782
],
"min": [
-1.0,
-1.0,
-0.9980823
]
},
{
"bufferView": 2,
"byteOffset": 0,
"componentType": 5126,
"count": 3575,
"type": "VEC3",
"max": [
0.009921154,
0.00977163,
0.0100762453
],
"min": [
-0.009921154,
-0.00977163,
-0.0100762453
]
},
{
"bufferView": 3,
"byteOffset": 0,
"componentType": 5123,
"count": 18108,
"type": "SCALAR",
"max": [
3574
],
"min": [
0
]
}
],
"asset": {
"generator": "glTF Tools for Unity",
"version": "2.0"
},
"bufferViews": [
{
"buffer": 0,
"byteOffset": 0,
"byteLength": 28600,
"target": 34962
},
{
"buffer": 0,
"byteOffset": 28600,
"byteLength": 42900,
"target": 34962
},
{
"buffer": 0,
"byteOffset": 71500,
"byteLength": 42900,
"target": 34962
},
{
"buffer": 0,
"byteOffset": 114400,
"byteLength": 36216,
"target": 34963
}
],
"buffers": [
{
"uri": "BoomBox.bin",
"byteLength": 150616
}
],
"extensionsUsed": [
"KHR_materials_pbrSpecularGlossiness"
],
"images": [
{
"uri": "BoomBox_baseColor.png"
},
{
"uri": "BoomBox_metallicRoughness.png"
},
{
"uri": "BoomBox_normal.png"
},
{
"uri": "BoomBox_occlusion.png"
},
{
"uri": "BoomBox_emissive.png"
},
{
"uri": "BoomBox_diffuse.png"
},
{
"uri": "BoomBox_specularGlossiness.png"
}
],
"meshes": [
{
"primitives": [
{
"attributes": {
"TEXCOORD_0": 0,
"NORMAL": 1,
"POSITION": 2
},
"indices": 3,
"material": 0,
"mode": 4
}
],
"name": "BoomBox"
}
],
"materials": [
{
"pbrMetallicRoughness": {
"baseColorTexture": {
"index": 0
},
"metallicRoughnessTexture": {
"index": 1
}
},
"normalTexture": {
"index": 2
},
"occlusionTexture": {
"index": 3
},
"emissiveFactor": [
1.0,
1.0,
1.0
],
"emissiveTexture": {
"index": 4
},
"name": "BoomBox_Mat",
"extensions": {
"KHR_materials_pbrSpecularGlossiness": {
"diffuseTexture": {
"index": 5
},
"specularGlossinessTexture": {
"index": 6
}
}
}
}
],
"nodes": [
{
"children": [],
"mesh": 0,
"scale": [
80.0,
80.0,
80.0
],
"translation": [
0.0,
0.163,
0.053
],
"name": "BoomBox"
}
],
"samplers": [
{}
],
"scene": 0,
"scenes": [
{
"nodes": [
0
]
}
],
"textures": [
{
"sampler": 0,
"source": 0
},
{
"sampler": 0,
"source": 1
},
{
"sampler": 0,
"source": 2
},
{
"sampler": 0,
"source": 3
},
{
"sampler": 0,
"source": 4
},
{
"sampler": 0,
"source": 5
},
{
"sampler": 0,
"source": 6
}
]
}
\ No newline at end of file
{
"accessors": [
{
"bufferView": 0,
"byteOffset": 0,
"componentType": 5126,
"count": 3575,
"type": "VEC2",
"max": [
0.9999003,
-0.0221377648
],
"min": [
0.0006585993,
-0.996773958
]
},
{
"bufferView": 1,
"byteOffset": 0,
"componentType": 5126,
"count": 3575,
"type": "VEC3",
"max": [
1.0,
1.0,
0.9999782
],
"min": [
-1.0,
-1.0,
-0.9980823
]
},
{
"bufferView": 2,
"byteOffset": 0,
"componentType": 5126,
"count": 3575,
"type": "VEC3",
"max": [
0.009921154,
0.00977163,
0.0100762453
],
"min": [
-0.009921154,
-0.00977163,
-0.0100762453
]
},
{
"bufferView": 3,
"byteOffset": 0,
"componentType": 5123,
"count": 18108,
"type": "SCALAR",
"max": [
3574
],
"min": [
0
]
}
],
"asset": {
"generator": "glTF Tools for Unity",
"version": "2.0"
},
"bufferViews": [
{
"buffer": 0,
"byteOffset": 0,
"byteLength": 28600,
"target": 34962
},
{
"buffer": 0,
"byteOffset": 28600,
"byteLength": 42900,
"target": 34962
},
{
"buffer": 0,
"byteOffset": 71500,
"byteLength": 42900,
"target": 34962
},
{
"buffer": 0,
"byteOffset": 114400,
"byteLength": 36216,
"target": 34963
}
],
"buffers": [
{
"uri": "BoomBox.bin",
"byteLength": 150616
}
],
"images": [
{
"uri": "BoomBox_baseColor.png"
},
{
"uri": "BoomBox_metallicRoughness.png"
},
{
"uri": "BoomBox_normal.png"
},
{
"uri": "BoomBox_occlusion.png"
},
{
"uri": "BoomBox_emissive.png"
}
],
"meshes": [
{
"primitives": [
{
"attributes": {
"TEXCOORD_0": 0,
"NORMAL": 1,
"POSITION": 2
},
"indices": 3,
"material": 0,
"mode": 4
}
],
"name": "BoomBox"
}
],
"materials": [
{
"pbrMetallicRoughness": {
"baseColorTexture": {
"index": 0
},
"metallicRoughnessTexture": {
"index": 1
}
},
"normalTexture": {
"index": 2
},
"occlusionTexture": {
"index": 3
},
"emissiveFactor": [
1.0,
1.0,
1.0
],
"emissiveTexture": {
"index": 4
},
"name": "BoomBox_Mat"
}
],
"nodes": [
{
"children": [],
"mesh": 0,
"scale": [
80.0,
80.0,
80.0
],
"translation": [
0.0,
0.163,
0.053
],
"name": "BoomBox"
}
],
"samplers": [
{}
],
"scene": 0,
"scenes": [
{
"nodes": [
0
]
}
],
"textures": [
{
"sampler": 0,
"source": 0
},
{
"sampler": 0,
"source": 1
},
{
"sampler": 0,
"source": 2
},
{
"sampler": 0,
"source": 3
},
{
"sampler": 0,
"source": 4
}
]
}
\ No newline at end of file
此差异已折叠。
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - glTF</title>
<title>three.js webgl - glTF 1.0</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
......@@ -63,7 +63,7 @@
<body>
<div id="info">
<a href="http://threejs.org" target="_blank">three.js</a> -
<a href="https://github.com/KhronosGroup/glTF" target="_blank">glTF</a> loader
<a href="https://github.com/KhronosGroup/glTF" target="_blank">glTF</a> 1.0 loader
<br>
monster by <a href="http://www.3drt.com/downloads.htm" target="_blank">3drt</a> - COLLADA duck by Sony -
Cesium models by <a href="http://cesiumjs.org/" target="_blank">Cesium</a>
......@@ -95,7 +95,7 @@
</div>
<script src="../build/three.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script src="js/loaders/GLTF2Loader.js"></script>
<script src="js/loaders/GLTFLoader.js"></script>
<script>
var orbitControls = null;
......@@ -202,7 +202,7 @@
scene.add(ground);
}
loader = new THREE.GLTF2Loader();
loader = new THREE.GLTFLoader();
for (var i = 0; i < extensionSelect.children.length; i++) {
var child = extensionSelect.children[i];
......
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - glTF 2.0</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: #222222;
margin: 0px;
overflow: hidden;
}
#info {
color: #808080;
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: 100;
display:block;
}
#container {
position: absolute;
top: 0px;
width:100%;
height:100%;
z-index: -1;
}
#controls {
position: absolute;
width: 200px;
bottom: 0px;
left: 0px;
padding: 10px;
background-color: White;
font: 13px "Lucida Grande", Lucida, Verdana, sans-serif;
}
#controls > div {
margin-bottom: 8px;
}
#controls hr {
border: 0px;
height: 1px;
margin-bottom: 10px;
background-color: #bbb;
}
#info a, .button {
color: #f00;
font-weight: bold;
text-decoration: underline;
cursor: pointer
}
</style>
</head>
<body>
<div id="info">
<a href="http://threejs.org" target="_blank">three.js</a> -
<a href="https://github.com/KhronosGroup/glTF" target="_blank">glTF</a> 2.0 loader
<br>
BoomBox by <a href="https://www.microsoft.com/" target="_blank">Microsoft</a>
</div>
<div id="container"></div>
<div id="controls">
<div id="status">Loading...</div>
<hr />
<div>
Model
<select id="scenes_list" size="1" onchange="selectScene();" ondblclick="selectScene();"></select>
</div>
<div>
Camera
<select id="cameras_list" size="1" onchange="selectCamera();" ondblclick="selectCamera();"></select>
</div>
<div>
Animations
<input type="checkbox" checked onclick="toggleAnimations();">Play</input>
</div>
<div>
Extension
<select id="extensions_list" onchange="selectExtension();">
<option value="glTF">None</option>
<option value="glTF-MaterialsCommon">Built-in shaders</option>
<option value="glTF-Binary">Binary</option>
</select>
</div>
</div>
<script src="../build/three.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script src="js/loaders/GLTF2Loader.js"></script>
<script>
var orbitControls = null;
var container, camera, scene, renderer, loader;
var cameraIndex = 0;
var cameras = [];
var cameraNames = [];
var defaultCamera = null;
var gltf = null;
var mixer = null;
var clock = new THREE.Clock();
function onload() {
window.addEventListener( 'resize', onWindowResize, false );
document.addEventListener( 'keydown', function(e) { onKeyDown(e); }, false );
buildSceneList();
switchScene(0);
animate();
}
function initScene(index) {
container = document.getElementById( 'container' );
scene = new THREE.Scene();
defaultCamera = new THREE.PerspectiveCamera( 45, container.offsetWidth / container.offsetHeight, 1, 20000 );
//defaultCamera.up = new THREE.Vector3( 0, 1, 0 );
scene.add( defaultCamera );
camera = defaultCamera;
var sceneInfo = sceneList[index];
var spot1 = null;
if (sceneInfo.addLights) {
var ambient = new THREE.AmbientLight( 0x222222 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xdddddd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );
spot1 = new THREE.SpotLight( 0xffffff, 1 );
spot1.position.set( 10, 20, 10 );
spot1.angle = 0.25;
spot1.distance = 1024;
spot1.penumbra = 0.75;
if ( sceneInfo.shadows ) {
spot1.castShadow = true;
spot1.shadow.bias = 0.0001;
spot1.shadow.mapSize.width = 2048;
spot1.shadow.mapSize.height = 2048;
}
scene.add( spot1 );
}
// RENDERER
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setClearColor( 0x222222 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
if (sceneInfo.shadows) {
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
}
container.appendChild( renderer.domElement );
var ground = null;
if (sceneInfo.addGround) {
var groundMaterial = new THREE.MeshPhongMaterial({
color: 0xFFFFFF,
shading: THREE.SmoothShading
});
ground = new THREE.Mesh( new THREE.PlaneBufferGeometry(512, 512), groundMaterial);
if (sceneInfo.shadows) {
ground.receiveShadow = true;
}
if (sceneInfo.groundPos) {
ground.position.copy(sceneInfo.groundPos);
} else {
ground.position.z = -70;
}
ground.rotation.x = -Math.PI / 2;
scene.add(ground);
}
loader = new THREE.GLTF2Loader();
for (var i = 0; i < extensionSelect.children.length; i++) {
var child = extensionSelect.children[i];
child.disabled = sceneInfo.extensions.indexOf(child.value) === -1;
if (child.disabled && child.selected) {
extensionSelect.value = extension = 'glTF';
}
}
var url = sceneInfo.url;
var r = eval("/" + '\%s' + "/g");
url = url.replace(r, extension);
if (extension === 'glTF-Binary') {
url = url.replace('.gltf', '.glb');
}
var loadStartTime = performance.now();
var status = document.getElementById("status");
status.innerHTML = "Loading...";
loader.load( url, function(data) {
gltf = data;
var object = gltf.scene;
status.innerHTML = "Load time: " + ( performance.now() - loadStartTime ).toFixed( 2 ) + " ms.";
if (sceneInfo.cameraPos)
defaultCamera.position.copy(sceneInfo.cameraPos);
if (sceneInfo.center) {
orbitControls.target.copy(sceneInfo.center);
}
if (sceneInfo.objectPosition) {
object.position.copy(sceneInfo.objectPosition);
if (spot1) {
spot1.position.set(sceneInfo.objectPosition.x - 100, sceneInfo.objectPosition.y + 200, sceneInfo.objectPosition.z - 100 );
spot1.target.position.copy(sceneInfo.objectPosition);
}
}
if (sceneInfo.objectRotation)
object.rotation.copy(sceneInfo.objectRotation);
if (sceneInfo.objectScale)
object.scale.copy(sceneInfo.objectScale);
cameraIndex = 0;
cameras = [];
cameraNames = [];
if (gltf.cameras && gltf.cameras.length) {
var i, len = gltf.cameras.length;
for (i = 0; i < len; i++) {
var addCamera = true;
var cameraName = gltf.cameras[i].parent.name;
if (sceneInfo.cameras && !(cameraName in sceneInfo.cameras)) {
addCamera = false;
}
if (addCamera) {
cameraNames.push(cameraName);
cameras.push(gltf.cameras[i]);
}
}
updateCamerasList();
switchCamera(1);
} else {
updateCamerasList();
switchCamera(0);
}
var animations = gltf.animations;
if ( animations && animations.length ) {
mixer = new THREE.AnimationMixer( object );
for ( var i = 0; i < animations.length; i ++ ) {
var animation = animations[ i ];
// There's .3333 seconds junk at the tail of the Monster animation that
// keeps it from looping cleanly. Clip it at 3 seconds
if ( sceneInfo.animationTime )
animation.duration = sceneInfo.animationTime;
mixer.clipAction( animation ).play();
}
}
scene.add( object );
onWindowResize();
});
orbitControls = new THREE.OrbitControls(defaultCamera, renderer.domElement);
}
function onWindowResize() {
defaultCamera.aspect = container.offsetWidth / container.offsetHeight;
defaultCamera.updateProjectionMatrix();
var i, len = cameras.length;
for (i = 0; i < len; i++) { // just do it for default
cameras[i].aspect = container.offsetWidth / container.offsetHeight;
cameras[i].updateProjectionMatrix();
}
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
if (mixer) mixer.update(clock.getDelta());
if (cameraIndex == 0)
orbitControls.update();
render();
}
function render() {
renderer.render( scene, camera );
}
function onKeyDown(event) {
var chr = String.fromCharCode(event.keyCode);
if (chr == ' ') {
index = cameraIndex + 1;
if (index > cameras.length)
index = 0;
switchCamera(index);
} else {
var index = parseInt(chr);
if (!isNaN(index) && (index <= cameras.length)) {
switchCamera(index);
}
}
}
var sceneList = [
{
name : "BoomBox (PBR)", url : "./models/gltf/BoomBox/%s/BoomBox.gltf",
cameraPos: new THREE.Vector3(2, 1, 3),
objectRotation: new THREE.Euler(0, Math.PI, 0),
addLights:true,
extensions: ["glTF"]
}
];
function buildSceneList() {
var elt = document.getElementById('scenes_list');
while( elt.hasChildNodes() ){
elt.removeChild(elt.lastChild);
}
var i, len = sceneList.length;
for (i = 0; i < len; i++) {
option = document.createElement("option");
option.text=sceneList[i].name;
elt.add(option);
}
}
function switchScene(index) {
cleanup();
initScene(index);
var elt = document.getElementById('scenes_list');
elt.selectedIndex = index;
}
function selectScene() {
var select = document.getElementById("scenes_list");
var index = select.selectedIndex;
if (index >= 0) {
switchScene(index);
}
}
function switchCamera(index) {
cameraIndex = index;
if (cameraIndex == 0) {
camera = defaultCamera;
}
if (cameraIndex >= 1 && cameraIndex <= cameras.length) {
camera = cameras[cameraIndex - 1];
}
var elt = document.getElementById('cameras_list');
elt.selectedIndex = cameraIndex;
}
function updateCamerasList() {
var elt = document.getElementById('cameras_list');
while( elt.hasChildNodes() ){
elt.removeChild(elt.lastChild);
}
option = document.createElement("option");
option.text="[default]";
elt.add(option);
var i, len = cameraNames.length;
for (i = 0; i < len; i++) {
option = document.createElement("option");
option.text=cameraNames[i];
elt.add(option);
}
}
function selectCamera() {
var select = document.getElementById("cameras_list");
var index = select.selectedIndex;
if (index >= 0) {
switchCamera(index);
}
}
function toggleAnimations() {
var i, len = gltf.animations.length;
for (i = 0; i < len; i++) {
var clip = gltf.animations[i];
var action = mixer.existingAction( clip );
if (action.isRunning()) {
action.stop();
} else {
action.play();
}
}
}
var extensionSelect = document.getElementById("extensions_list");
var extension = extensionSelect.value;
function selectExtension()
{
extension = extensionSelect.value;
selectScene();
}
function cleanup() {
if (container && renderer) {
container.removeChild(renderer.domElement);
}
cameraIndex = 0;
cameras = [];
cameraNames = [];
defaultCamera = null;
if (!loader || !mixer)
return;
mixer.stopAllAction();
}
onload();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang='en'>
<head>
<title>three.js webgl - loaders - X-File loader</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: #000;
color: #fff;
margin: 0px;
overflow: hidden;
}
#info {
color: #fff;
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: -1;
display: block;
}
#info a,
.button {
color: #f00;
font-weight: bold;
text-decoration: underline;
cursor: pointer;
}
</style>
</head>
<body>
<div id='info'>
<a href='http://threejs.org' target='_blank'>three.js</a> - X-File Loader test<br />
</div>
<script src='../build/three.js'></script>
<script src='js/controls/OrbitControls.js'></script>
<script src='js/loaders/XLoader.js'></script>
<script src='js/Detector.js'></script>
<script src='js/libs/stats.min.js'></script>
<script src='js/libs/dat.gui.min.js'></script>
<script>
if (!Detector.webgl) Detector.addGetWebGLMessage();
var container, stats, controls;
var camera, scene, renderer;
var clock = new THREE.Clock();
var gui = new dat.GUI();
var mixers = [];
var manager = null;
var Texloader = null;
var ParentList = null;
var skeletonHelper = null;
var Models = [];
var animateInf = null;
var DashAnime = null;
var d = new Date();
var LastDateTime = null;
var animates = [];
var actions = [];
init();
function init() {
LastDateTime = Date.now();
container = document.createElement('div');
document.body.appendChild(container);
container.style.zIndex = -10;
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
scene = new THREE.Scene();
scene.add(new THREE.AmbientLight(0x999999));
// grid
var gridHelper = new THREE.GridHelper(14, 1, 0x303030, 0x303030);
gridHelper.position.set(0, -0.04, 0);
scene.add(gridHelper);
// stats
stats = new Stats();
container.appendChild(stats.dom);
// model
manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
var onProgress = function (xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log(Math.round(percentComplete, 2) + '% downloaded');
}
};
var onError = function (xhr) {
console.log('Errror Loading!');
};
Texloader = new THREE.TextureLoader();
var loader = new THREE.XLoader(manager, Texloader);
// ! If [ Texture ] was reversed Y axis, enable the following.
// THREE.XLoader.IsUvYReverse = false;
// ! And if [ Model ] was reversed X axis, enable the following.
// loader.load([' your model url ', false ], function (object) {
// read (download) model file
loader.load(['models/xfile/SSR06_Born2.x', true], function (object) {
for (var i = 0; i < object.FrameInfo.length; i++) {
Models.push(object.FrameInfo[i]);
scene.add(Models[i]);
if (Models[i] instanceof THREE.SkinnedMesh) {
skeletonHelper = new THREE.SkeletonHelper(Models[i]);
scene.add(skeletonHelper);
if (object.XAnimationObj !== undefined && object.XAnimationObj.length !== 0) {
Models[i].geometry.animations = [];
/*
* ↓ that is BASIC animation data code.
* Usually, please use this.
* Because of the data I have, I use a different code
*
for (var a = 0; a < object.XAnimationObj.length; a++) {
Models[i].geometry.animations.push(THREE.AnimationClip.parseAnimation(object.XAnimationObj[a], Models[i].skeleton.bones));
}
Models[i].mixer = new THREE.AnimationMixer(Models[i]);
animates.push(Models[i].mixer);
var action = Models[i].mixer.clipAction(Models[i].geometry.animations[0]);
action.play();
*/
// ↓ that is a code for [ All animation-keyframes are connected data ]. output from 'LightWave3D'
{
Models[i].geometry.animations.push(THREE.AnimationClip.parseAnimation(splitAnimation(object.XAnimationObj[0], 'stand', 10 * object.XAnimationObj[0].fps, 11 * object.XAnimationObj[0].fps), Models[i].skeleton.bones));
Models[i].geometry.animations.push(THREE.AnimationClip.parseAnimation(splitAnimation(object.XAnimationObj[0], 'walk', 50 * object.XAnimationObj[0].fps, 80 * object.XAnimationObj[0].fps), Models[i].skeleton.bones));
Models[i].geometry.animations.push(THREE.AnimationClip.parseAnimation(splitAnimation(object.XAnimationObj[0], 'dash', 140 * object.XAnimationObj[0].fps, 160 * object.XAnimationObj[0].fps), Models[i].skeleton.bones));
Models[i].geometry.animations.push(THREE.AnimationClip.parseAnimation(splitAnimation(object.XAnimationObj[0], 'dashing', 160 * object.XAnimationObj[0].fps, 165 * object.XAnimationObj[0].fps), Models[i].skeleton.bones));
Models[i].geometry.animations.push(THREE.AnimationClip.parseAnimation(splitAnimation(object.XAnimationObj[0], 'damage', 500 * object.XAnimationObj[0].fps, 530 * object.XAnimationObj[0].fps), Models[i].skeleton.bones));
Models[i].mixer = new THREE.AnimationMixer(Models[i]);
animates.push(Models[i].mixer);
var stand = Models[i].mixer.clipAction('stand');
// stand.play();
stand.setLoop(THREE.LoopRepeat);
actions['stand'] = stand;
var walk = Models[i].mixer.clipAction('walk');
walk.setLoop(THREE.LoopRepeat);
walk.play();
actions['walk'] = walk;
var dash = Models[i].mixer.clipAction('dash');
dash.setLoop(THREE.LoopOnce);
//dash.play();
actions['dash'] = dash;
var dashing = Models[i].mixer.clipAction('dashing');
dashing.setLoop(THREE.LoopPingPong);
// dashing.play();
actions['dashing'] = dashing;
var damage = Models[i].mixer.clipAction('damage');
damage.setLoop(THREE.LoopRepeat);
//damage.play();
actions['damage'] = damage;
var ActionKeys = Object.keys(actions);
var dmy = {};
dmy.gui = '';
dmy.action = '';
gui.add(dmy, 'action', ActionKeys).onChange(function (v) {
animates[0].stopAllAction();
actions[v].play();
});
}
///////////
}
}
}
object = null;
}, onProgress, onError);
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x666666);
container.appendChild(renderer.domElement);
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.target.set(0, 12, 0);
camera.position.set(2, 18, 28);
camera.up.set(0, 1, 0);
var light = new THREE.DirectionalLight(0xeeeeff, 2);
light.position.set(10, 100, 1).normalize();
scene.add(light);
light = new THREE.DirectionalLight(0xaa5555);
light.position.set(-1, -1, -1).normalize();
scene.add(light);
controls.update();
window.addEventListener('resize', onWindowResize, false);
animate();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
//
function animate() {
requestAnimationFrame(animate);
var nowTime = Date.now();
var dulTime = nowTime - LastDateTime;
LastDateTime = nowTime;
if (animates != null && animates.length > 0) {
for (var i = 0; i < animates.length; i++) {
animates[i].update(dulTime);
}
}
if (Models != null && Models.length > 0 && skeletonHelper != null) { skeletonHelper.update(); }
stats.update();
render();
}
function render() {
renderer.render(scene, camera);
}
/////////////////
/// this is not must mount codes.
// split One and Long Animation, for time
function splitAnimation(_baseAnime, _name, _beginTime, _endTime) {
var Animation = {};
Animation.fps = _baseAnime.fps;
Animation.name = _name;
Animation.length = _endTime - _beginTime;
Animation.hierarchy = [];
for (var i = 0; i < _baseAnime.hierarchy.length; i++) {
var firstKey = -1;
var lastKey = -1;
var frame = {};
frame.name = _baseAnime.hierarchy[i].name;
frame.parent = _baseAnime.hierarchy[i].parent;
frame.keys = [];
for (var m = 1; m < _baseAnime.hierarchy[i].keys.length; m++) {
if (_baseAnime.hierarchy[i].keys[m].time > _beginTime) {
if (firstKey === -1) {
firstKey = m - 1;
frame.keys.push(_baseAnime.hierarchy[i].keys[m - 1]);
}
frame.keys.push(_baseAnime.hierarchy[i].keys[m]);
}
if (_endTime <= _baseAnime.hierarchy[i].keys[m].time || m >= _baseAnime.hierarchy[i].keys.length - 1) {
break;
}
}
for (var m = 0; m < frame.keys.length; m++) {
frame.keys[m].time -= _beginTime;
}
Animation.hierarchy.push(frame);
}
return Animation;
}
</script>
</body>
</html>
\ No newline at end of file
......@@ -37,6 +37,7 @@
<script src="../build/three.js"></script>
<script src="js/libs/dat.gui.min.js"></script>
<script src="js/Mirror.js"></script>
<script src="js/MirrorRTT.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<!-- NodeLibrary -->
......@@ -152,8 +153,7 @@
var planeGeo = new THREE.PlaneBufferGeometry( 100.1, 100.1 );
// MIRROR planes
var groundMirror = new THREE.Mirror( 100, 100, { clipBias: 0.003, textureWidth: WIDTH, textureHeight: HEIGHT } );
groundMirror.geometry.setDrawRange( 0, 0 ); // avoid rendering geometry
var groundMirror = new THREE.MirrorRTT( 100, 100, { clipBias: 0.003, textureWidth: WIDTH, textureHeight: HEIGHT } );
var mask = new THREE.SwitchNode( new THREE.TextureNode( decalDiffuse ), 'w' );
var maskFlip = new THREE.Math1Node( mask, THREE.Math1Node.INVERT );
......
......@@ -23,10 +23,9 @@
<script src="../build/three.js"></script>
<script src="js/controls/VRControls.js"></script>
<script src="js/effects/VREffect.js"></script>
<script src="js/vr/DaydreamController.js"></script>
<script src="js/vr/WebVR.js"></script>
<script src="js/vr/WebVRCamera.js"></script>
<script>
......@@ -42,7 +41,7 @@
var container;
var camera, scene, ray, raycaster, renderer;
var effect, controls, gamepad;
var gamepad, vrdisplay;
var room;
......@@ -65,9 +64,9 @@
container.appendChild( info );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x505050 );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 10 );
scene.add( camera );
room = new THREE.Mesh(
new THREE.BoxGeometry( 6, 6, 6, 8, 8, 8 ),
......@@ -115,7 +114,6 @@
//
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor( 0x505050 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.sortObjects = false;
......@@ -123,23 +121,15 @@
//
controls = new THREE.VRControls( camera );
effect = new THREE.VREffect( renderer );
WEBVR.getVRDisplay( function ( display ) {
if ( navigator.getVRDisplays ) {
vrdisplay = display;
navigator.getVRDisplays()
.then( function ( displays ) {
effect.setVRDisplay( displays[ 0 ] );
controls.setVRDisplay( displays[ 0 ] );
} )
.catch( function () {
// no displays
} );
camera = new THREE.WebVRCamera( display, renderer );
document.body.appendChild( WEBVR.getButton( effect ) );
document.body.appendChild( WEBVR.getButton( display, renderer.domElement ) );
}
} );
//
......@@ -153,6 +143,12 @@
gamepadHelper.geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 0, 0, - 10 ], 3 ) );
gamepad.add( gamepadHelper );
renderer.domElement.addEventListener( 'click', function ( event ) {
gamepadHelper.material.color.setHex( Math.random() * 0xffffff );
} );
//
window.addEventListener( 'resize', onWindowResize, false );
......@@ -164,7 +160,7 @@
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
effect.setSize( window.innerWidth, window.innerHeight );
renderer.setSize( window.innerWidth, window.innerHeight );
}
......@@ -172,9 +168,10 @@
function animate() {
effect.requestAnimationFrame( animate );
render();
gamepad.update();
render();
( vrdisplay ? vrdisplay : window ).requestAnimationFrame( animate );
}
......@@ -215,8 +212,6 @@
var cube = room.children[ i ];
cube.userData.velocity.multiplyScalar( 1 - ( 0.001 * delta ) );
cube.position.add( cube.userData.velocity );
if ( cube.position.x < - 3 || cube.position.x > 3 ) {
......@@ -246,8 +241,7 @@
}
controls.update();
effect.render( scene, camera );
renderer.render( scene, camera );
}
......
......@@ -31,9 +31,10 @@
"build-test": "rollup -c test/rollup.unit.config.js",
"build-uglify": "rollup -c && uglifyjs build/three.js -cm --preamble \"// threejs.org/license\" > build/three.min.js",
"build-closure": "rollup -c && java -jar utils/build/compiler/closure-compiler-v20160713.jar --warning_level=VERBOSE --jscomp_off=globalThis --jscomp_off=checkTypes --externs utils/build/externs.js --language_in=ECMASCRIPT5_STRICT --js build/three.js --js_output_file build/three.min.js",
"dev": "rollup -c -w",
"dev": "rollup -c -w -m inline",
"lint": "eslint src",
"test": "rollup -c test/rollup.unit.config.js -w"
"test": "rollup -c test/rollup.unit.config.js -w",
"editor": "electron ./editor/main.js"
},
"keywords": [
"three",
......@@ -53,6 +54,7 @@
"qunitjs": "^2.1.1",
"rollup": "^0.41.4",
"rollup-watch": "^3.2.2",
"uglify-js": "^2.6.0"
"uglify-js": "^2.6.0",
"electron": "^1.6.1"
}
}
......@@ -61,6 +61,7 @@ export { StereoCamera } from './cameras/StereoCamera.js';
export { PerspectiveCamera } from './cameras/PerspectiveCamera.js';
export { OrthographicCamera } from './cameras/OrthographicCamera.js';
export { CubeCamera } from './cameras/CubeCamera.js';
export { ArrayCamera } from './cameras/ArrayCamera.js';
export { Camera } from './cameras/Camera.js';
export { AudioListener } from './audio/AudioListener.js';
export { PositionalAudio } from './audio/PositionalAudio.js';
......
/**
* @author mrdoob / http://mrdoob.com/
*/
import { PerspectiveCamera } from './PerspectiveCamera';
function ArrayCamera( array ) {
PerspectiveCamera.call( this );
this.enabled = false;
this.cameras = array || [];
}
ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
constructor: ArrayCamera,
isArrayCamera: true
} );
export { ArrayCamera };
import { Matrix4 } from '../math/Matrix4';
import { Quaternion } from '../math/Quaternion';
import { Object3D } from '../core/Object3D';
import { Vector3 } from '../math/Vector3';
/**
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
* @author WestLangley / http://github.com/WestLangley
*/
import { Matrix4 } from '../math/Matrix4';
import { Quaternion } from '../math/Quaternion';
import { Object3D } from '../core/Object3D';
import { Vector3 } from '../math/Vector3';
function Camera() {
Object3D.call( this );
......@@ -20,43 +20,45 @@ function Camera() {
}
Camera.prototype = Object.create( Object3D.prototype );
Camera.prototype.constructor = Camera;
Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Camera,
Camera.prototype.isCamera = true;
isCamera: true,
Camera.prototype.getWorldDirection = function () {
copy: function ( source ) {
var quaternion = new Quaternion();
Object3D.prototype.copy.call( this, source );
return function getWorldDirection( optionalTarget ) {
this.matrixWorldInverse.copy( source.matrixWorldInverse );
this.projectionMatrix.copy( source.projectionMatrix );
var result = optionalTarget || new Vector3();
return this;
this.getWorldQuaternion( quaternion );
},
return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
getWorldDirection: function () {
};
var quaternion = new Quaternion();
}();
return function getWorldDirection( optionalTarget ) {
Camera.prototype.clone = function () {
var result = optionalTarget || new Vector3();
return new this.constructor().copy( this );
this.getWorldQuaternion( quaternion );
};
return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
Camera.prototype.copy = function ( source ) {
};
Object3D.prototype.copy.call( this, source );
}(),
this.matrixWorldInverse.copy( source.matrixWorldInverse );
this.projectionMatrix.copy( source.projectionMatrix );
clone: function () {
return this;
return new this.constructor().copy( this );
};
}
} );
export { Camera };
......@@ -161,7 +161,7 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ),
},
clearViewOffset: function() {
clearViewOffset: function () {
this.view = null;
this.updateProjectionMatrix();
......
......@@ -47,6 +47,7 @@ Object.assign( Clock.prototype, {
if ( this.autoStart && ! this.running ) {
this.start();
return 0;
}
......
......@@ -641,11 +641,9 @@ ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
}
if (options.extrudeMaterial !== undefined){
scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
}
scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
}
......
......@@ -14,8 +14,6 @@ function SkinnedMesh( geometry, material ) {
Mesh.call( this, geometry, material );
if ( this.material.skinning === false ) console.warn( 'THREE.SkinnedMesh: Material must have skinning set to true.', this.material );
this.type = 'SkinnedMesh';
this.bindMode = 'attached';
......
......@@ -1060,6 +1060,8 @@ function WebGLRenderer( parameters ) {
// update camera matrices and frustum
camera.onBeforeRender( _this );
if ( camera.parent === null ) camera.updateMatrixWorld();
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
......@@ -1208,6 +1210,7 @@ function WebGLRenderer( parameters ) {
// opaque pass (front-to-back order)
state.setBlending( NoBlending );
if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
// transparent pass (back-to-front order)
......@@ -1235,6 +1238,14 @@ function WebGLRenderer( parameters ) {
state.buffers.depth.setMask( true );
state.buffers.color.setMask( true );
if ( camera.isArrayCamera && camera.enabled ) {
_this.setScissorTest( false );
}
camera.onAfterRender( _this );
// _gl.finish();
};
......@@ -1401,22 +1412,30 @@ function WebGLRenderer( parameters ) {
object.onBeforeRender( _this, scene, camera, geometry, material, group );
object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
if ( object.isImmediateRenderObject ) {
if ( camera.isArrayCamera && camera.enabled ) {
state.setMaterial( material );
var cameras = camera.cameras;
var program = setProgram( camera, scene.fog, material, object );
for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
_currentGeometryProgram = '';
var camera2 = cameras[ j ];
var bounds = camera2.bounds;
_this.setViewport(
bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
);
_this.setScissor(
bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
);
_this.setScissorTest( true );
renderObject( object, scene, camera2, geometry, material, group );
renderObjectImmediate( object, program, material );
}
} else {
_this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
renderObject( object, scene, camera, geometry, material, group );
}
......@@ -1426,6 +1445,29 @@ function WebGLRenderer( parameters ) {
}
function renderObject( object, scene, camera, geometry, material, group ) {
object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
if ( object.isImmediateRenderObject ) {
state.setMaterial( material );
var program = setProgram( camera, scene.fog, material, object );
_currentGeometryProgram = '';
renderObjectImmediate( object, program, material );
} else {
_this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
}
}
function initMaterial( material, fog, object ) {
var materialProperties = properties.get( material );
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册