From b3c6512d7c9f807f3a129983926efddecb15ea91 Mon Sep 17 00:00:00 2001 From: Rich-Harris Date: Fri, 8 Jul 2016 23:58:38 -0400 Subject: [PATCH 1/4] convert to ES modules --- package.json | 7 +- rollup.config.js | 20 + src/Three.js | 572 ++++++++---------- src/animation/AnimationAction.js | 36 +- src/animation/AnimationClip.js | 51 +- src/animation/AnimationMixer.js | 32 +- src/animation/AnimationObjectGroup.js | 21 +- src/animation/AnimationUtils.js | 9 +- src/animation/KeyframeTrack.js | 395 +----------- src/animation/KeyframeTrackConstructor.js | 26 + src/animation/KeyframeTrackPrototype.js | 345 +++++++++++ src/animation/PropertyBinding.js | 42 +- src/animation/PropertyMixer.js | 14 +- src/animation/tracks/BooleanKeyframeTrack.js | 20 +- src/animation/tracks/ColorKeyframeTrack.js | 17 +- src/animation/tracks/NumberKeyframeTrack.js | 17 +- .../tracks/QuaternionKeyframeTrack.js | 23 +- src/animation/tracks/StringKeyframeTrack.js | 20 +- src/animation/tracks/VectorKeyframeTrack.js | 17 +- src/audio/Audio.js | 14 +- src/audio/AudioAnalyser.js | 8 +- src/audio/AudioContext.js | 30 +- src/audio/AudioListener.js | 29 +- src/audio/PositionalAudio.js | 20 +- src/cameras/Camera.js | 37 +- src/cameras/CubeCamera.js | 46 +- src/cameras/OrthographicCamera.js | 19 +- src/cameras/PerspectiveCamera.js | 30 +- src/cameras/StereoCamera.js | 22 +- src/constants.js | 122 ++++ src/core/BufferAttribute.js | 88 ++- src/core/BufferGeometry.js | 106 ++-- src/core/Clock.js | 10 +- src/core/DirectGeometry.js | 26 +- src/core/EventDispatcher.js | 8 +- src/core/Face3.js | 17 +- src/core/Geometry.js | 81 ++- src/core/InstancedBufferAttribute.js | 18 +- src/core/InstancedBufferGeometry.js | 18 +- src/core/InstancedInterleavedBuffer.js | 18 +- src/core/InterleavedBuffer.js | 14 +- src/core/InterleavedBufferAttribute.js | 14 +- src/core/Layers.js | 10 +- src/core/Object3D.js | 94 +-- src/core/Raycaster.js | 150 ++--- src/core/Uniform.js | 10 +- src/extras/CurveUtils.js | 7 +- src/extras/SceneUtils.js | 17 +- src/extras/ShapeUtils.js | 13 +- src/extras/core/Curve.js | 14 +- src/extras/core/CurvePath.js | 27 +- src/extras/core/Font.js | 15 +- src/extras/core/Path.js | 156 +---- src/extras/core/PathPrototype.js | 131 ++++ src/extras/core/Shape.js | 21 +- src/extras/curves/ArcCurve.js | 14 +- src/extras/curves/CatmullRomCurve3.js | 16 +- src/extras/curves/ClosedSplineCurve3.js | 12 +- src/extras/curves/CubicBezierCurve.js | 27 +- src/extras/curves/CubicBezierCurve3.js | 15 +- src/extras/curves/EllipseCurve.js | 17 +- src/extras/curves/LineCurve.js | 18 +- src/extras/curves/LineCurve3.js | 12 +- src/extras/curves/QuadraticBezierCurve.js | 27 +- src/extras/curves/QuadraticBezierCurve3.js | 15 +- src/extras/curves/SplineCurve.js | 20 +- src/extras/curves/SplineCurve3.js | 15 +- src/extras/geometries/BoxBufferGeometry.js | 26 +- src/extras/geometries/BoxGeometry.js | 21 +- src/extras/geometries/CircleBufferGeometry.js | 27 +- src/extras/geometries/CircleGeometry.js | 17 +- src/extras/geometries/ConeBufferGeometry.js | 15 +- src/extras/geometries/ConeGeometry.js | 14 +- .../geometries/CylinderBufferGeometry.js | 33 +- src/extras/geometries/CylinderGeometry.js | 17 +- src/extras/geometries/DodecahedronGeometry.js | 14 +- src/extras/geometries/EdgesGeometry.js | 25 +- src/extras/geometries/ExtrudeGeometry.js | 75 ++- src/extras/geometries/IcosahedronGeometry.js | 14 +- src/extras/geometries/LatheBufferGeometry.js | 36 +- src/extras/geometries/LatheGeometry.js | 17 +- src/extras/geometries/OctahedronGeometry.js | 14 +- src/extras/geometries/ParametricGeometry.js | 28 +- src/extras/geometries/PlaneBufferGeometry.js | 23 +- src/extras/geometries/PlaneGeometry.js | 17 +- src/extras/geometries/PolyhedronGeometry.js | 34 +- src/extras/geometries/RingBufferGeometry.js | 29 +- src/extras/geometries/RingGeometry.js | 17 +- src/extras/geometries/ShapeGeometry.js | 34 +- src/extras/geometries/SphereBufferGeometry.js | 29 +- src/extras/geometries/SphereGeometry.js | 17 +- src/extras/geometries/TetrahedronGeometry.js | 14 +- src/extras/geometries/TextGeometry.js | 19 +- src/extras/geometries/TorusBufferGeometry.js | 30 +- src/extras/geometries/TorusGeometry.js | 17 +- .../geometries/TorusKnotBufferGeometry.js | 41 +- src/extras/geometries/TorusKnotGeometry.js | 17 +- src/extras/geometries/TubeGeometry.js | 59 +- src/extras/geometries/WireframeGeometry.js | 25 +- src/extras/helpers/ArrowHelper.js | 41 +- src/extras/helpers/AxisHelper.js | 26 +- src/extras/helpers/BoundingBoxHelper.js | 21 +- src/extras/helpers/BoxHelper.js | 30 +- src/extras/helpers/CameraHelper.js | 34 +- src/extras/helpers/DirectionalLightHelper.js | 43 +- src/extras/helpers/EdgesHelper.js | 16 +- src/extras/helpers/FaceNormalsHelper.js | 33 +- src/extras/helpers/GridHelper.js | 33 +- src/extras/helpers/HemisphereLightHelper.js | 34 +- src/extras/helpers/PointLightHelper.js | 24 +- src/extras/helpers/SkeletonHelper.js | 46 +- src/extras/helpers/SpotLightHelper.js | 35 +- src/extras/helpers/VertexNormalsHelper.js | 39 +- src/extras/helpers/WireframeHelper.js | 16 +- src/extras/objects/ImmediateRenderObject.js | 14 +- src/extras/objects/MorphBlendMesh.js | 43 +- src/lights/AmbientLight.js | 14 +- src/lights/DirectionalLight.js | 24 +- src/lights/DirectionalLightShadow.js | 15 +- src/lights/HemisphereLight.js | 22 +- src/lights/Light.js | 21 +- src/lights/LightShadow.js | 15 +- src/lights/PointLight.js | 20 +- src/lights/SpotLight.js | 24 +- src/lights/SpotLightShadow.js | 18 +- src/loaders/AnimationLoader.js | 18 +- src/loaders/AudioLoader.js | 18 +- src/loaders/BinaryTextureLoader.js | 29 +- src/loaders/BufferGeometryLoader.js | 29 +- src/loaders/Cache.js | 7 +- src/loaders/CompressedTextureLoader.js | 23 +- src/loaders/CubeTextureLoader.js | 18 +- src/loaders/FontLoader.js | 18 +- src/loaders/ImageLoader.js | 15 +- src/loaders/JSONLoader.js | 61 +- src/loaders/Loader.js | 50 +- src/loaders/LoadingManager.js | 10 +- src/loaders/MaterialLoader.js | 21 +- src/loaders/ObjectLoader.js | 86 ++- src/loaders/TextureLoader.js | 21 +- src/loaders/XHRLoader.js | 17 +- src/materials/LineBasicMaterial.js | 21 +- src/materials/LineDashedMaterial.js | 21 +- src/materials/Material.js | 79 +-- src/materials/MeshBasicMaterial.js | 24 +- src/materials/MeshDepthMaterial.js | 21 +- src/materials/MeshLambertMaterial.js | 26 +- src/materials/MeshNormalMaterial.js | 18 +- src/materials/MeshPhongMaterial.js | 31 +- src/materials/MeshPhysicalMaterial.js | 18 +- src/materials/MeshStandardMaterial.js | 26 +- src/materials/MultiMaterial.js | 14 +- src/materials/PointsMaterial.js | 21 +- src/materials/RawShaderMaterial.js | 14 +- src/materials/ShaderMaterial.js | 25 +- src/materials/ShadowMaterial.js | 25 +- src/materials/SpriteMaterial.js | 21 +- src/math/Box2.js | 28 +- src/math/Box3.js | 59 +- src/math/Color.js | 26 +- src/math/Euler.js | 29 +- src/math/Frustum.js | 34 +- src/math/Interpolant.js | 16 +- src/math/Line3.js | 31 +- src/math/Math.js | 11 +- src/math/Matrix3.js | 18 +- src/math/Matrix4.js | 37 +- src/math/Plane.js | 31 +- src/math/Quaternion.js | 18 +- src/math/Ray.js | 42 +- src/math/Sphere.js | 21 +- src/math/Spherical.js | 14 +- src/math/Spline.js | 14 +- src/math/Triangle.js | 66 +- src/math/Vector2.js | 14 +- src/math/Vector3.js | 34 +- src/math/Vector4.js | 14 +- src/math/interpolants/CubicInterpolant.js | 30 +- src/math/interpolants/DiscreteInterpolant.js | 16 +- src/math/interpolants/LinearInterpolant.js | 16 +- .../QuaternionLinearInterpolant.js | 19 +- src/objects/Bone.js | 16 +- src/objects/Group.js | 14 +- src/objects/LOD.js | 25 +- src/objects/LensFlare.js | 25 +- src/objects/Line.js | 47 +- src/objects/LineSegments.js | 14 +- src/objects/Mesh.js | 76 ++- src/objects/Points.js | 34 +- src/objects/Skeleton.js | 29 +- src/objects/SkinnedMesh.js | 34 +- src/objects/Sprite.js | 20 +- src/renderers/WebGLRenderTarget.js | 24 +- src/renderers/WebGLRenderTargetCube.js | 14 +- src/renderers/WebGLRenderer.js | 375 ++++++------ src/renderers/shaders/ShaderChunk.js | 113 +++- .../ShaderChunk/alphamap_fragment.glsl | 5 - .../ShaderChunk/alphamap_pars_fragment.glsl | 5 - .../ShaderChunk/alphatest_fragment.glsl | 5 - .../shaders/ShaderChunk/ambient_pars.glsl | 15 - .../shaders/ShaderChunk/aomap_fragment.glsl | 15 - .../ShaderChunk/aomap_pars_fragment.glsl | 6 - .../shaders/ShaderChunk/begin_vertex.glsl | 2 - .../ShaderChunk/beginnormal_vertex.glsl | 2 - src/renderers/shaders/ShaderChunk/bsdfs.glsl | 179 ------ .../ShaderChunk/bumpmap_pars_fragment.glsl | 40 -- .../ShaderChunk/clipping_planes_fragment.glsl | 10 - .../clipping_planes_pars_fragment.glsl | 9 - .../clipping_planes_pars_vertex.glsl | 3 - .../ShaderChunk/clipping_planes_vertex.glsl | 4 - .../shaders/ShaderChunk/color_fragment.glsl | 5 - .../ShaderChunk/color_pars_fragment.glsl | 5 - .../ShaderChunk/color_pars_vertex.glsl | 5 - .../shaders/ShaderChunk/color_vertex.glsl | 5 - src/renderers/shaders/ShaderChunk/common.glsl | 74 --- .../cube_uv_reflection_fragment.glsl | 128 ---- .../ShaderChunk/defaultnormal_vertex.glsl | 7 - .../displacementmap_pars_vertex.glsl | 7 - .../ShaderChunk/displacementmap_vertex.glsl | 5 - .../ShaderChunk/emissivemap_fragment.glsl | 9 - .../emissivemap_pars_fragment.glsl | 5 - .../ShaderChunk/encodings_fragment.glsl | 1 - .../ShaderChunk/encodings_pars_fragment.glsl | 78 --- .../shaders/ShaderChunk/envmap_fragment.glsl | 60 -- .../ShaderChunk/envmap_pars_fragment.glsl | 25 - .../ShaderChunk/envmap_pars_vertex.glsl | 13 - .../shaders/ShaderChunk/envmap_vertex.glsl | 25 - .../shaders/ShaderChunk/fog_fragment.glsl | 25 - .../ShaderChunk/fog_pars_fragment.glsl | 15 - .../ShaderChunk/lightmap_fragment.glsl | 5 - .../ShaderChunk/lightmap_pars_fragment.glsl | 6 - .../ShaderChunk/lights_lambert_vertex.glsl | 99 --- .../shaders/ShaderChunk/lights_pars.glsl | 300 --------- .../ShaderChunk/lights_phong_fragment.glsl | 5 - .../lights_phong_pars_fragment.glsl | 45 -- .../ShaderChunk/lights_physical_fragment.glsl | 10 - .../lights_physical_pars_fragment.glsl | 91 --- .../shaders/ShaderChunk/lights_template.glsl | 136 ----- .../ShaderChunk/logdepthbuf_fragment.glsl | 5 - .../logdepthbuf_pars_fragment.glsl | 11 - .../ShaderChunk/logdepthbuf_pars_vertex.glsl | 11 - .../ShaderChunk/logdepthbuf_vertex.glsl | 15 - .../shaders/ShaderChunk/map_fragment.glsl | 8 - .../ShaderChunk/map_pars_fragment.glsl | 5 - .../ShaderChunk/map_particle_fragment.glsl | 6 - .../map_particle_pars_fragment.glsl | 6 - .../ShaderChunk/metalnessmap_fragment.glsl | 8 - .../metalnessmap_pars_fragment.glsl | 5 - .../ShaderChunk/morphnormal_vertex.glsl | 8 - .../ShaderChunk/morphtarget_pars_vertex.glsl | 13 - .../ShaderChunk/morphtarget_vertex.glsl | 17 - .../shaders/ShaderChunk/normal_flip.glsl | 5 - .../shaders/ShaderChunk/normal_fragment.glsl | 23 - .../ShaderChunk/normalmap_pars_fragment.glsl | 27 - .../shaders/ShaderChunk/packing.glsl | 45 -- .../premultiplied_alpha_fragment.glsl | 6 - .../shaders/ShaderChunk/project_vertex.glsl | 11 - .../ShaderChunk/roughnessmap_fragment.glsl | 8 - .../roughnessmap_pars_fragment.glsl | 5 - .../ShaderChunk/shadowmap_pars_fragment.glsl | 231 ------- .../ShaderChunk/shadowmap_pars_vertex.glsl | 24 - .../shaders/ShaderChunk/shadowmap_vertex.glsl | 33 - .../ShaderChunk/shadowmask_pars_fragment.glsl | 50 -- .../shaders/ShaderChunk/skinbase_vertex.glsl | 8 - .../ShaderChunk/skinning_pars_vertex.glsl | 47 -- .../shaders/ShaderChunk/skinning_vertex.glsl | 12 - .../ShaderChunk/skinnormal_vertex.glsl | 12 - .../ShaderChunk/specularmap_fragment.glsl | 12 - .../specularmap_pars_fragment.glsl | 5 - .../ShaderChunk/tonemapping_fragment.glsl | 5 - .../tonemapping_pars_fragment.glsl | 39 -- .../ShaderChunk/uv2_pars_fragment.glsl | 5 - .../shaders/ShaderChunk/uv2_pars_vertex.glsl | 6 - .../shaders/ShaderChunk/uv2_vertex.glsl | 5 - .../shaders/ShaderChunk/uv_pars_fragment.glsl | 5 - .../shaders/ShaderChunk/uv_pars_vertex.glsl | 6 - .../shaders/ShaderChunk/uv_vertex.glsl | 5 - .../shaders/ShaderChunk/worldpos_vertex.glsl | 13 - src/renderers/shaders/ShaderLib.js | 161 ++--- .../shaders/ShaderLib/cube_frag.glsl | 14 - .../shaders/ShaderLib/cube_vert.glsl | 12 - .../shaders/ShaderLib/depth_frag.glsl | 43 -- .../shaders/ShaderLib/depth_vert.glsl | 23 - .../shaders/ShaderLib/distanceRGBA_frag.glsl | 14 - .../shaders/ShaderLib/distanceRGBA_vert.glsl | 20 - .../shaders/ShaderLib/equirect_frag.glsl | 17 - .../shaders/ShaderLib/equirect_vert.glsl | 12 - .../shaders/ShaderLib/linedashed_frag.glsl | 40 -- .../shaders/ShaderLib/linedashed_vert.glsl | 23 - .../shaders/ShaderLib/meshbasic_frag.glsl | 56 -- .../shaders/ShaderLib/meshbasic_vert.glsl | 37 -- .../shaders/ShaderLib/meshlambert_frag.glsl | 83 --- .../shaders/ShaderLib/meshlambert_vert.glsl | 48 -- .../shaders/ShaderLib/meshphong_frag.glsl | 67 -- .../shaders/ShaderLib/meshphong_vert.glsl | 55 -- .../shaders/ShaderLib/meshphysical_frag.glsl | 84 --- .../shaders/ShaderLib/meshphysical_vert.glsl | 54 -- .../shaders/ShaderLib/normal_frag.glsl | 16 - .../shaders/ShaderLib/normal_vert.glsl | 18 - .../shaders/ShaderLib/points_frag.glsl | 33 - .../shaders/ShaderLib/points_vert.glsl | 27 - .../shaders/ShaderLib/shadow_frag.glsl | 14 - .../shaders/ShaderLib/shadow_vert.glsl | 10 - src/renderers/shaders/UniformsLib.js | 23 +- src/renderers/shaders/UniformsUtils.js | 21 +- src/renderers/webgl/WebGLBufferRenderer.js | 8 +- src/renderers/webgl/WebGLCapabilities.js | 6 +- src/renderers/webgl/WebGLClipping.js | 13 +- src/renderers/webgl/WebGLExtensions.js | 6 +- src/renderers/webgl/WebGLGeometries.js | 18 +- .../webgl/WebGLIndexedBufferRenderer.js | 6 +- src/renderers/webgl/WebGLLights.js | 36 +- src/renderers/webgl/WebGLObjects.js | 19 +- src/renderers/webgl/WebGLProgram.js | 82 +-- src/renderers/webgl/WebGLPrograms.js | 33 +- src/renderers/webgl/WebGLProperties.js | 6 +- src/renderers/webgl/WebGLShader.js | 7 +- src/renderers/webgl/WebGLShadowMap.js | 80 ++- src/renderers/webgl/WebGLState.js | 72 ++- src/renderers/webgl/WebGLTextures.js | 61 +- src/renderers/webgl/WebGLUniforms.js | 14 +- .../webgl/plugins/LensFlarePlugin.js | 20 +- src/renderers/webgl/plugins/SpritePlugin.js | 22 +- src/scenes/Fog.js | 14 +- src/scenes/FogExp2.js | 14 +- src/scenes/Scene.js | 18 +- src/textures/CanvasTexture.js | 14 +- src/textures/CompressedTexture.js | 14 +- src/textures/CubeTexture.js | 19 +- src/textures/DataTexture.js | 19 +- src/textures/DepthTexture.js | 21 +- src/textures/Texture.js | 67 +- src/textures/VideoTexture.js | 14 +- 333 files changed, 5041 insertions(+), 6184 deletions(-) create mode 100644 rollup.config.js create mode 100644 src/animation/KeyframeTrackConstructor.js create mode 100644 src/animation/KeyframeTrackPrototype.js create mode 100644 src/constants.js create mode 100644 src/extras/core/PathPrototype.js mode change 100755 => 100644 src/loaders/ObjectLoader.js delete mode 100644 src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/ambient_pars.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/aomap_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/begin_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/bsdfs.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/color_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/color_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/common.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/encodings_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/envmap_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/envmap_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/fog_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/lights_pars.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/lights_template.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/map_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/normal_flip.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/normal_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/packing.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/project_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/skinning_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/uv2_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/uv_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl delete mode 100644 src/renderers/shaders/ShaderLib/cube_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/cube_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/depth_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/depth_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/equirect_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/equirect_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/linedashed_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/linedashed_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/meshbasic_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/meshbasic_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/meshlambert_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/meshlambert_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/meshphong_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/meshphong_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/meshphysical_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/meshphysical_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/normal_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/normal_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/points_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/points_vert.glsl delete mode 100644 src/renderers/shaders/ShaderLib/shadow_frag.glsl delete mode 100644 src/renderers/shaders/ShaderLib/shadow_vert.glsl diff --git a/package.json b/package.json index 20d7231d9a1665..db6a107fcfd3f5 100644 --- a/package.json +++ b/package.json @@ -20,9 +20,9 @@ "test": "test" }, "scripts": { - "build": "node utils/build/build.js --include common --include extras", - "build-min": "node utils/build/build.js --include common --include extras --minify", - "dev": "chokidar \"./src/**/*.*\" \"./utils/build/includes/*.*\" --initial -c \"npm run build\"", + "build": "rollup -c", + "build-min": "rollup -c && uglifyjs build/three.js -cm > build/three.min.js", + "dev": "rollup -c -w", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { @@ -45,6 +45,7 @@ "argparse": "^1.0.3", "chokidar-cli": "1.2.0", "jscs": "^1.13.1", + "rollup": "^0.33.1", "uglify-js": "^2.6.0" } } diff --git a/rollup.config.js b/rollup.config.js new file mode 100644 index 00000000000000..9c28007742bbad --- /dev/null +++ b/rollup.config.js @@ -0,0 +1,20 @@ +import * as fs from 'fs'; + +var outro = ` +Object.defineProperty( exports, 'AudioContext', { + get: function () { + return exports.getAudioContext(); + } +});`; + +var footer = fs.readFileSync( 'src/Three.Legacy.js', 'utf-8' ); + +export default { + entry: 'src/Three.js', + dest: 'build/three.js', + moduleName: 'THREE', + format: 'umd', + + outro: outro, + footer: footer +}; diff --git a/src/Three.js b/src/Three.js index 935c206ae21d5d..a752a822f5b085 100644 --- a/src/Three.js +++ b/src/Three.js @@ -1,335 +1,237 @@ -/** - * @author mrdoob / http://mrdoob.com/ - */ - -var THREE = { REVISION: '79dev' }; - -// - -if ( typeof define === 'function' && define.amd ) { - - define( 'three', THREE ); - -} else if ( 'undefined' !== typeof exports && 'undefined' !== typeof module ) { - - module.exports = THREE; - -} - -// Polyfills - -if ( Number.EPSILON === undefined ) { - - Number.EPSILON = Math.pow( 2, - 52 ); - -} - -// - -if ( Math.sign === undefined ) { - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign - - Math.sign = function ( x ) { - - return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; - - }; - -} - -if ( Function.prototype.name === undefined ) { - - // Missing in IE9-11. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name - - Object.defineProperty( Function.prototype, 'name', { - - get: function () { - - return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; - - } - - } ); - -} - -if ( Object.assign === undefined ) { - - // Missing in IE. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - - ( function () { - - Object.assign = function ( target ) { - - 'use strict'; - - if ( target === undefined || target === null ) { - - throw new TypeError( 'Cannot convert undefined or null to object' ); - - } - - var output = Object( target ); - - for ( var index = 1; index < arguments.length; index ++ ) { - - var source = arguments[ index ]; - - if ( source !== undefined && source !== null ) { - - for ( var nextKey in source ) { - - if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { - - output[ nextKey ] = source[ nextKey ]; - - } - - } - - } - - } - - return output; - - }; - - } )(); - -} - -// - -Object.assign( THREE, { - - // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button - - MOUSE: { LEFT: 0, MIDDLE: 1, RIGHT: 2 }, - - // GL STATE CONSTANTS - - CullFaceNone: 0, - CullFaceBack: 1, - CullFaceFront: 2, - CullFaceFrontBack: 3, - - FrontFaceDirectionCW: 0, - FrontFaceDirectionCCW: 1, - - // SHADOWING TYPES - - BasicShadowMap: 0, - PCFShadowMap: 1, - PCFSoftShadowMap: 2, - - // MATERIAL CONSTANTS - - // side - - FrontSide: 0, - BackSide: 1, - DoubleSide: 2, - - // shading - - FlatShading: 1, - SmoothShading: 2, - - // colors - - NoColors: 0, - FaceColors: 1, - VertexColors: 2, - - // blending modes - - NoBlending: 0, - NormalBlending: 1, - AdditiveBlending: 2, - SubtractiveBlending: 3, - MultiplyBlending: 4, - CustomBlending: 5, - - // custom blending equations - // (numbers start from 100 not to clash with other - // mappings to OpenGL constants defined in Texture.js) - - AddEquation: 100, - SubtractEquation: 101, - ReverseSubtractEquation: 102, - MinEquation: 103, - MaxEquation: 104, - - // custom blending destination factors - - ZeroFactor: 200, - OneFactor: 201, - SrcColorFactor: 202, - OneMinusSrcColorFactor: 203, - SrcAlphaFactor: 204, - OneMinusSrcAlphaFactor: 205, - DstAlphaFactor: 206, - OneMinusDstAlphaFactor: 207, - - // custom blending source factors - - //ZeroFactor: 200, - //OneFactor: 201, - //SrcAlphaFactor: 204, - //OneMinusSrcAlphaFactor: 205, - //DstAlphaFactor: 206, - //OneMinusDstAlphaFactor: 207, - DstColorFactor: 208, - OneMinusDstColorFactor: 209, - SrcAlphaSaturateFactor: 210, - - // depth modes - - NeverDepth: 0, - AlwaysDepth: 1, - LessDepth: 2, - LessEqualDepth: 3, - EqualDepth: 4, - GreaterEqualDepth: 5, - GreaterDepth: 6, - NotEqualDepth: 7, - - - // TEXTURE CONSTANTS - - MultiplyOperation: 0, - MixOperation: 1, - AddOperation: 2, - - // Tone Mapping modes - - NoToneMapping: 0, // do not do any tone mapping, not even exposure (required for special purpose passes.) - LinearToneMapping: 1, // only apply exposure. - ReinhardToneMapping: 2, - Uncharted2ToneMapping: 3, // John Hable - CineonToneMapping: 4, // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson - - // Mapping modes - - UVMapping: 300, - - CubeReflectionMapping: 301, - CubeRefractionMapping: 302, - - EquirectangularReflectionMapping: 303, - EquirectangularRefractionMapping: 304, - - SphericalReflectionMapping: 305, - CubeUVReflectionMapping: 306, - CubeUVRefractionMapping: 307, - - // Wrapping modes - - RepeatWrapping: 1000, - ClampToEdgeWrapping: 1001, - MirroredRepeatWrapping: 1002, - - // Filters - - NearestFilter: 1003, - NearestMipMapNearestFilter: 1004, - NearestMipMapLinearFilter: 1005, - LinearFilter: 1006, - LinearMipMapNearestFilter: 1007, - LinearMipMapLinearFilter: 1008, - - // Data types - - UnsignedByteType: 1009, - ByteType: 1010, - ShortType: 1011, - UnsignedShortType: 1012, - IntType: 1013, - UnsignedIntType: 1014, - FloatType: 1015, - HalfFloatType: 1025, - - // Pixel types - - //UnsignedByteType: 1009, - UnsignedShort4444Type: 1016, - UnsignedShort5551Type: 1017, - UnsignedShort565Type: 1018, - - // Pixel formats - - AlphaFormat: 1019, - RGBFormat: 1020, - RGBAFormat: 1021, - LuminanceFormat: 1022, - LuminanceAlphaFormat: 1023, - // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders - RGBEFormat: THREE.RGBAFormat, //1024; - DepthFormat: 1026, - - // DDS / ST3C Compressed texture formats - - RGB_S3TC_DXT1_Format: 2001, - RGBA_S3TC_DXT1_Format: 2002, - RGBA_S3TC_DXT3_Format: 2003, - RGBA_S3TC_DXT5_Format: 2004, - - // PVRTC compressed texture formats - - RGB_PVRTC_4BPPV1_Format: 2100, - RGB_PVRTC_2BPPV1_Format: 2101, - RGBA_PVRTC_4BPPV1_Format: 2102, - RGBA_PVRTC_2BPPV1_Format: 2103, - - // ETC compressed texture formats - - RGB_ETC1_Format: 2151, - - // Loop styles for AnimationAction - - LoopOnce: 2200, - LoopRepeat: 2201, - LoopPingPong: 2202, - - // Interpolation - - InterpolateDiscrete: 2300, - InterpolateLinear: 2301, - InterpolateSmooth: 2302, - - // Interpolant ending modes - - ZeroCurvatureEnding: 2400, - ZeroSlopeEnding: 2401, - WrapAroundEnding: 2402, - - // Triangle Draw modes - - TrianglesDrawMode: 0, - TriangleStripDrawMode: 1, - TriangleFanDrawMode: 2, - - // Texture Encodings - - LinearEncoding: 3000, // No encoding at all. - sRGBEncoding: 3001, - GammaEncoding: 3007, // uses GAMMA_FACTOR, for backwards compatibility with WebGLRenderer.gammaInput/gammaOutput - - // The following Texture Encodings are for RGB-only (no alpha) HDR light emission sources. - // These encodings should not specified as output encodings except in rare situations. - RGBEEncoding: 3002, // AKA Radiance. - LogLuvEncoding: 3003, - RGBM7Encoding: 3004, - RGBM16Encoding: 3005, - RGBDEncoding: 3006, // MaxRange is 256. - - // Depth packing strategies - - BasicDepthPacking: 3200, // for writing to float textures for high precision or for visualizing results in RGB buffers - RGBADepthPacking: 3201 // for packing into RGBA buffers. - -} ); +export { SpritePlugin } from './renderers/webgl/plugins/SpritePlugin.js'; +export { LensFlarePlugin } from './renderers/webgl/plugins/LensFlarePlugin.js'; +export { WebGLUniforms } from './renderers/webgl/WebGLUniforms.js'; +export { WebGLTextures } from './renderers/webgl/WebGLTextures.js'; +export { + WebGLStencilBuffer, + WebGLDepthBuffer, + WebGLColorBuffer, + WebGLState +} from './renderers/webgl/WebGLState.js'; +export { WebGLShadowMap } from './renderers/webgl/WebGLShadowMap.js'; +export { WebGLShader } from './renderers/webgl/WebGLShader.js'; +export { WebGLProperties } from './renderers/webgl/WebGLProperties.js'; +export { WebGLPrograms } from './renderers/webgl/WebGLPrograms.js'; +export { WebGLProgram } from './renderers/webgl/WebGLProgram.js'; +export { WebGLObjects } from './renderers/webgl/WebGLObjects.js'; +export { WebGLLights } from './renderers/webgl/WebGLLights.js'; +export { WebGLGeometries } from './renderers/webgl/WebGLGeometries.js'; +export { WebGLCapabilities } from './renderers/webgl/WebGLCapabilities.js'; +export { WebGLExtensions } from './renderers/webgl/WebGLExtensions.js'; +export { WebGLIndexedBufferRenderer } from './renderers/webgl/WebGLIndexedBufferRenderer.js'; +export { WebGLClipping } from './renderers/webgl/WebGLClipping.js'; +export { WebGLBufferRenderer } from './renderers/webgl/WebGLBufferRenderer.js'; +export { WebGLRenderTargetCube } from './renderers/WebGLRenderTargetCube.js'; +export { WebGLRenderTarget } from './renderers/WebGLRenderTarget.js'; +export { WebGLRenderer } from './renderers/WebGLRenderer.js'; +export { ShaderLib } from './renderers/shaders/ShaderLib.js'; +export { UniformsLib } from './renderers/shaders/UniformsLib.js'; +export { UniformsUtils } from './renderers/shaders/UniformsUtils.js'; +export { ShaderChunk } from './renderers/shaders/ShaderChunk.js'; +export { FogExp2 } from './scenes/FogExp2.js'; +export { Fog } from './scenes/Fog.js'; +export { Scene } from './scenes/Scene.js'; +export { LensFlare } from './objects/LensFlare.js'; +export { Sprite } from './objects/Sprite.js'; +export { LOD } from './objects/LOD.js'; +export { SkinnedMesh } from './objects/SkinnedMesh.js'; +export { Skeleton } from './objects/Skeleton.js'; +export { Bone } from './objects/Bone.js'; +export { Mesh } from './objects/Mesh.js'; +export { LineSegments } from './objects/LineSegments.js'; +export { Line } from './objects/Line.js'; +export { Points } from './objects/Points.js'; +export { Group } from './objects/Group.js'; +export { VideoTexture } from './textures/VideoTexture.js'; +export { DataTexture } from './textures/DataTexture.js'; +export { CompressedTexture } from './textures/CompressedTexture.js'; +export { CubeTexture } from './textures/CubeTexture.js'; +export { CanvasTexture } from './textures/CanvasTexture.js'; +export { DepthTexture } from './textures/DepthTexture.js'; +export { TextureIdCount, Texture } from './textures/Texture.js'; +export { ShadowMaterial } from './materials/ShadowMaterial.js'; +export { SpriteMaterial } from './materials/SpriteMaterial.js'; +export { RawShaderMaterial } from './materials/RawShaderMaterial.js'; +export { ShaderMaterial } from './materials/ShaderMaterial.js'; +export { PointsMaterial } from './materials/PointsMaterial.js'; +export { MultiMaterial } from './materials/MultiMaterial.js'; +export { MeshPhysicalMaterial } from './materials/MeshPhysicalMaterial.js'; +export { MeshStandardMaterial } from './materials/MeshStandardMaterial.js'; +export { MeshPhongMaterial } from './materials/MeshPhongMaterial.js'; +export { MeshNormalMaterial } from './materials/MeshNormalMaterial.js'; +export { MeshLambertMaterial } from './materials/MeshLambertMaterial.js'; +export { MeshDepthMaterial } from './materials/MeshDepthMaterial.js'; +export { MeshBasicMaterial } from './materials/MeshBasicMaterial.js'; +export { LineDashedMaterial } from './materials/LineDashedMaterial.js'; +export { LineBasicMaterial } from './materials/LineBasicMaterial.js'; +export { MaterialIdCount, Material } from './materials/Material.js'; +export { CompressedTextureLoader } from './loaders/CompressedTextureLoader.js'; +export { BinaryTextureLoader, DataTextureLoader } from './loaders/BinaryTextureLoader.js'; +export { CubeTextureLoader } from './loaders/CubeTextureLoader.js'; +export { TextureLoader } from './loaders/TextureLoader.js'; +export { ObjectLoader } from './loaders/ObjectLoader.js'; +export { MaterialLoader } from './loaders/MaterialLoader.js'; +export { BufferGeometryLoader } from './loaders/BufferGeometryLoader.js'; +export { DefaultLoadingManager, LoadingManager } from './loaders/LoadingManager.js'; +export { JSONLoader } from './loaders/JSONLoader.js'; +export { ImageLoader } from './loaders/ImageLoader.js'; +export { FontLoader } from './loaders/FontLoader.js'; +export { XHRLoader } from './loaders/XHRLoader.js'; +export { Loader } from './loaders/Loader.js'; +export { Cache } from './loaders/Cache.js'; +export { AudioLoader } from './loaders/AudioLoader.js'; +export { SpotLightShadow } from './lights/SpotLightShadow.js'; +export { SpotLight } from './lights/SpotLight.js'; +export { PointLight } from './lights/PointLight.js'; +export { HemisphereLight } from './lights/HemisphereLight.js'; +export { DirectionalLightShadow } from './lights/DirectionalLightShadow.js'; +export { DirectionalLight } from './lights/DirectionalLight.js'; +export { AmbientLight } from './lights/AmbientLight.js'; +export { LightShadow } from './lights/LightShadow.js'; +export { Light } from './lights/Light.js'; +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 { Camera } from './cameras/Camera.js'; +export { AudioListener } from './audio/AudioListener.js'; +export { PositionalAudio } from './audio/PositionalAudio.js'; +export { getAudioContext } from './audio/AudioContext.js'; +export { AudioAnalyser } from './audio/AudioAnalyser.js'; +export { Audio } from './audio/Audio.js'; +export { VectorKeyframeTrack } from './animation/tracks/VectorKeyframeTrack.js'; +export { StringKeyframeTrack } from './animation/tracks/StringKeyframeTrack.js'; +export { QuaternionKeyframeTrack } from './animation/tracks/QuaternionKeyframeTrack.js'; +export { NumberKeyframeTrack } from './animation/tracks/NumberKeyframeTrack.js'; +export { ColorKeyframeTrack } from './animation/tracks/ColorKeyframeTrack.js'; +export { BooleanKeyframeTrack } from './animation/tracks/BooleanKeyframeTrack.js'; +export { PropertyMixer } from './animation/PropertyMixer.js'; +export { PropertyBinding } from './animation/PropertyBinding.js'; +export { KeyframeTrack } from './animation/KeyframeTrack.js'; +export { AnimationUtils } from './animation/AnimationUtils.js'; +export { AnimationObjectGroup } from './animation/AnimationObjectGroup.js'; +export { AnimationMixer } from './animation/AnimationMixer.js'; +export { AnimationClip } from './animation/AnimationClip.js'; +export { AnimationAction } from './animation/AnimationAction.js'; +export { Uniform } from './core/Uniform.js'; +export { InstancedBufferGeometry } from './core/InstancedBufferGeometry.js'; +export { BufferGeometry } from './core/BufferGeometry.js'; +export { DirectGeometry } from './core/DirectGeometry.js'; +export { GeometryIdCount, Geometry } from './core/Geometry.js'; +export { InterleavedBufferAttribute } from './core/InterleavedBufferAttribute.js'; +export { InstancedInterleavedBuffer } from './core/InstancedInterleavedBuffer.js'; +export { InterleavedBuffer } from './core/InterleavedBuffer.js'; +export { InstancedBufferAttribute } from './core/InstancedBufferAttribute.js'; +export { + DynamicBufferAttribute, + Float64Attribute, + Float32Attribute, + Uint32Attribute, + Int32Attribute, + Uint16Attribute, + Int16Attribute, + Uint8ClampedAttribute, + Uint8Attribute, + Int8Attribute, + BufferAttribute +} from './core/BufferAttribute.js'; +export { Face3 } from './core/Face3.js'; +export { Object3DIdCount, Object3D } from './core/Object3D.js'; +export { Raycaster } from './core/Raycaster.js'; +export { Layers } from './core/Layers.js'; +export { EventDispatcher } from './core/EventDispatcher.js'; +export { Clock } from './core/Clock.js'; +export { QuaternionLinearInterpolant } from './math/interpolants/QuaternionLinearInterpolant.js'; +export { LinearInterpolant } from './math/interpolants/LinearInterpolant.js'; +export { DiscreteInterpolant } from './math/interpolants/DiscreteInterpolant.js'; +export { CubicInterpolant } from './math/interpolants/CubicInterpolant.js'; +export { Interpolant } from './math/Interpolant.js'; +export { Triangle } from './math/Triangle.js'; +export { Spline } from './math/Spline.js'; +export { _Math as Math } from './math/Math.js'; +export { Spherical } from './math/Spherical.js'; +export { Plane } from './math/Plane.js'; +export { Frustum } from './math/Frustum.js'; +export { Sphere } from './math/Sphere.js'; +export { Ray } from './math/Ray.js'; +export { Matrix4 } from './math/Matrix4.js'; +export { Matrix3 } from './math/Matrix3.js'; +export { Box3 } from './math/Box3.js'; +export { Box2 } from './math/Box2.js'; +export { Line3 } from './math/Line3.js'; +export { Euler } from './math/Euler.js'; +export { Vector4 } from './math/Vector4.js'; +export { Vector3 } from './math/Vector3.js'; +export { Vector2 } from './math/Vector2.js'; +export { Quaternion } from './math/Quaternion.js'; +export { ColorKeywords, Color } from './math/Color.js'; +export { MorphBlendMesh } from './extras/objects/MorphBlendMesh.js'; +export { ImmediateRenderObject } from './extras/objects/ImmediateRenderObject.js'; +export { WireframeHelper } from './extras/helpers/WireframeHelper.js'; +export { VertexNormalsHelper } from './extras/helpers/VertexNormalsHelper.js'; +export { SpotLightHelper } from './extras/helpers/SpotLightHelper.js'; +export { SkeletonHelper } from './extras/helpers/SkeletonHelper.js'; +export { PointLightHelper } from './extras/helpers/PointLightHelper.js'; +export { HemisphereLightHelper } from './extras/helpers/HemisphereLightHelper.js'; +export { GridHelper } from './extras/helpers/GridHelper.js'; +export { FaceNormalsHelper } from './extras/helpers/FaceNormalsHelper.js'; +export { EdgesHelper } from './extras/helpers/EdgesHelper.js'; +export { DirectionalLightHelper } from './extras/helpers/DirectionalLightHelper.js'; +export { CameraHelper } from './extras/helpers/CameraHelper.js'; +export { BoundingBoxHelper } from './extras/helpers/BoundingBoxHelper.js'; +export { BoxHelper } from './extras/helpers/BoxHelper.js'; +export { ArrowHelper } from './extras/helpers/ArrowHelper.js'; +export { AxisHelper } from './extras/helpers/AxisHelper.js'; +export { WireframeGeometry } from './extras/geometries/WireframeGeometry.js'; +export { ParametricGeometry } from './extras/geometries/ParametricGeometry.js'; +export { TetrahedronGeometry } from './extras/geometries/TetrahedronGeometry.js'; +export { OctahedronGeometry } from './extras/geometries/OctahedronGeometry.js'; +export { IcosahedronGeometry } from './extras/geometries/IcosahedronGeometry.js'; +export { DodecahedronGeometry } from './extras/geometries/DodecahedronGeometry.js'; +export { PolyhedronGeometry } from './extras/geometries/PolyhedronGeometry.js'; +export { TubeGeometry } from './extras/geometries/TubeGeometry.js'; +export { TorusKnotGeometry } from './extras/geometries/TorusKnotGeometry.js'; +export { TorusKnotBufferGeometry } from './extras/geometries/TorusKnotBufferGeometry.js'; +export { TorusGeometry } from './extras/geometries/TorusGeometry.js'; +export { TorusBufferGeometry } from './extras/geometries/TorusBufferGeometry.js'; +export { TextGeometry } from './extras/geometries/TextGeometry.js'; +export { SphereBufferGeometry } from './extras/geometries/SphereBufferGeometry.js'; +export { SphereGeometry } from './extras/geometries/SphereGeometry.js'; +export { RingGeometry } from './extras/geometries/RingGeometry.js'; +export { RingBufferGeometry } from './extras/geometries/RingBufferGeometry.js'; +export { PlaneBufferGeometry } from './extras/geometries/PlaneBufferGeometry.js'; +export { PlaneGeometry } from './extras/geometries/PlaneGeometry.js'; +export { LatheGeometry } from './extras/geometries/LatheGeometry.js'; +export { LatheBufferGeometry } from './extras/geometries/LatheBufferGeometry.js'; +export { ShapeGeometry } from './extras/geometries/ShapeGeometry.js'; +export { ExtrudeGeometry } from './extras/geometries/ExtrudeGeometry.js'; +export { EdgesGeometry } from './extras/geometries/EdgesGeometry.js'; +export { ConeGeometry } from './extras/geometries/ConeGeometry.js'; +export { ConeBufferGeometry } from './extras/geometries/ConeBufferGeometry.js'; +export { CylinderGeometry } from './extras/geometries/CylinderGeometry.js'; +export { CylinderBufferGeometry } from './extras/geometries/CylinderBufferGeometry.js'; +export { CircleBufferGeometry } from './extras/geometries/CircleBufferGeometry.js'; +export { CircleGeometry } from './extras/geometries/CircleGeometry.js'; +export { BoxBufferGeometry } from './extras/geometries/BoxBufferGeometry.js'; +export { CubeGeometry, BoxGeometry } from './extras/geometries/BoxGeometry.js'; +export { ClosedSplineCurve3 } from './extras/curves/ClosedSplineCurve3.js'; +export { CatmullRomCurve3 } from './extras/curves/CatmullRomCurve3.js'; +export { SplineCurve3 } from './extras/curves/SplineCurve3.js'; +export { CubicBezierCurve3 } from './extras/curves/CubicBezierCurve3.js'; +export { QuadraticBezierCurve3 } from './extras/curves/QuadraticBezierCurve3.js'; +export { LineCurve3 } from './extras/curves/LineCurve3.js'; +export { ArcCurve } from './extras/curves/ArcCurve.js'; +export { EllipseCurve } from './extras/curves/EllipseCurve.js'; +export { SplineCurve } from './extras/curves/SplineCurve.js'; +export { CubicBezierCurve } from './extras/curves/CubicBezierCurve.js'; +export { QuadraticBezierCurve } from './extras/curves/QuadraticBezierCurve.js'; +export { LineCurve } from './extras/curves/LineCurve.js'; +export { Shape } from './extras/core/Shape.js'; +export { ShapePath, Path } from './extras/core/Path.js'; +export { Font } from './extras/core/Font.js'; +export { CurvePath } from './extras/core/CurvePath.js'; +export { Curve } from './extras/core/Curve.js'; +export { ShapeUtils } from './extras/ShapeUtils.js'; +export { SceneUtils } from './extras/SceneUtils.js'; +export { CurveUtils } from './extras/CurveUtils.js'; +export * from './constants.js'; \ No newline at end of file diff --git a/src/animation/AnimationAction.js b/src/animation/AnimationAction.js index 7763c611de9daf..ad8308c85836e8 100644 --- a/src/animation/AnimationAction.js +++ b/src/animation/AnimationAction.js @@ -1,3 +1,5 @@ +import { WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, LoopPingPong, LoopOnce, LoopRepeat } from '../constants'; + /** * * Action provided by AnimationMixer for scheduling clip playback on specific @@ -9,14 +11,15 @@ * */ -THREE.AnimationAction = function() { +function AnimationAction() { + this.isAnimationAction = true; throw new Error( "THREE.AnimationAction: " + "Use mixer.clipAction for construction." ); }; -THREE.AnimationAction._new = +AnimationAction._new = function AnimationAction( mixer, clip, localRoot ) { this._mixer = mixer; @@ -28,8 +31,8 @@ THREE.AnimationAction._new = interpolants = new Array( nTracks ); var interpolantSettings = { - endingStart: THREE.ZeroCurvatureEnding, - endingEnd: THREE.ZeroCurvatureEnding + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding }; for ( var i = 0; i !== nTracks; ++ i ) { @@ -53,7 +56,7 @@ THREE.AnimationAction._new = this._timeScaleInterpolant = null; this._weightInterpolant = null; - this.loop = THREE.LoopRepeat; + this.loop = LoopRepeat; this._loopCount = -1; // global mixer time when the action is to be started @@ -82,9 +85,9 @@ THREE.AnimationAction._new = }; -THREE.AnimationAction._new.prototype = { +AnimationAction._new.prototype = { - constructor: THREE.AnimationAction._new, + constructor: AnimationAction._new, // State & Scheduling @@ -478,7 +481,7 @@ THREE.AnimationAction._new.prototype = { loop = this.loop, loopCount = this._loopCount; - if ( loop === THREE.LoopOnce ) { + if ( loop === LoopOnce ) { if ( loopCount === -1 ) { // just started @@ -512,7 +515,7 @@ THREE.AnimationAction._new.prototype = { } else { // repetitive Repeat or PingPong - var pingPong = ( loop === THREE.LoopPingPong ); + var pingPong = ( loop === LoopPingPong ); if ( loopCount === -1 ) { // just started @@ -606,8 +609,8 @@ THREE.AnimationAction._new.prototype = { if ( pingPong ) { - settings.endingStart = THREE.ZeroSlopeEnding; - settings.endingEnd = THREE.ZeroSlopeEnding; + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; } else { @@ -616,22 +619,22 @@ THREE.AnimationAction._new.prototype = { if ( atStart ) { settings.endingStart = this.zeroSlopeAtStart ? - THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding; + ZeroSlopeEnding : ZeroCurvatureEnding; } else { - settings.endingStart = THREE.WrapAroundEnding; + settings.endingStart = WrapAroundEnding; } if ( atEnd ) { settings.endingEnd = this.zeroSlopeAtEnd ? - THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding; + ZeroSlopeEnding : ZeroCurvatureEnding; } else { - settings.endingEnd = THREE.WrapAroundEnding; + settings.endingEnd = WrapAroundEnding; } @@ -663,3 +666,6 @@ THREE.AnimationAction._new.prototype = { }; + + +export { AnimationAction }; \ No newline at end of file diff --git a/src/animation/AnimationClip.js b/src/animation/AnimationClip.js index a5e64a8fe13b6b..efb6c48c6b62c5 100644 --- a/src/animation/AnimationClip.js +++ b/src/animation/AnimationClip.js @@ -1,3 +1,10 @@ +import { VectorKeyframeTrack } from './tracks/VectorKeyframeTrack'; +import { QuaternionKeyframeTrack } from './tracks/QuaternionKeyframeTrack'; +import { NumberKeyframeTrack } from './tracks/NumberKeyframeTrack'; +import { AnimationUtils } from './AnimationUtils'; +import { KeyframeTrack } from './KeyframeTrack'; +import { _Math } from '../math/Math'; + /** * * Reusable set of Tracks that represent an animation. @@ -6,13 +13,14 @@ * @author David Sarno / http://lighthaus.us/ */ -THREE.AnimationClip = function ( name, duration, tracks ) { +function AnimationClip ( name, duration, tracks ) { + this.isAnimationClip = true; this.name = name; this.tracks = tracks; this.duration = ( duration !== undefined ) ? duration : -1; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracks if ( this.duration < 0 ) { @@ -28,9 +36,9 @@ THREE.AnimationClip = function ( name, duration, tracks ) { }; -THREE.AnimationClip.prototype = { +AnimationClip.prototype = { - constructor: THREE.AnimationClip, + constructor: AnimationClip, resetDuration: function() { @@ -78,7 +86,7 @@ THREE.AnimationClip.prototype = { // Static methods: -Object.assign( THREE.AnimationClip, { +Object.assign( AnimationClip, { parse: function( json ) { @@ -88,11 +96,11 @@ Object.assign( THREE.AnimationClip, { for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { - tracks.push( THREE.KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); + tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); } - return new THREE.AnimationClip( json.name, json.duration, tracks ); + return new AnimationClip( json.name, json.duration, tracks ); }, @@ -112,7 +120,7 @@ Object.assign( THREE.AnimationClip, { for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { - tracks.push( THREE.KeyframeTrack.toJSON( clipTracks[ i ] ) ); + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); } @@ -138,9 +146,9 @@ Object.assign( THREE.AnimationClip, { values.push( 0, 1, 0 ); - var order = THREE.AnimationUtils.getKeyframeOrder( times ); - times = THREE.AnimationUtils.sortedArray( times, 1, order ); - values = THREE.AnimationUtils.sortedArray( values, 1, order ); + var order = AnimationUtils.getKeyframeOrder( times ); + times = AnimationUtils.sortedArray( times, 1, order ); + values = AnimationUtils.sortedArray( values, 1, order ); // if there is a key at the first frame, duplicate it as the // last frame as well for perfect loop. @@ -152,13 +160,13 @@ Object.assign( THREE.AnimationClip, { } tracks.push( - new THREE.NumberKeyframeTrack( + new NumberKeyframeTrack( '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', times, values ).scale( 1.0 / fps ) ); } - return new THREE.AnimationClip( name, -1, tracks ); + return new AnimationClip( name, -1, tracks ); }, @@ -222,7 +230,7 @@ Object.assign( THREE.AnimationClip, { for ( var name in animationToMorphTargets ) { - clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); } @@ -249,7 +257,7 @@ Object.assign( THREE.AnimationClip, { var times = []; var values = []; - THREE.AnimationUtils.flattenJSON( + AnimationUtils.flattenJSON( animationKeys, times, values, propertyName ); // empty keys are filtered out, so check again @@ -316,7 +324,7 @@ Object.assign( THREE.AnimationClip, { } - tracks.push( new THREE.NumberKeyframeTrack( + tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); } @@ -329,15 +337,15 @@ Object.assign( THREE.AnimationClip, { var boneName = '.bones[' + bones[ h ].name + ']'; addNonemptyTrack( - THREE.VectorKeyframeTrack, boneName + '.position', + VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks ); addNonemptyTrack( - THREE.QuaternionKeyframeTrack, boneName + '.quaternion', + QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks ); addNonemptyTrack( - THREE.VectorKeyframeTrack, boneName + '.scale', + VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks ); } @@ -350,10 +358,13 @@ Object.assign( THREE.AnimationClip, { } - var clip = new THREE.AnimationClip( clipName, duration, tracks ); + var clip = new AnimationClip( clipName, duration, tracks ); return clip; } } ); + + +export { AnimationClip }; \ No newline at end of file diff --git a/src/animation/AnimationMixer.js b/src/animation/AnimationMixer.js index 8483c40faf2fec..d0cfd3bada73f8 100644 --- a/src/animation/AnimationMixer.js +++ b/src/animation/AnimationMixer.js @@ -1,3 +1,10 @@ +import { AnimationAction } from './AnimationAction'; +import { EventDispatcher } from '../core/EventDispatcher'; +import { LinearInterpolant } from '../math/interpolants/LinearInterpolant'; +import { PropertyBinding } from './PropertyBinding'; +import { PropertyMixer } from './PropertyMixer'; +import { AnimationClip } from './AnimationClip'; + /** * * Player for AnimationClips. @@ -8,7 +15,8 @@ * @author tschw */ -THREE.AnimationMixer = function( root ) { +function AnimationMixer( root ) { + this.isAnimationMixer = true; this._root = root; this._initMemoryManager(); @@ -20,7 +28,7 @@ THREE.AnimationMixer = function( root ) { }; -Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, { +Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, { // return an action for a clip optionally using a custom root target // object (this method allocates a lot of dynamic memory in case a @@ -31,7 +39,7 @@ Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, rootUuid = root.uuid, clipObject = typeof clip === 'string' ? - THREE.AnimationClip.findByName( root, clip ) : clip, + AnimationClip.findByName( root, clip ) : clip, clipUuid = clipObject !== null ? clipObject.uuid : clip, @@ -63,8 +71,7 @@ Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, if ( clipObject === null ) return null; // allocate all resources required to run it - var newAction = new THREE. - AnimationMixer._Action( this, clipObject, optionalRoot ); + var newAction = new AnimationMixer._Action( this, clipObject, optionalRoot ); this._bindAction( newAction, prototypeAction ); @@ -82,7 +89,7 @@ Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, rootUuid = root.uuid, clipObject = typeof clip === 'string' ? - THREE.AnimationClip.findByName( root, clip ) : clip, + AnimationClip.findByName( root, clip ) : clip, clipUuid = clipObject ? clipObject.uuid : clip, @@ -269,11 +276,11 @@ Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, } ); -THREE.AnimationMixer._Action = THREE.AnimationAction._new; +AnimationMixer._Action = AnimationAction._new; // Implementation details: -Object.assign( THREE.AnimationMixer.prototype, { +Object.assign( AnimationMixer.prototype, { _bindAction: function( action, prototypeAction ) { @@ -325,8 +332,8 @@ Object.assign( THREE.AnimationMixer.prototype, { var path = prototypeAction && prototypeAction. _propertyBindings[ i ].binding.parsedPath; - binding = new THREE.PropertyMixer( - THREE.PropertyBinding.create( root, trackName, path ), + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), track.ValueTypeName, track.getValueSize() ); ++ binding.referenceCount; @@ -703,7 +710,7 @@ Object.assign( THREE.AnimationMixer.prototype, { if ( interpolant === undefined ) { - interpolant = new THREE.LinearInterpolant( + interpolant = new LinearInterpolant( new Float32Array( 2 ), new Float32Array( 2 ), 1, this._controlInterpolantsResultBuffer ); @@ -736,3 +743,6 @@ Object.assign( THREE.AnimationMixer.prototype, { _controlInterpolantsResultBuffer: new Float32Array( 1 ) } ); + + +export { AnimationMixer }; \ No newline at end of file diff --git a/src/animation/AnimationObjectGroup.js b/src/animation/AnimationObjectGroup.js index 815aee2b4e62c6..c5df23305c3aee 100644 --- a/src/animation/AnimationObjectGroup.js +++ b/src/animation/AnimationObjectGroup.js @@ -1,3 +1,6 @@ +import { PropertyBinding } from './PropertyBinding'; +import { _Math } from '../math/Math'; + /** * * A group of objects that receives a shared animation state. @@ -29,9 +32,10 @@ * @author tschw */ -THREE.AnimationObjectGroup = function( var_args ) { +function AnimationObjectGroup( var_args ) { + this.isAnimationObjectGroup = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); // cached objects followed by the active ones this._objects = Array.prototype.slice.call( arguments ); @@ -68,9 +72,9 @@ THREE.AnimationObjectGroup = function( var_args ) { }; -THREE.AnimationObjectGroup.prototype = { +AnimationObjectGroup.prototype = { - constructor: THREE.AnimationObjectGroup, + constructor: AnimationObjectGroup, add: function( var_args ) { @@ -102,7 +106,7 @@ THREE.AnimationObjectGroup.prototype = { for ( var j = 0, m = nBindings; j !== m; ++ j ) { bindings[ j ].push( - new THREE.PropertyBinding( + new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); } @@ -138,7 +142,7 @@ THREE.AnimationObjectGroup.prototype = { // for objects that are cached, the binding may // or may not exist - binding = new THREE.PropertyBinding( + binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); } @@ -327,7 +331,7 @@ THREE.AnimationObjectGroup.prototype = { var object = objects[ i ]; bindingsForPath[ i ] = - new THREE.PropertyBinding( object, path, parsedPath ); + new PropertyBinding( object, path, parsedPath ); } @@ -368,3 +372,6 @@ THREE.AnimationObjectGroup.prototype = { }; + + +export { AnimationObjectGroup }; \ No newline at end of file diff --git a/src/animation/AnimationUtils.js b/src/animation/AnimationUtils.js index ff7bce3fa12f67..b85bb836d9c27f 100644 --- a/src/animation/AnimationUtils.js +++ b/src/animation/AnimationUtils.js @@ -1,15 +1,17 @@ +var AnimationUtils; + /** * @author tschw * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ */ -THREE.AnimationUtils = { +AnimationUtils = { // same as Array.prototype.slice, but also works on typed arrays arraySlice: function( array, from, to ) { - if ( THREE.AnimationUtils.isTypedArray( array ) ) { + if ( AnimationUtils.isTypedArray( array ) ) { return new array.constructor( array.subarray( from, to ) ); @@ -157,3 +159,6 @@ THREE.AnimationUtils = { } }; + + +export { AnimationUtils }; \ No newline at end of file diff --git a/src/animation/KeyframeTrack.js b/src/animation/KeyframeTrack.js index 30f73e21ff51bd..ce8a03d5e7ee60 100644 --- a/src/animation/KeyframeTrack.js +++ b/src/animation/KeyframeTrack.js @@ -1,3 +1,13 @@ +import { KeyframeTrackPrototype } from './KeyframeTrackPrototype'; +import { StringKeyframeTrack } from './tracks/StringKeyframeTrack'; +import { BooleanKeyframeTrack } from './tracks/BooleanKeyframeTrack'; +import { QuaternionKeyframeTrack } from './tracks/QuaternionKeyframeTrack'; +import { ColorKeyframeTrack } from './tracks/ColorKeyframeTrack'; +import { VectorKeyframeTrack } from './tracks/VectorKeyframeTrack'; +import { NumberKeyframeTrack } from './tracks/NumberKeyframeTrack'; +import { AnimationUtils } from './AnimationUtils'; +import { KeyframeTrackConstructor } from './KeyframeTrackConstructor'; + /** * * A timed sequence of keyframes for a specific property. @@ -8,368 +18,16 @@ * @author tschw */ -THREE.KeyframeTrack = function ( name, times, values, interpolation ) { - - if( name === undefined ) throw new Error( "track name is undefined" ); - - if( times === undefined || times.length === 0 ) { - - throw new Error( "no keyframes in track named " + name ); - - } - - this.name = name; - - this.times = THREE.AnimationUtils.convertArray( times, this.TimeBufferType ); - this.values = THREE.AnimationUtils.convertArray( values, this.ValueBufferType ); - - this.setInterpolation( interpolation || this.DefaultInterpolation ); - - this.validate(); - this.optimize(); - +function KeyframeTrack ( name, times, values, interpolation ) { + KeyframeTrackConstructor.apply( this, arguments ); }; -THREE.KeyframeTrack.prototype = { - - constructor: THREE.KeyframeTrack, - - TimeBufferType: Float32Array, - ValueBufferType: Float32Array, - - DefaultInterpolation: THREE.InterpolateLinear, - - InterpolantFactoryMethodDiscrete: function( result ) { - - return new THREE.DiscreteInterpolant( - this.times, this.values, this.getValueSize(), result ); - - }, - - InterpolantFactoryMethodLinear: function( result ) { - - return new THREE.LinearInterpolant( - this.times, this.values, this.getValueSize(), result ); - - }, - - InterpolantFactoryMethodSmooth: function( result ) { - - return new THREE.CubicInterpolant( - this.times, this.values, this.getValueSize(), result ); - - }, - - setInterpolation: function( interpolation ) { - - var factoryMethod; - - switch ( interpolation ) { - - case THREE.InterpolateDiscrete: - - factoryMethod = this.InterpolantFactoryMethodDiscrete; - - break; - - case THREE.InterpolateLinear: - - factoryMethod = this.InterpolantFactoryMethodLinear; - - break; - - case THREE.InterpolateSmooth: - - factoryMethod = this.InterpolantFactoryMethodSmooth; - - break; - - } - - if ( factoryMethod === undefined ) { - - var message = "unsupported interpolation for " + - this.ValueTypeName + " keyframe track named " + this.name; - - if ( this.createInterpolant === undefined ) { - - // fall back to default, unless the default itself is messed up - if ( interpolation !== this.DefaultInterpolation ) { - - this.setInterpolation( this.DefaultInterpolation ); - - } else { - - throw new Error( message ); // fatal, in this case - - } - - } - - console.warn( message ); - return; - - } - - this.createInterpolant = factoryMethod; - - }, - - getInterpolation: function() { - - switch ( this.createInterpolant ) { - - case this.InterpolantFactoryMethodDiscrete: - - return THREE.InterpolateDiscrete; - - case this.InterpolantFactoryMethodLinear: - - return THREE.InterpolateLinear; - - case this.InterpolantFactoryMethodSmooth: - - return THREE.InterpolateSmooth; - - } - - }, - - getValueSize: function() { - - return this.values.length / this.times.length; - - }, - - // move all keyframes either forwards or backwards in time - shift: function( timeOffset ) { - - if( timeOffset !== 0.0 ) { - - var times = this.times; - - for( var i = 0, n = times.length; i !== n; ++ i ) { - - times[ i ] += timeOffset; - - } - - } - - return this; - - }, - - // scale all keyframe times by a factor (useful for frame <-> seconds conversions) - scale: function( timeScale ) { - - if( timeScale !== 1.0 ) { - - var times = this.times; - - for( var i = 0, n = times.length; i !== n; ++ i ) { - - times[ i ] *= timeScale; - - } - - } - - return this; - - }, - - // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. - // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values - trim: function( startTime, endTime ) { - - var times = this.times, - nKeys = times.length, - from = 0, - to = nKeys - 1; - - while ( from !== nKeys && times[ from ] < startTime ) ++ from; - while ( to !== -1 && times[ to ] > endTime ) -- to; - - ++ to; // inclusive -> exclusive bound - - if( from !== 0 || to !== nKeys ) { - - // empty tracks are forbidden, so keep at least one keyframe - if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; - - var stride = this.getValueSize(); - this.times = THREE.AnimationUtils.arraySlice( times, from, to ); - this.values = THREE.AnimationUtils. - arraySlice( this.values, from * stride, to * stride ); - - } - - return this; - - }, - - // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable - validate: function() { - - var valid = true; - - var valueSize = this.getValueSize(); - if ( valueSize - Math.floor( valueSize ) !== 0 ) { - - console.error( "invalid value size in track", this ); - valid = false; - - } - - var times = this.times, - values = this.values, - - nKeys = times.length; - - if( nKeys === 0 ) { - - console.error( "track is empty", this ); - valid = false; - - } - - var prevTime = null; - - for( var i = 0; i !== nKeys; i ++ ) { - - var currTime = times[ i ]; - - if ( typeof currTime === 'number' && isNaN( currTime ) ) { - - console.error( "time is not a valid number", this, i, currTime ); - valid = false; - break; - - } - - if( prevTime !== null && prevTime > currTime ) { - - console.error( "out of order keys", this, i, currTime, prevTime ); - valid = false; - break; - - } - - prevTime = currTime; - - } - - if ( values !== undefined ) { - - if ( THREE.AnimationUtils.isTypedArray( values ) ) { - - for ( var i = 0, n = values.length; i !== n; ++ i ) { - - var value = values[ i ]; - - if ( isNaN( value ) ) { - - console.error( "value is not a valid number", this, i, value ); - valid = false; - break; - - } - - } - - } - - } - - return valid; - - }, - - // removes equivalent sequential keys as common in morph target sequences - // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) - optimize: function() { - - var times = this.times, - values = this.values, - stride = this.getValueSize(), - - writeIndex = 1; - - for( var i = 1, n = times.length - 1; i <= n; ++ i ) { - - var keep = false; - - var time = times[ i ]; - var timeNext = times[ i + 1 ]; - - // remove adjacent keyframes scheduled at the same time - - if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { - - // remove unnecessary keyframes same as their neighbors - var offset = i * stride, - offsetP = offset - stride, - offsetN = offset + stride; - - for ( var j = 0; j !== stride; ++ j ) { - - var value = values[ offset + j ]; - - if ( value !== values[ offsetP + j ] || - value !== values[ offsetN + j ] ) { - - keep = true; - break; - - } - - } - - } - - // in-place compaction - - if ( keep ) { - - if ( i !== writeIndex ) { - - times[ writeIndex ] = times[ i ]; - - var readOffset = i * stride, - writeOffset = writeIndex * stride; - - for ( var j = 0; j !== stride; ++ j ) { - - values[ writeOffset + j ] = values[ readOffset + j ]; - - } - - - } - - ++ writeIndex; - - } - - } - - if ( writeIndex !== times.length ) { - - this.times = THREE.AnimationUtils.arraySlice( times, 0, writeIndex ); - this.values = THREE.AnimationUtils.arraySlice( values, 0, writeIndex * stride ); - - } - - return this; - - } - -}; +KeyframeTrack.prototype = KeyframeTrackPrototype; +KeyframeTrackPrototype.constructor = KeyframeTrack; // Static methods: -Object.assign( THREE.KeyframeTrack, { +Object.assign( KeyframeTrack, { // Serialization (in static context, because of constructor invocation // and automatic invocation of .toJSON): @@ -382,13 +40,13 @@ Object.assign( THREE.KeyframeTrack, { } - var trackType = THREE.KeyframeTrack._getTrackTypeForValueTypeName( json.type ); + var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type ); if ( json.times === undefined ) { var times = [], values = []; - THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); + AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); json.times = times; json.values = values; @@ -427,8 +85,8 @@ Object.assign( THREE.KeyframeTrack, { json = { 'name': track.name, - 'times': THREE.AnimationUtils.convertArray( track.times, Array ), - 'values': THREE.AnimationUtils.convertArray( track.values, Array ) + 'times': AnimationUtils.convertArray( track.times, Array ), + 'values': AnimationUtils.convertArray( track.values, Array ) }; @@ -458,31 +116,31 @@ Object.assign( THREE.KeyframeTrack, { case "number": case "integer": - return THREE.NumberKeyframeTrack; + return NumberKeyframeTrack; case "vector": case "vector2": case "vector3": case "vector4": - return THREE.VectorKeyframeTrack; + return VectorKeyframeTrack; case "color": - return THREE.ColorKeyframeTrack; + return ColorKeyframeTrack; case "quaternion": - return THREE.QuaternionKeyframeTrack; + return QuaternionKeyframeTrack; case "bool": case "boolean": - return THREE.BooleanKeyframeTrack; + return BooleanKeyframeTrack; case "string": - return THREE.StringKeyframeTrack; + return StringKeyframeTrack; } @@ -491,3 +149,6 @@ Object.assign( THREE.KeyframeTrack, { } } ); + + +export { KeyframeTrack }; \ No newline at end of file diff --git a/src/animation/KeyframeTrackConstructor.js b/src/animation/KeyframeTrackConstructor.js new file mode 100644 index 00000000000000..015cff61c007a6 --- /dev/null +++ b/src/animation/KeyframeTrackConstructor.js @@ -0,0 +1,26 @@ +import { AnimationUtils } from './AnimationUtils'; + +function KeyframeTrackConstructor ( name, times, values, interpolation ) { + this.isKeyframeTrack = true; + + if( name === undefined ) throw new Error( "track name is undefined" ); + + if( times === undefined || times.length === 0 ) { + + throw new Error( "no keyframes in track named " + name ); + + } + + this.name = name; + + this.times = AnimationUtils.convertArray( times, this.TimeBufferType ); + this.values = AnimationUtils.convertArray( values, this.ValueBufferType ); + + this.setInterpolation( interpolation || this.DefaultInterpolation ); + + this.validate(); + this.optimize(); + +} + +export { KeyframeTrackConstructor }; \ No newline at end of file diff --git a/src/animation/KeyframeTrackPrototype.js b/src/animation/KeyframeTrackPrototype.js new file mode 100644 index 00000000000000..aebc7da9b17820 --- /dev/null +++ b/src/animation/KeyframeTrackPrototype.js @@ -0,0 +1,345 @@ +import { InterpolateLinear } from '../constants'; +import { AnimationUtils } from './AnimationUtils'; +import { InterpolateSmooth, InterpolateDiscrete } from '../constants'; +import { CubicInterpolant } from '../math/interpolants/CubicInterpolant'; +import { LinearInterpolant } from '../math/interpolants/LinearInterpolant'; +import { DiscreteInterpolant } from '../math/interpolants/DiscreteInterpolant'; + +var KeyframeTrackPrototype; + +KeyframeTrackPrototype = { + + TimeBufferType: Float32Array, + ValueBufferType: Float32Array, + + DefaultInterpolation: InterpolateLinear, + + InterpolantFactoryMethodDiscrete: function( result ) { + + return new DiscreteInterpolant( + this.times, this.values, this.getValueSize(), result ); + + }, + + InterpolantFactoryMethodLinear: function( result ) { + + return new LinearInterpolant( + this.times, this.values, this.getValueSize(), result ); + + }, + + InterpolantFactoryMethodSmooth: function( result ) { + + return new CubicInterpolant( + this.times, this.values, this.getValueSize(), result ); + + }, + + setInterpolation: function( interpolation ) { + + var factoryMethod; + + switch ( interpolation ) { + + case InterpolateDiscrete: + + factoryMethod = this.InterpolantFactoryMethodDiscrete; + + break; + + case InterpolateLinear: + + factoryMethod = this.InterpolantFactoryMethodLinear; + + break; + + case InterpolateSmooth: + + factoryMethod = this.InterpolantFactoryMethodSmooth; + + break; + + } + + if ( factoryMethod === undefined ) { + + var message = "unsupported interpolation for " + + this.ValueTypeName + " keyframe track named " + this.name; + + if ( this.createInterpolant === undefined ) { + + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { + + this.setInterpolation( this.DefaultInterpolation ); + + } else { + + throw new Error( message ); // fatal, in this case + + } + + } + + console.warn( message ); + return; + + } + + this.createInterpolant = factoryMethod; + + }, + + getInterpolation: function() { + + switch ( this.createInterpolant ) { + + case this.InterpolantFactoryMethodDiscrete: + + return InterpolateDiscrete; + + case this.InterpolantFactoryMethodLinear: + + return InterpolateLinear; + + case this.InterpolantFactoryMethodSmooth: + + return InterpolateSmooth; + + } + + }, + + getValueSize: function() { + + return this.values.length / this.times.length; + + }, + + // move all keyframes either forwards or backwards in time + shift: function( timeOffset ) { + + if( timeOffset !== 0.0 ) { + + var times = this.times; + + for( var i = 0, n = times.length; i !== n; ++ i ) { + + times[ i ] += timeOffset; + + } + + } + + return this; + + }, + + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale: function( timeScale ) { + + if( timeScale !== 1.0 ) { + + var times = this.times; + + for( var i = 0, n = times.length; i !== n; ++ i ) { + + times[ i ] *= timeScale; + + } + + } + + return this; + + }, + + // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. + // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values + trim: function( startTime, endTime ) { + + var times = this.times, + nKeys = times.length, + from = 0, + to = nKeys - 1; + + while ( from !== nKeys && times[ from ] < startTime ) ++ from; + while ( to !== -1 && times[ to ] > endTime ) -- to; + + ++ to; // inclusive -> exclusive bound + + if( from !== 0 || to !== nKeys ) { + + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; + + var stride = this.getValueSize(); + this.times = AnimationUtils.arraySlice( times, from, to ); + this.values = AnimationUtils. + arraySlice( this.values, from * stride, to * stride ); + + } + + return this; + + }, + + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate: function() { + + var valid = true; + + var valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { + + console.error( "invalid value size in track", this ); + valid = false; + + } + + var times = this.times, + values = this.values, + + nKeys = times.length; + + if( nKeys === 0 ) { + + console.error( "track is empty", this ); + valid = false; + + } + + var prevTime = null; + + for( var i = 0; i !== nKeys; i ++ ) { + + var currTime = times[ i ]; + + if ( typeof currTime === 'number' && isNaN( currTime ) ) { + + console.error( "time is not a valid number", this, i, currTime ); + valid = false; + break; + + } + + if( prevTime !== null && prevTime > currTime ) { + + console.error( "out of order keys", this, i, currTime, prevTime ); + valid = false; + break; + + } + + prevTime = currTime; + + } + + if ( values !== undefined ) { + + if ( AnimationUtils.isTypedArray( values ) ) { + + for ( var i = 0, n = values.length; i !== n; ++ i ) { + + var value = values[ i ]; + + if ( isNaN( value ) ) { + + console.error( "value is not a valid number", this, i, value ); + valid = false; + break; + + } + + } + + } + + } + + return valid; + + }, + + // removes equivalent sequential keys as common in morph target sequences + // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) + optimize: function() { + + var times = this.times, + values = this.values, + stride = this.getValueSize(), + + writeIndex = 1; + + for( var i = 1, n = times.length - 1; i <= n; ++ i ) { + + var keep = false; + + var time = times[ i ]; + var timeNext = times[ i + 1 ]; + + // remove adjacent keyframes scheduled at the same time + + if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { + + // remove unnecessary keyframes same as their neighbors + var offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; + + for ( var j = 0; j !== stride; ++ j ) { + + var value = values[ offset + j ]; + + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { + + keep = true; + break; + + } + + } + + } + + // in-place compaction + + if ( keep ) { + + if ( i !== writeIndex ) { + + times[ writeIndex ] = times[ i ]; + + var readOffset = i * stride, + writeOffset = writeIndex * stride; + + for ( var j = 0; j !== stride; ++ j ) { + + values[ writeOffset + j ] = values[ readOffset + j ]; + + } + + + } + + ++ writeIndex; + + } + + } + + if ( writeIndex !== times.length ) { + + this.times = AnimationUtils.arraySlice( times, 0, writeIndex ); + this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride ); + + } + + return this; + + } + +} + +export { KeyframeTrackPrototype }; \ No newline at end of file diff --git a/src/animation/PropertyBinding.js b/src/animation/PropertyBinding.js index 0d9416de90a456..6e3fef2026fab1 100644 --- a/src/animation/PropertyBinding.js +++ b/src/animation/PropertyBinding.js @@ -8,22 +8,23 @@ * @author tschw */ -THREE.PropertyBinding = function ( rootNode, path, parsedPath ) { +function PropertyBinding ( rootNode, path, parsedPath ) { + this.isPropertyBinding = true; this.path = path; this.parsedPath = parsedPath || - THREE.PropertyBinding.parseTrackName( path ); + PropertyBinding.parseTrackName( path ); - this.node = THREE.PropertyBinding.findNode( + this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; this.rootNode = rootNode; }; -THREE.PropertyBinding.prototype = { +PropertyBinding.prototype = { - constructor: THREE.PropertyBinding, + constructor: PropertyBinding, getValue: function getValue_unbound( targetArray, offset ) { @@ -57,7 +58,7 @@ THREE.PropertyBinding.prototype = { if ( ! targetObject ) { - targetObject = THREE.PropertyBinding.findNode( + targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; this.node = targetObject; @@ -268,15 +269,15 @@ THREE.PropertyBinding.prototype = { }; -Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued +Object.assign( PropertyBinding.prototype, { // prototype, continued // these are used to "bind" a nonexistent property _getValue_unavailable: function() {}, _setValue_unavailable: function() {}, // initial state of these methods that calls 'bind' - _getValue_unbound: THREE.PropertyBinding.prototype.getValue, - _setValue_unbound: THREE.PropertyBinding.prototype.setValue, + _getValue_unbound: PropertyBinding.prototype.getValue, + _setValue_unbound: PropertyBinding.prototype.setValue, BindingType: { Direct: 0, @@ -448,20 +449,20 @@ Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued } ); -THREE.PropertyBinding.Composite = +PropertyBinding.Composite = function( targetGroup, path, optionalParsedPath ) { var parsedPath = optionalParsedPath || - THREE.PropertyBinding.parseTrackName( path ); + PropertyBinding.parseTrackName( path ); this._targetGroup = targetGroup; this._bindings = targetGroup.subscribe_( path, parsedPath ); }; -THREE.PropertyBinding.Composite.prototype = { +PropertyBinding.Composite.prototype = { - constructor: THREE.PropertyBinding.Composite, + constructor: PropertyBinding.Composite, getValue: function( array, offset ) { @@ -516,21 +517,21 @@ THREE.PropertyBinding.Composite.prototype = { }; -THREE.PropertyBinding.create = function( root, path, parsedPath ) { +PropertyBinding.create = function( root, path, parsedPath ) { - if ( ! ( root instanceof THREE.AnimationObjectGroup ) ) { + if ( ! ( (root && root.isAnimationObjectGroup) ) ) { - return new THREE.PropertyBinding( root, path, parsedPath ); + return new PropertyBinding( root, path, parsedPath ); } else { - return new THREE.PropertyBinding.Composite( root, path, parsedPath ); + return new PropertyBinding.Composite( root, path, parsedPath ); } }; -THREE.PropertyBinding.parseTrackName = function( trackName ) { +PropertyBinding.parseTrackName = function( trackName ) { // matches strings in the form of: // nodeName.property @@ -577,7 +578,7 @@ THREE.PropertyBinding.parseTrackName = function( trackName ) { }; -THREE.PropertyBinding.findNode = function( root, nodeName ) { +PropertyBinding.findNode = function( root, nodeName ) { if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { @@ -652,3 +653,6 @@ THREE.PropertyBinding.findNode = function( root, nodeName ) { return null; }; + + +export { PropertyBinding }; \ No newline at end of file diff --git a/src/animation/PropertyMixer.js b/src/animation/PropertyMixer.js index ebd3132bbd5863..ee03f7e99143fc 100644 --- a/src/animation/PropertyMixer.js +++ b/src/animation/PropertyMixer.js @@ -1,3 +1,5 @@ +import { Quaternion } from '../math/Quaternion'; + /** * * Buffered scene graph property that allows weighted accumulation. @@ -8,7 +10,8 @@ * @author tschw */ -THREE.PropertyMixer = function ( binding, typeName, valueSize ) { +function PropertyMixer ( binding, typeName, valueSize ) { + this.isPropertyMixer = true; this.binding = binding; this.valueSize = valueSize; @@ -50,9 +53,9 @@ THREE.PropertyMixer = function ( binding, typeName, valueSize ) { }; -THREE.PropertyMixer.prototype = { +PropertyMixer.prototype = { - constructor: THREE.PropertyMixer, + constructor: PropertyMixer, // accumulate data in the 'incoming' region into 'accu' accumulate: function( accuIndex, weight ) { @@ -181,7 +184,7 @@ THREE.PropertyMixer.prototype = { _slerp: function( buffer, dstOffset, srcOffset, t, stride ) { - THREE.Quaternion.slerpFlat( buffer, dstOffset, + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); }, @@ -201,3 +204,6 @@ THREE.PropertyMixer.prototype = { } }; + + +export { PropertyMixer }; \ No newline at end of file diff --git a/src/animation/tracks/BooleanKeyframeTrack.js b/src/animation/tracks/BooleanKeyframeTrack.js index 10633c1a456c9d..e314cec6623069 100644 --- a/src/animation/tracks/BooleanKeyframeTrack.js +++ b/src/animation/tracks/BooleanKeyframeTrack.js @@ -1,3 +1,7 @@ +import { InterpolateDiscrete } from '../../constants'; +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track of Boolean keyframe values. @@ -8,21 +12,22 @@ * @author tschw */ -THREE.BooleanKeyframeTrack = function ( name, times, values ) { +function BooleanKeyframeTrack ( name, times, values ) { + this.isBooleanKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values ); + KeyframeTrackConstructor.call( this, name, times, values ); }; -THREE.BooleanKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +BooleanKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.BooleanKeyframeTrack, + constructor: BooleanKeyframeTrack, ValueTypeName: 'bool', ValueBufferType: Array, - DefaultInterpolation: THREE.InterpolateDiscrete, + DefaultInterpolation: InterpolateDiscrete, InterpolantFactoryMethodLinear: undefined, InterpolantFactoryMethodSmooth: undefined @@ -32,3 +37,6 @@ THREE.BooleanKeyframeTrack.prototype = // computes "firstValue ^ isOdd( index )". } ); + + +export { BooleanKeyframeTrack }; \ No newline at end of file diff --git a/src/animation/tracks/ColorKeyframeTrack.js b/src/animation/tracks/ColorKeyframeTrack.js index 9b4a156de9a57c..3f508c323f2ca6 100644 --- a/src/animation/tracks/ColorKeyframeTrack.js +++ b/src/animation/tracks/ColorKeyframeTrack.js @@ -1,3 +1,6 @@ +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track of keyframe values that represent color. @@ -8,16 +11,17 @@ * @author tschw */ -THREE.ColorKeyframeTrack = function ( name, times, values, interpolation ) { +function ColorKeyframeTrack ( name, times, values, interpolation ) { + this.isColorKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); }; -THREE.ColorKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +ColorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.ColorKeyframeTrack, + constructor: ColorKeyframeTrack, ValueTypeName: 'color' @@ -30,3 +34,6 @@ THREE.ColorKeyframeTrack.prototype = // However, this is the place for color space parameterization. } ); + + +export { ColorKeyframeTrack }; \ No newline at end of file diff --git a/src/animation/tracks/NumberKeyframeTrack.js b/src/animation/tracks/NumberKeyframeTrack.js index 01585638438cbe..cdf584c03c42aa 100644 --- a/src/animation/tracks/NumberKeyframeTrack.js +++ b/src/animation/tracks/NumberKeyframeTrack.js @@ -1,3 +1,6 @@ +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track of numeric keyframe values. @@ -7,16 +10,17 @@ * @author tschw */ -THREE.NumberKeyframeTrack = function ( name, times, values, interpolation ) { +function NumberKeyframeTrack ( name, times, values, interpolation ) { + this.isNumberKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); }; -THREE.NumberKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +NumberKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.NumberKeyframeTrack, + constructor: NumberKeyframeTrack, ValueTypeName: 'number', @@ -25,3 +29,6 @@ THREE.NumberKeyframeTrack.prototype = // DefaultInterpolation is inherited } ); + + +export { NumberKeyframeTrack }; \ No newline at end of file diff --git a/src/animation/tracks/QuaternionKeyframeTrack.js b/src/animation/tracks/QuaternionKeyframeTrack.js index e0e3002f7dd9f7..63aec7a0e82d9d 100644 --- a/src/animation/tracks/QuaternionKeyframeTrack.js +++ b/src/animation/tracks/QuaternionKeyframeTrack.js @@ -1,3 +1,8 @@ +import { InterpolateLinear } from '../../constants'; +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { QuaternionLinearInterpolant } from '../../math/interpolants/QuaternionLinearInterpolant'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track of quaternion keyframe values. @@ -7,26 +12,27 @@ * @author tschw */ -THREE.QuaternionKeyframeTrack = function ( name, times, values, interpolation ) { +function QuaternionKeyframeTrack ( name, times, values, interpolation ) { + this.isQuaternionKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); }; -THREE.QuaternionKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +QuaternionKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.QuaternionKeyframeTrack, + constructor: QuaternionKeyframeTrack, ValueTypeName: 'quaternion', // ValueBufferType is inherited - DefaultInterpolation: THREE.InterpolateLinear, + DefaultInterpolation: InterpolateLinear, InterpolantFactoryMethodLinear: function( result ) { - return new THREE.QuaternionLinearInterpolant( + return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); }, @@ -34,3 +40,6 @@ THREE.QuaternionKeyframeTrack.prototype = InterpolantFactoryMethodSmooth: undefined // not yet implemented } ); + + +export { QuaternionKeyframeTrack }; \ No newline at end of file diff --git a/src/animation/tracks/StringKeyframeTrack.js b/src/animation/tracks/StringKeyframeTrack.js index 38afdcb95cd398..df4fe0907cefb6 100644 --- a/src/animation/tracks/StringKeyframeTrack.js +++ b/src/animation/tracks/StringKeyframeTrack.js @@ -1,3 +1,7 @@ +import { InterpolateDiscrete } from '../../constants'; +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track that interpolates Strings @@ -8,24 +12,28 @@ * @author tschw */ -THREE.StringKeyframeTrack = function ( name, times, values, interpolation ) { +function StringKeyframeTrack ( name, times, values, interpolation ) { + this.isStringKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); }; -THREE.StringKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +StringKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.StringKeyframeTrack, + constructor: StringKeyframeTrack, ValueTypeName: 'string', ValueBufferType: Array, - DefaultInterpolation: THREE.InterpolateDiscrete, + DefaultInterpolation: InterpolateDiscrete, InterpolantFactoryMethodLinear: undefined, InterpolantFactoryMethodSmooth: undefined } ); + + +export { StringKeyframeTrack }; \ No newline at end of file diff --git a/src/animation/tracks/VectorKeyframeTrack.js b/src/animation/tracks/VectorKeyframeTrack.js index aa1b04ba240b30..923b32d83211fd 100644 --- a/src/animation/tracks/VectorKeyframeTrack.js +++ b/src/animation/tracks/VectorKeyframeTrack.js @@ -1,3 +1,6 @@ +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track of vectored keyframe values. @@ -8,16 +11,17 @@ * @author tschw */ -THREE.VectorKeyframeTrack = function ( name, times, values, interpolation ) { +function VectorKeyframeTrack ( name, times, values, interpolation ) { + this.isVectorKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); }; -THREE.VectorKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +VectorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.VectorKeyframeTrack, + constructor: VectorKeyframeTrack, ValueTypeName: 'vector' @@ -26,3 +30,6 @@ THREE.VectorKeyframeTrack.prototype = // DefaultInterpolation is inherited } ); + + +export { VectorKeyframeTrack }; \ No newline at end of file diff --git a/src/audio/Audio.js b/src/audio/Audio.js index ba1229dfa64ebc..d0100abdcd1bfa 100644 --- a/src/audio/Audio.js +++ b/src/audio/Audio.js @@ -1,11 +1,14 @@ +import { Object3D } from '../core/Object3D'; + /** * @author mrdoob / http://mrdoob.com/ * @author Reece Aaron Lecrivain / http://reecenotes.com/ */ -THREE.Audio = function ( listener ) { +function Audio ( listener ) { + this.isAudio = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Audio'; @@ -28,9 +31,9 @@ THREE.Audio = function ( listener ) { }; -THREE.Audio.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Audio, + constructor: Audio, getOutput: function () { @@ -287,3 +290,6 @@ THREE.Audio.prototype = Object.assign( Object.create( THREE.Object3D.prototype ) } } ); + + +export { Audio }; \ No newline at end of file diff --git a/src/audio/AudioAnalyser.js b/src/audio/AudioAnalyser.js index 2f6378e2d59163..3f2ebdcc3ac3e0 100644 --- a/src/audio/AudioAnalyser.js +++ b/src/audio/AudioAnalyser.js @@ -2,7 +2,8 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.AudioAnalyser = function ( audio, fftSize ) { +function AudioAnalyser ( audio, fftSize ) { + this.isAudioAnalyser = true; this.analyser = audio.context.createAnalyser(); this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; @@ -13,7 +14,7 @@ THREE.AudioAnalyser = function ( audio, fftSize ) { }; -Object.assign( THREE.AudioAnalyser.prototype, { +Object.assign( AudioAnalyser.prototype, { getFrequencyData: function () { @@ -38,3 +39,6 @@ Object.assign( THREE.AudioAnalyser.prototype, { } } ); + + +export { AudioAnalyser }; \ No newline at end of file diff --git a/src/audio/AudioContext.js b/src/audio/AudioContext.js index 11c6a2033589e0..b8c897cefe64d7 100644 --- a/src/audio/AudioContext.js +++ b/src/audio/AudioContext.js @@ -1,25 +1,9 @@ -/** - * @author mrdoob / http://mrdoob.com/ - */ +var context; -Object.defineProperty( THREE, 'AudioContext', { +export function getAudioContext () { + if ( context === undefined ) { + context = new ( window.AudioContext || window.webkitAudioContext )(); + } - get: ( function () { - - var context; - - return function get() { - - if ( context === undefined ) { - - context = new ( window.AudioContext || window.webkitAudioContext )(); - - } - - return context; - - }; - - } )() - -} ); + return context; +} \ No newline at end of file diff --git a/src/audio/AudioListener.js b/src/audio/AudioListener.js index adeacda1952b73..4a6149544cd907 100644 --- a/src/audio/AudioListener.js +++ b/src/audio/AudioListener.js @@ -1,14 +1,20 @@ +import { Vector3 } from '../math/Vector3'; +import { Quaternion } from '../math/Quaternion'; +import { Object3D } from '../core/Object3D'; +import { getAudioContext } from './AudioContext'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.AudioListener = function () { +function AudioListener () { + this.isAudioListener = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'AudioListener'; - this.context = THREE.AudioContext; + this.context = getAudioContext(); this.gain = this.context.createGain(); this.gain.connect( this.context.destination ); @@ -17,9 +23,9 @@ THREE.AudioListener = function () { }; -THREE.AudioListener.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.AudioListener, + constructor: AudioListener, getInput: function () { @@ -79,15 +85,15 @@ THREE.AudioListener.prototype = Object.assign( Object.create( THREE.Object3D.pro updateMatrixWorld: ( function () { - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3(); + var position = new Vector3(); + var quaternion = new Quaternion(); + var scale = new Vector3(); - var orientation = new THREE.Vector3(); + var orientation = new Vector3(); return function updateMatrixWorld( force ) { - THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); + Object3D.prototype.updateMatrixWorld.call( this, force ); var listener = this.context.listener; var up = this.up; @@ -104,3 +110,6 @@ THREE.AudioListener.prototype = Object.assign( Object.create( THREE.Object3D.pro } )() } ); + + +export { AudioListener }; \ No newline at end of file diff --git a/src/audio/PositionalAudio.js b/src/audio/PositionalAudio.js index 188e20c49bba35..c813381c96577b 100644 --- a/src/audio/PositionalAudio.js +++ b/src/audio/PositionalAudio.js @@ -1,19 +1,24 @@ +import { Vector3 } from '../math/Vector3'; +import { Audio } from './Audio'; +import { Object3D } from '../core/Object3D'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.PositionalAudio = function ( listener ) { +function PositionalAudio ( listener ) { + this.isPositionalAudio = true; - THREE.Audio.call( this, listener ); + Audio.call( this, listener ); this.panner = this.context.createPanner(); this.panner.connect( this.gain ); }; -THREE.PositionalAudio.prototype = Object.assign( Object.create( THREE.Audio.prototype ), { +PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { - constructor: THREE.PositionalAudio, + constructor: PositionalAudio, getOutput: function () { @@ -71,11 +76,11 @@ THREE.PositionalAudio.prototype = Object.assign( Object.create( THREE.Audio.prot updateMatrixWorld: ( function () { - var position = new THREE.Vector3(); + var position = new Vector3(); return function updateMatrixWorld( force ) { - THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); + Object3D.prototype.updateMatrixWorld.call( this, force ); position.setFromMatrixPosition( this.matrixWorld ); @@ -87,3 +92,6 @@ THREE.PositionalAudio.prototype = Object.assign( Object.create( THREE.Audio.prot } ); + + +export { PositionalAudio }; \ No newline at end of file diff --git a/src/cameras/Camera.js b/src/cameras/Camera.js index 11634cae684829..e1c104e5047695 100644 --- a/src/cameras/Camera.js +++ b/src/cameras/Camera.js @@ -1,30 +1,36 @@ +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 */ -THREE.Camera = function () { +function Camera () { + this.isCamera = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Camera'; - this.matrixWorldInverse = new THREE.Matrix4(); - this.projectionMatrix = new THREE.Matrix4(); + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); }; -THREE.Camera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Camera.prototype.constructor = THREE.Camera; +Camera.prototype = Object.create( Object3D.prototype ); +Camera.prototype.constructor = Camera; -THREE.Camera.prototype.getWorldDirection = function () { +Camera.prototype.getWorldDirection = function () { - var quaternion = new THREE.Quaternion(); + var quaternion = new Quaternion(); return function getWorldDirection( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); this.getWorldQuaternion( quaternion ); @@ -34,11 +40,11 @@ THREE.Camera.prototype.getWorldDirection = function () { }(); -THREE.Camera.prototype.lookAt = function () { +Camera.prototype.lookAt = function () { // This routine does not support cameras with rotated and/or translated parent(s) - var m1 = new THREE.Matrix4(); + var m1 = new Matrix4(); return function lookAt( vector ) { @@ -50,15 +56,15 @@ THREE.Camera.prototype.lookAt = function () { }(); -THREE.Camera.prototype.clone = function () { +Camera.prototype.clone = function () { return new this.constructor().copy( this ); }; -THREE.Camera.prototype.copy = function ( source ) { +Camera.prototype.copy = function ( source ) { - THREE.Object3D.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source ); this.matrixWorldInverse.copy( source.matrixWorldInverse ); this.projectionMatrix.copy( source.projectionMatrix ); @@ -66,3 +72,6 @@ THREE.Camera.prototype.copy = function ( source ) { return this; }; + + +export { Camera }; \ No newline at end of file diff --git a/src/cameras/CubeCamera.js b/src/cameras/CubeCamera.js index 006746d5d7ed12..7c157ba4057519 100644 --- a/src/cameras/CubeCamera.js +++ b/src/cameras/CubeCamera.js @@ -1,3 +1,9 @@ +import { Object3D } from '../core/Object3D'; +import { WebGLRenderTargetCube } from '../renderers/WebGLRenderTargetCube'; +import { LinearFilter, RGBFormat } from '../constants'; +import { Vector3 } from '../math/Vector3'; +import { PerspectiveCamera } from './PerspectiveCamera'; + /** * Camera for rendering cube maps * - renders scene into axis-aligned cube @@ -5,47 +11,48 @@ * @author alteredq / http://alteredqualia.com/ */ -THREE.CubeCamera = function ( near, far, cubeResolution ) { +function CubeCamera ( near, far, cubeResolution ) { + this.isCubeCamera = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'CubeCamera'; var fov = 90, aspect = 1; - var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraPX = new PerspectiveCamera( fov, aspect, near, far ); cameraPX.up.set( 0, - 1, 0 ); - cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) ); + cameraPX.lookAt( new Vector3( 1, 0, 0 ) ); this.add( cameraPX ); - var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraNX = new PerspectiveCamera( fov, aspect, near, far ); cameraNX.up.set( 0, - 1, 0 ); - cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) ); + cameraNX.lookAt( new Vector3( - 1, 0, 0 ) ); this.add( cameraNX ); - var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraPY = new PerspectiveCamera( fov, aspect, near, far ); cameraPY.up.set( 0, 0, 1 ); - cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) ); + cameraPY.lookAt( new Vector3( 0, 1, 0 ) ); this.add( cameraPY ); - var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraNY = new PerspectiveCamera( fov, aspect, near, far ); cameraNY.up.set( 0, 0, - 1 ); - cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) ); + cameraNY.lookAt( new Vector3( 0, - 1, 0 ) ); this.add( cameraNY ); - var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); cameraPZ.up.set( 0, - 1, 0 ); - cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) ); + cameraPZ.lookAt( new Vector3( 0, 0, 1 ) ); this.add( cameraPZ ); - var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); cameraNZ.up.set( 0, - 1, 0 ); - cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) ); + cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) ); this.add( cameraNZ ); - var options = { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter }; + var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter }; - this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); + this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); this.updateCubeMap = function ( renderer, scene ) { @@ -82,5 +89,8 @@ THREE.CubeCamera = function ( near, far, cubeResolution ) { }; -THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.CubeCamera.prototype.constructor = THREE.CubeCamera; +CubeCamera.prototype = Object.create( Object3D.prototype ); +CubeCamera.prototype.constructor = CubeCamera; + + +export { CubeCamera }; \ No newline at end of file diff --git a/src/cameras/OrthographicCamera.js b/src/cameras/OrthographicCamera.js index da96a1cb38b171..a2f9c8a0beceef 100644 --- a/src/cameras/OrthographicCamera.js +++ b/src/cameras/OrthographicCamera.js @@ -1,11 +1,15 @@ +import { Camera } from './Camera'; +import { Object3D } from '../core/Object3D'; + /** * @author alteredq / http://alteredqualia.com/ * @author arose / http://github.com/arose */ -THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { +function OrthographicCamera ( left, right, top, bottom, near, far ) { + this.isOrthographicCamera = true; - THREE.Camera.call( this ); + Camera.call( this ); this.type = 'OrthographicCamera'; @@ -24,13 +28,13 @@ THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { }; -THREE.OrthographicCamera.prototype = Object.assign( Object.create( THREE.Camera.prototype ), { +OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - constructor: THREE.OrthographicCamera, + constructor: OrthographicCamera, copy: function ( source ) { - THREE.Camera.prototype.copy.call( this, source ); + Camera.prototype.copy.call( this, source ); this.left = source.left; this.right = source.right; @@ -100,7 +104,7 @@ THREE.OrthographicCamera.prototype = Object.assign( Object.create( THREE.Camera. toJSON: function ( meta ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var data = Object3D.prototype.toJSON.call( this, meta ); data.object.zoom = this.zoom; data.object.left = this.left; @@ -117,3 +121,6 @@ THREE.OrthographicCamera.prototype = Object.assign( Object.create( THREE.Camera. } } ); + + +export { OrthographicCamera }; \ No newline at end of file diff --git a/src/cameras/PerspectiveCamera.js b/src/cameras/PerspectiveCamera.js index 52c612395d7851..d88abf85da6527 100644 --- a/src/cameras/PerspectiveCamera.js +++ b/src/cameras/PerspectiveCamera.js @@ -1,3 +1,7 @@ +import { Camera } from './Camera'; +import { Object3D } from '../core/Object3D'; +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ * @author greggman / http://games.greggman.com/ @@ -5,9 +9,10 @@ * @author tschw */ -THREE.PerspectiveCamera = function ( fov, aspect, near, far ) { +function PerspectiveCamera ( fov, aspect, near, far ) { + this.isPerspectiveCamera = true; - THREE.Camera.call( this ); + Camera.call( this ); this.type = 'PerspectiveCamera'; @@ -28,13 +33,13 @@ THREE.PerspectiveCamera = function ( fov, aspect, near, far ) { }; -THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.prototype ), { +PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - constructor: THREE.PerspectiveCamera, + constructor: PerspectiveCamera, copy: function ( source ) { - THREE.Camera.prototype.copy.call( this, source ); + Camera.prototype.copy.call( this, source ); this.fov = source.fov; this.zoom = source.zoom; @@ -66,7 +71,7 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p // see http://www.bobatkins.com/photography/technical/field_of_view.html var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - this.fov = THREE.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); this.updateProjectionMatrix(); }, @@ -76,7 +81,7 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p */ getFocalLength: function () { - var vExtentSlope = Math.tan( THREE.Math.DEG2RAD * 0.5 * this.fov ); + var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov ); return 0.5 * this.getFilmHeight() / vExtentSlope; @@ -84,8 +89,8 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p getEffectiveFOV: function () { - return THREE.Math.RAD2DEG * 2 * Math.atan( - Math.tan( THREE.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + return _Math.RAD2DEG * 2 * Math.atan( + Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); }, @@ -166,7 +171,7 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p var near = this.near, top = near * Math.tan( - THREE.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, + _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, height = 2 * top, width = this.aspect * height, left = - 0.5 * width, @@ -194,7 +199,7 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p toJSON: function ( meta ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var data = Object3D.prototype.toJSON.call( this, meta ); data.object.fov = this.fov; data.object.zoom = this.zoom; @@ -215,3 +220,6 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p } } ); + + +export { PerspectiveCamera }; \ No newline at end of file diff --git a/src/cameras/StereoCamera.js b/src/cameras/StereoCamera.js index 59550b8d549c97..b02b3c3523b165 100644 --- a/src/cameras/StereoCamera.js +++ b/src/cameras/StereoCamera.js @@ -1,31 +1,36 @@ +import { Matrix4 } from '../math/Matrix4'; +import { _Math } from '../math/Math'; +import { PerspectiveCamera } from './PerspectiveCamera'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.StereoCamera = function () { +function StereoCamera () { + this.isStereoCamera = true; this.type = 'StereoCamera'; this.aspect = 1; - this.cameraL = new THREE.PerspectiveCamera(); + this.cameraL = new PerspectiveCamera(); this.cameraL.layers.enable( 1 ); this.cameraL.matrixAutoUpdate = false; - this.cameraR = new THREE.PerspectiveCamera(); + this.cameraR = new PerspectiveCamera(); this.cameraR.layers.enable( 2 ); this.cameraR.matrixAutoUpdate = false; }; -Object.assign( THREE.StereoCamera.prototype, { +Object.assign( StereoCamera.prototype, { update: ( function () { var focus, fov, aspect, near, far; - var eyeRight = new THREE.Matrix4(); - var eyeLeft = new THREE.Matrix4(); + var eyeRight = new Matrix4(); + var eyeLeft = new Matrix4(); return function update( camera ) { @@ -47,7 +52,7 @@ Object.assign( THREE.StereoCamera.prototype, { var projectionMatrix = camera.projectionMatrix.clone(); var eyeSep = 0.064 / 2; var eyeSepOnProjection = eyeSep * near / focus; - var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 ); + var ymax = near * Math.tan( _Math.DEG2RAD * fov * 0.5 ); var xmin, xmax; // translate xOffset @@ -85,3 +90,6 @@ Object.assign( THREE.StereoCamera.prototype, { } )() } ); + + +export { StereoCamera }; \ No newline at end of file diff --git a/src/constants.js b/src/constants.js new file mode 100644 index 00000000000000..5aebb0129cd4be --- /dev/null +++ b/src/constants.js @@ -0,0 +1,122 @@ +export var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; +export var CullFaceNone = 0; +export var CullFaceBack = 1; +export var CullFaceFront = 2; +export var CullFaceFrontBack = 3; +export var FrontFaceDirectionCW = 0; +export var FrontFaceDirectionCCW = 1; +export var BasicShadowMap = 0; +export var PCFShadowMap = 1; +export var PCFSoftShadowMap = 2; +export var FrontSide = 0; +export var BackSide = 1; +export var DoubleSide = 2; +export var FlatShading = 1; +export var SmoothShading = 2; +export var NoColors = 0; +export var FaceColors = 1; +export var VertexColors = 2; +export var NoBlending = 0; +export var NormalBlending = 1; +export var AdditiveBlending = 2; +export var SubtractiveBlending = 3; +export var MultiplyBlending = 4; +export var CustomBlending = 5; +export var AddEquation = 100; +export var SubtractEquation = 101; +export var ReverseSubtractEquation = 102; +export var MinEquation = 103; +export var MaxEquation = 104; +export var ZeroFactor = 200; +export var OneFactor = 201; +export var SrcColorFactor = 202; +export var OneMinusSrcColorFactor = 203; +export var SrcAlphaFactor = 204; +export var OneMinusSrcAlphaFactor = 205; +export var DstAlphaFactor = 206; +export var OneMinusDstAlphaFactor = 207; +export var DstColorFactor = 208; +export var OneMinusDstColorFactor = 209; +export var SrcAlphaSaturateFactor = 210; +export var NeverDepth = 0; +export var AlwaysDepth = 1; +export var LessDepth = 2; +export var LessEqualDepth = 3; +export var EqualDepth = 4; +export var GreaterEqualDepth = 5; +export var GreaterDepth = 6; +export var NotEqualDepth = 7; +export var MultiplyOperation = 0; +export var MixOperation = 1; +export var AddOperation = 2; +export var NoToneMapping = 0; +export var LinearToneMapping = 1; +export var ReinhardToneMapping = 2; +export var Uncharted2ToneMapping = 3; +export var CineonToneMapping = 4; +export var UVMapping = 300; +export var CubeReflectionMapping = 301; +export var CubeRefractionMapping = 302; +export var EquirectangularReflectionMapping = 303; +export var EquirectangularRefractionMapping = 304; +export var SphericalReflectionMapping = 305; +export var CubeUVReflectionMapping = 306; +export var CubeUVRefractionMapping = 307; +export var RepeatWrapping = 1000; +export var ClampToEdgeWrapping = 1001; +export var MirroredRepeatWrapping = 1002; +export var NearestFilter = 1003; +export var NearestMipMapNearestFilter = 1004; +export var NearestMipMapLinearFilter = 1005; +export var LinearFilter = 1006; +export var LinearMipMapNearestFilter = 1007; +export var LinearMipMapLinearFilter = 1008; +export var UnsignedByteType = 1009; +export var ByteType = 1010; +export var ShortType = 1011; +export var UnsignedShortType = 1012; +export var IntType = 1013; +export var UnsignedIntType = 1014; +export var FloatType = 1015; +export var HalfFloatType = 1025; +export var UnsignedShort4444Type = 1016; +export var UnsignedShort5551Type = 1017; +export var UnsignedShort565Type = 1018; +export var AlphaFormat = 1019; +export var RGBFormat = 1020; +export var RGBAFormat = 1021; +export var LuminanceFormat = 1022; +export var LuminanceAlphaFormat = 1023; +export var RGBEFormat = RGBAFormat; +export var DepthFormat = 1026; +export var RGB_S3TC_DXT1_Format = 2001; +export var RGBA_S3TC_DXT1_Format = 2002; +export var RGBA_S3TC_DXT3_Format = 2003; +export var RGBA_S3TC_DXT5_Format = 2004; +export var RGB_PVRTC_4BPPV1_Format = 2100; +export var RGB_PVRTC_2BPPV1_Format = 2101; +export var RGBA_PVRTC_4BPPV1_Format = 2102; +export var RGBA_PVRTC_2BPPV1_Format = 2103; +export var RGB_ETC1_Format = 2151; +export var LoopOnce = 2200; +export var LoopRepeat = 2201; +export var LoopPingPong = 2202; +export var InterpolateDiscrete = 2300; +export var InterpolateLinear = 2301; +export var InterpolateSmooth = 2302; +export var ZeroCurvatureEnding = 2400; +export var ZeroSlopeEnding = 2401; +export var WrapAroundEnding = 2402; +export var TrianglesDrawMode = 0; +export var TriangleStripDrawMode = 1; +export var TriangleFanDrawMode = 2; +export var LinearEncoding = 3000; +export var sRGBEncoding = 3001; +export var GammaEncoding = 3007; +export var RGBEEncoding = 3002; +export var LogLuvEncoding = 3003; +export var RGBM7Encoding = 3004; +export var RGBM16Encoding = 3005; +export var RGBDEncoding = 3006; +export var BasicDepthPacking = 3200; +export var RGBADepthPacking = 3201; \ No newline at end of file diff --git a/src/core/BufferAttribute.js b/src/core/BufferAttribute.js index 79833201986fc1..ca88f59845be8d 100644 --- a/src/core/BufferAttribute.js +++ b/src/core/BufferAttribute.js @@ -1,10 +1,17 @@ +import { Vector4 } from '../math/Vector4'; +import { Vector3 } from '../math/Vector3'; +import { Vector2 } from '../math/Vector2'; +import { Color } from '../math/Color'; +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.BufferAttribute = function ( array, itemSize, normalized ) { +function BufferAttribute ( array, itemSize, normalized ) { + this.isBufferAttribute = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.array = array; this.itemSize = itemSize; @@ -17,9 +24,9 @@ THREE.BufferAttribute = function ( array, itemSize, normalized ) { }; -THREE.BufferAttribute.prototype = { +BufferAttribute.prototype = { - constructor: THREE.BufferAttribute, + constructor: BufferAttribute, get count() { @@ -86,7 +93,7 @@ THREE.BufferAttribute.prototype = { if ( color === undefined ) { console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new THREE.Color(); + color = new Color(); } @@ -129,7 +136,7 @@ THREE.BufferAttribute.prototype = { if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new THREE.Vector2(); + vector = new Vector2(); } @@ -153,7 +160,7 @@ THREE.BufferAttribute.prototype = { if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new THREE.Vector3(); + vector = new Vector3(); } @@ -178,7 +185,7 @@ THREE.BufferAttribute.prototype = { if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new THREE.Vector4(); + vector = new Vector4(); } @@ -305,66 +312,91 @@ THREE.BufferAttribute.prototype = { // -THREE.Int8Attribute = function ( array, itemSize ) { +function Int8Attribute ( array, itemSize ) { + this.isInt8Attribute = true; - return new THREE.BufferAttribute( new Int8Array( array ), itemSize ); + return new BufferAttribute( new Int8Array( array ), itemSize ); }; -THREE.Uint8Attribute = function ( array, itemSize ) { +function Uint8Attribute ( array, itemSize ) { + this.isUint8Attribute = true; - return new THREE.BufferAttribute( new Uint8Array( array ), itemSize ); + return new BufferAttribute( new Uint8Array( array ), itemSize ); }; -THREE.Uint8ClampedAttribute = function ( array, itemSize ) { +function Uint8ClampedAttribute ( array, itemSize ) { + this.isUint8ClampedAttribute = true; - return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize ); + return new BufferAttribute( new Uint8ClampedArray( array ), itemSize ); }; -THREE.Int16Attribute = function ( array, itemSize ) { +function Int16Attribute ( array, itemSize ) { + this.isInt16Attribute = true; - return new THREE.BufferAttribute( new Int16Array( array ), itemSize ); + return new BufferAttribute( new Int16Array( array ), itemSize ); }; -THREE.Uint16Attribute = function ( array, itemSize ) { +function Uint16Attribute ( array, itemSize ) { + this.isUint16Attribute = true; - return new THREE.BufferAttribute( new Uint16Array( array ), itemSize ); + return new BufferAttribute( new Uint16Array( array ), itemSize ); }; -THREE.Int32Attribute = function ( array, itemSize ) { +function Int32Attribute ( array, itemSize ) { + this.isInt32Attribute = true; - return new THREE.BufferAttribute( new Int32Array( array ), itemSize ); + return new BufferAttribute( new Int32Array( array ), itemSize ); }; -THREE.Uint32Attribute = function ( array, itemSize ) { +function Uint32Attribute ( array, itemSize ) { + this.isUint32Attribute = true; - return new THREE.BufferAttribute( new Uint32Array( array ), itemSize ); + return new BufferAttribute( new Uint32Array( array ), itemSize ); }; -THREE.Float32Attribute = function ( array, itemSize ) { +function Float32Attribute ( array, itemSize ) { + this.isFloat32Attribute = true; - return new THREE.BufferAttribute( new Float32Array( array ), itemSize ); + return new BufferAttribute( new Float32Array( array ), itemSize ); }; -THREE.Float64Attribute = function ( array, itemSize ) { +function Float64Attribute ( array, itemSize ) { + this.isFloat64Attribute = true; - return new THREE.BufferAttribute( new Float64Array( array ), itemSize ); + return new BufferAttribute( new Float64Array( array ), itemSize ); }; // Deprecated -THREE.DynamicBufferAttribute = function ( array, itemSize ) { +function DynamicBufferAttribute ( array, itemSize ) { + this.isDynamicBufferAttribute = true; console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); - return new THREE.BufferAttribute( array, itemSize ).setDynamic( true ); + return new BufferAttribute( array, itemSize ).setDynamic( true ); }; + + +export { + DynamicBufferAttribute, + Float64Attribute, + Float32Attribute, + Uint32Attribute, + Int32Attribute, + Uint16Attribute, + Int16Attribute, + Uint8ClampedAttribute, + Uint8Attribute, + Int8Attribute, + BufferAttribute +}; \ No newline at end of file diff --git a/src/core/BufferGeometry.js b/src/core/BufferGeometry.js index 25a4c8273295be..462c823461a0fb 100644 --- a/src/core/BufferGeometry.js +++ b/src/core/BufferGeometry.js @@ -1,13 +1,26 @@ +import { Vector3 } from '../math/Vector3'; +import { Box3 } from '../math/Box3'; +import { EventDispatcher } from './EventDispatcher'; +import { BufferAttribute, Float32Attribute } from './BufferAttribute'; +import { Sphere } from '../math/Sphere'; +import { DirectGeometry } from './DirectGeometry'; +import { Object3D } from './Object3D'; +import { Matrix4 } from '../math/Matrix4'; +import { Matrix3 } from '../math/Matrix3'; +import { _Math } from '../math/Math'; +import { GeometryIdCount } from './Geometry'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.BufferGeometry = function () { +function BufferGeometry () { + this.isBufferGeometry = true; - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'BufferGeometry'; @@ -26,7 +39,7 @@ THREE.BufferGeometry = function () { }; -Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, { +Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, { getIndex: function () { @@ -42,11 +55,11 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, addAttribute: function ( name, attribute ) { - if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) { + if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) { console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); return; @@ -121,7 +134,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, if ( normal !== undefined ) { - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); normalMatrix.applyToVector3Array( normal.array ); normal.needsUpdate = true; @@ -152,7 +165,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function rotateX( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationX( angle ); @@ -172,7 +185,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function rotateY( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationY( angle ); @@ -192,7 +205,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function rotateZ( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationZ( angle ); @@ -212,7 +225,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function translate( x, y, z ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeTranslation( x, y, z ); @@ -232,7 +245,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function scale( x, y, z ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeScale( x, y, z ); @@ -250,7 +263,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function lookAt( vector ) { - if ( obj === undefined ) obj = new THREE.Object3D(); + if ( obj === undefined ) obj = new Object3D(); obj.lookAt( vector ); @@ -280,17 +293,17 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, var geometry = object.geometry; - if ( object instanceof THREE.Points || object instanceof THREE.Line ) { + if ( (object && object.isPoints) || (object && object.isLine) ) { - var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 ); - var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 ); + var positions = new Float32Attribute( geometry.vertices.length * 3, 3 ); + var colors = new Float32Attribute( geometry.colors.length * 3, 3 ); this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { - var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 ); + var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 ); this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); @@ -308,9 +321,9 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, } - } else if ( object instanceof THREE.Mesh ) { + } else if ( (object && object.isMesh) ) { - if ( geometry instanceof THREE.Geometry ) { + if ( (geometry && geometry.isGeometry) ) { this.fromGeometry( geometry ); @@ -326,7 +339,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, var geometry = object.geometry; - if ( object instanceof THREE.Mesh ) { + if ( (object && object.isMesh) ) { var direct = geometry.__directGeometry; @@ -445,7 +458,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, fromGeometry: function ( geometry ) { - geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry ); + geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); return this.fromDirectGeometry( geometry.__directGeometry ); @@ -454,33 +467,33 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, fromDirectGeometry: function ( geometry ) { var positions = new Float32Array( geometry.vertices.length * 3 ); - this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); if ( geometry.normals.length > 0 ) { var normals = new Float32Array( geometry.normals.length * 3 ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); } if ( geometry.colors.length > 0 ) { var colors = new Float32Array( geometry.colors.length * 3 ); - this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); + this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); } if ( geometry.uvs.length > 0 ) { var uvs = new Float32Array( geometry.uvs.length * 2 ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); } if ( geometry.uvs2.length > 0 ) { var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); - this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); + this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); } @@ -488,7 +501,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array; var indices = new TypeArray( geometry.indices.length * 3 ); - this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); + this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); } @@ -507,7 +520,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, var morphTarget = morphTargets[ i ]; - var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 ); + var attribute = new Float32Attribute( morphTarget.length * 3, 3 ); array.push( attribute.copyVector3sArray( morphTarget ) ); @@ -521,14 +534,14 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, if ( geometry.skinIndices.length > 0 ) { - var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 ); + var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 ); this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); } if ( geometry.skinWeights.length > 0 ) { - var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 ); + var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 ); this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); } @@ -555,7 +568,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, if ( this.boundingBox === null ) { - this.boundingBox = new THREE.Box3(); + this.boundingBox = new Box3(); } @@ -581,14 +594,14 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, computeBoundingSphere: function () { - var box = new THREE.Box3(); - var vector = new THREE.Vector3(); + var box = new Box3(); + var vector = new Vector3(); return function computeBoundingSphere() { if ( this.boundingSphere === null ) { - this.boundingSphere = new THREE.Sphere(); + this.boundingSphere = new Sphere(); } @@ -646,7 +659,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, if ( attributes.normal === undefined ) { - this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); } else { @@ -666,12 +679,12 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, var vA, vB, vC, - pA = new THREE.Vector3(), - pB = new THREE.Vector3(), - pC = new THREE.Vector3(), + pA = new Vector3(), + pB = new Vector3(), + pC = new Vector3(), - cb = new THREE.Vector3(), - ab = new THREE.Vector3(); + cb = new Vector3(), + ab = new Vector3(); // indexed elements @@ -762,7 +775,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, merge: function ( geometry, offset ) { - if ( geometry instanceof THREE.BufferGeometry === false ) { + if ( (geometry && geometry.isBufferGeometry) === false ) { console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); return; @@ -828,7 +841,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, } - var geometry2 = new THREE.BufferGeometry(); + var geometry2 = new BufferGeometry(); var indices = this.index.array; var attributes = this.attributes; @@ -856,7 +869,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, } - geometry2.addAttribute( name, new THREE.BufferAttribute( array2, itemSize ) ); + geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); } @@ -975,7 +988,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return new this.constructor().copy( this ); */ - return new THREE.BufferGeometry().copy( this ); + return new BufferGeometry().copy( this ); }, @@ -1019,4 +1032,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, } ); -THREE.BufferGeometry.MaxIndex = 65535; +BufferGeometry.MaxIndex = 65535; + + +export { BufferGeometry }; \ No newline at end of file diff --git a/src/core/Clock.js b/src/core/Clock.js index e5286030784e37..4a815039a9d992 100644 --- a/src/core/Clock.js +++ b/src/core/Clock.js @@ -2,7 +2,8 @@ * @author alteredq / http://alteredqualia.com/ */ -THREE.Clock = function ( autoStart ) { +function Clock ( autoStart ) { + this.isClock = true; this.autoStart = ( autoStart !== undefined ) ? autoStart : true; @@ -14,9 +15,9 @@ THREE.Clock = function ( autoStart ) { }; -THREE.Clock.prototype = { +Clock.prototype = { - constructor: THREE.Clock, + constructor: Clock, start: function () { @@ -67,3 +68,6 @@ THREE.Clock.prototype = { } }; + + +export { Clock }; \ No newline at end of file diff --git a/src/core/DirectGeometry.js b/src/core/DirectGeometry.js index a50f1a9267bd9a..6daf26aeed5932 100644 --- a/src/core/DirectGeometry.js +++ b/src/core/DirectGeometry.js @@ -1,12 +1,19 @@ +import { Geometry } from './Geometry'; +import { EventDispatcher } from './EventDispatcher'; +import { Vector2 } from '../math/Vector2'; +import { _Math } from '../math/Math'; +import { GeometryIdCount } from './Geometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.DirectGeometry = function () { +function DirectGeometry () { + this.isDirectGeometry = true; - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'DirectGeometry'; @@ -40,10 +47,10 @@ THREE.DirectGeometry = function () { }; -Object.assign( THREE.DirectGeometry.prototype, THREE.EventDispatcher.prototype, { +Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, { - computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox, - computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere, + computeBoundingBox: Geometry.prototype.computeBoundingBox, + computeBoundingSphere: Geometry.prototype.computeBoundingSphere, computeFaceNormals: function () { @@ -207,7 +214,7 @@ Object.assign( THREE.DirectGeometry.prototype, THREE.EventDispatcher.prototype, console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); - this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ); + this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); } @@ -225,7 +232,7 @@ Object.assign( THREE.DirectGeometry.prototype, THREE.EventDispatcher.prototype, console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); - this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ); + this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); } @@ -284,3 +291,6 @@ Object.assign( THREE.DirectGeometry.prototype, THREE.EventDispatcher.prototype, } } ); + + +export { DirectGeometry }; \ No newline at end of file diff --git a/src/core/EventDispatcher.js b/src/core/EventDispatcher.js index b35fd282f0c44e..09a9f3f92ee726 100644 --- a/src/core/EventDispatcher.js +++ b/src/core/EventDispatcher.js @@ -2,9 +2,10 @@ * https://github.com/mrdoob/eventdispatcher.js/ */ -THREE.EventDispatcher = function () {}; +function EventDispatcher () { + this.isEventDispatcher = true;}; -Object.assign( THREE.EventDispatcher.prototype, { +Object.assign( EventDispatcher.prototype, { addEventListener: function ( type, listener ) { @@ -94,3 +95,6 @@ Object.assign( THREE.EventDispatcher.prototype, { } } ); + + +export { EventDispatcher }; \ No newline at end of file diff --git a/src/core/Face3.js b/src/core/Face3.js index dee52fb22d40e7..3defb50bc57265 100644 --- a/src/core/Face3.js +++ b/src/core/Face3.js @@ -1,27 +1,31 @@ +import { Color } from '../math/Color'; +import { Vector3 } from '../math/Vector3'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) { +function Face3 ( a, b, c, normal, color, materialIndex ) { + this.isFace3 = true; this.a = a; this.b = b; this.c = c; - this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3(); + this.normal = (normal && normal.isVector3) ? normal : new Vector3(); this.vertexNormals = Array.isArray( normal ) ? normal : []; - this.color = color instanceof THREE.Color ? color : new THREE.Color(); + this.color = (color && color.isColor) ? color : new Color(); this.vertexColors = Array.isArray( color ) ? color : []; this.materialIndex = materialIndex !== undefined ? materialIndex : 0; }; -THREE.Face3.prototype = { +Face3.prototype = { - constructor: THREE.Face3, + constructor: Face3, clone: function () { @@ -57,3 +61,6 @@ THREE.Face3.prototype = { } }; + + +export { Face3 }; \ No newline at end of file diff --git a/src/core/Geometry.js b/src/core/Geometry.js index c3674acb2749ae..1bb5abb15883ca 100644 --- a/src/core/Geometry.js +++ b/src/core/Geometry.js @@ -1,3 +1,15 @@ +import { EventDispatcher } from './EventDispatcher'; +import { Face3 } from './Face3'; +import { Matrix3 } from '../math/Matrix3'; +import { Sphere } from '../math/Sphere'; +import { Box3 } from '../math/Box3'; +import { Vector3 } from '../math/Vector3'; +import { Matrix4 } from '../math/Matrix4'; +import { Vector2 } from '../math/Vector2'; +import { Color } from '../math/Color'; +import { Object3D } from './Object3D'; +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ * @author kile / http://kile.stravaganza.org/ @@ -7,11 +19,12 @@ * @author bhouston / http://clara.io */ -THREE.Geometry = function () { +function Geometry () { + this.isGeometry = true; - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'Geometry'; @@ -44,11 +57,11 @@ THREE.Geometry = function () { }; -Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { +Object.assign( Geometry.prototype, EventDispatcher.prototype, { applyMatrix: function ( matrix ) { - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { @@ -97,7 +110,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function rotateX( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationX( angle ); @@ -117,7 +130,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function rotateY( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationY( angle ); @@ -137,7 +150,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function rotateZ( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationZ( angle ); @@ -157,7 +170,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function translate( x, y, z ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeTranslation( x, y, z ); @@ -177,7 +190,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function scale( x, y, z ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeScale( x, y, z ); @@ -195,7 +208,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function lookAt( vector ) { - if ( obj === undefined ) obj = new THREE.Object3D(); + if ( obj === undefined ) obj = new Object3D(); obj.lookAt( vector ); @@ -228,29 +241,29 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { - scope.vertices.push( new THREE.Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); + scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); if ( normals !== undefined ) { - tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); + tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); } if ( colors !== undefined ) { - scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); } if ( uvs !== undefined ) { - tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) ); + tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); } if ( uvs2 !== undefined ) { - tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); + tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); } @@ -261,7 +274,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; - var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); + var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); scope.faces.push( face ); @@ -359,7 +372,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { var s = radius === 0 ? 1 : 1.0 / radius; - var matrix = new THREE.Matrix4(); + var matrix = new Matrix4(); matrix.set( s, 0, 0, - s * center.x, 0, s, 0, - s * center.y, @@ -375,7 +388,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { computeFaceNormals: function () { - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); + var cb = new Vector3(), ab = new Vector3(); for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { @@ -407,7 +420,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - vertices[ v ] = new THREE.Vector3(); + vertices[ v ] = new Vector3(); } @@ -417,7 +430,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { // http://www.iquilezles.org/www/articles/normals/normals.htm var vA, vB, vC; - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); + var cb = new Vector3(), ab = new Vector3(); for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { @@ -529,7 +542,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { // use temp geometry to compute face and vertex normals for each morph - var tmpGeo = new THREE.Geometry(); + var tmpGeo = new Geometry(); tmpGeo.faces = this.faces; for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { @@ -549,8 +562,8 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - faceNormal = new THREE.Vector3(); - vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() }; + faceNormal = new Vector3(); + vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; dstNormalsFace.push( faceNormal ); dstNormalsVertex.push( vertexNormals ); @@ -633,7 +646,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { if ( this.boundingBox === null ) { - this.boundingBox = new THREE.Box3(); + this.boundingBox = new Box3(); } @@ -645,7 +658,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { if ( this.boundingSphere === null ) { - this.boundingSphere = new THREE.Sphere(); + this.boundingSphere = new Sphere(); } @@ -655,7 +668,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { merge: function ( geometry, matrix, materialIndexOffset ) { - if ( geometry instanceof THREE.Geometry === false ) { + if ( (geometry && geometry.isGeometry) === false ) { console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); return; @@ -675,7 +688,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { if ( matrix !== undefined ) { - normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + normalMatrix = new Matrix3().getNormalMatrix( matrix ); } @@ -701,7 +714,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { faceVertexNormals = face.vertexNormals, faceVertexColors = face.vertexColors; - faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); + faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); faceCopy.normal.copy( face.normal ); if ( normalMatrix !== undefined ) { @@ -765,7 +778,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { mergeMesh: function ( mesh ) { - if ( mesh instanceof THREE.Mesh === false ) { + if ( (mesh && mesh.isMesh) === false ) { console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); return; @@ -1136,7 +1149,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return new this.constructor().copy( this ); */ - return new THREE.Geometry().copy( this ); + return new Geometry().copy( this ); }, @@ -1202,4 +1215,8 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { } ); -THREE.GeometryIdCount = 0; +var count = 0; +function GeometryIdCount () { return count++; }; + + +export { GeometryIdCount, Geometry }; \ No newline at end of file diff --git a/src/core/InstancedBufferAttribute.js b/src/core/InstancedBufferAttribute.js index a326811d076ff5..b0e5645344187c 100644 --- a/src/core/InstancedBufferAttribute.js +++ b/src/core/InstancedBufferAttribute.js @@ -1,24 +1,30 @@ +import { BufferAttribute } from './BufferAttribute'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) { +function InstancedBufferAttribute ( array, itemSize, meshPerAttribute ) { + this.isInstancedBufferAttribute = this.isBufferAttribute = true; - THREE.BufferAttribute.call( this, array, itemSize ); + BufferAttribute.call( this, array, itemSize ); this.meshPerAttribute = meshPerAttribute || 1; }; -THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype ); -THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute; +InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute; -THREE.InstancedBufferAttribute.prototype.copy = function ( source ) { +InstancedBufferAttribute.prototype.copy = function ( source ) { - THREE.BufferAttribute.prototype.copy.call( this, source ); + BufferAttribute.prototype.copy.call( this, source ); this.meshPerAttribute = source.meshPerAttribute; return this; }; + + +export { InstancedBufferAttribute }; \ No newline at end of file diff --git a/src/core/InstancedBufferGeometry.js b/src/core/InstancedBufferGeometry.js index 4ee05765c77e05..c39f8b52dee0ab 100644 --- a/src/core/InstancedBufferGeometry.js +++ b/src/core/InstancedBufferGeometry.js @@ -1,20 +1,23 @@ +import { BufferGeometry } from './BufferGeometry'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.InstancedBufferGeometry = function () { +function InstancedBufferGeometry () { + this.isInstancedBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'InstancedBufferGeometry'; this.maxInstancedCount = undefined; }; -THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry; +InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry; -THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { +InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { this.groups.push( { @@ -26,7 +29,7 @@ THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, inst }; -THREE.InstancedBufferGeometry.prototype.copy = function ( source ) { +InstancedBufferGeometry.prototype.copy = function ( source ) { var index = source.index; @@ -57,3 +60,6 @@ THREE.InstancedBufferGeometry.prototype.copy = function ( source ) { return this; }; + + +export { InstancedBufferGeometry }; \ No newline at end of file diff --git a/src/core/InstancedInterleavedBuffer.js b/src/core/InstancedInterleavedBuffer.js index c6ec553518deca..72e5369ca79034 100644 --- a/src/core/InstancedInterleavedBuffer.js +++ b/src/core/InstancedInterleavedBuffer.js @@ -1,24 +1,30 @@ +import { InterleavedBuffer } from './InterleavedBuffer'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) { +function InstancedInterleavedBuffer ( array, stride, meshPerAttribute ) { + this.isInstancedInterleavedBuffer = this.isInterleavedBuffer = true; - THREE.InterleavedBuffer.call( this, array, stride ); + InterleavedBuffer.call( this, array, stride ); this.meshPerAttribute = meshPerAttribute || 1; }; -THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype ); -THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer; +InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype ); +InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer; -THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) { +InstancedInterleavedBuffer.prototype.copy = function ( source ) { - THREE.InterleavedBuffer.prototype.copy.call( this, source ); + InterleavedBuffer.prototype.copy.call( this, source ); this.meshPerAttribute = source.meshPerAttribute; return this; }; + + +export { InstancedInterleavedBuffer }; \ No newline at end of file diff --git a/src/core/InterleavedBuffer.js b/src/core/InterleavedBuffer.js index 21a66712f085a8..7aaeea7911e6d8 100644 --- a/src/core/InterleavedBuffer.js +++ b/src/core/InterleavedBuffer.js @@ -1,10 +1,13 @@ +import { _Math } from '../math/Math'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.InterleavedBuffer = function ( array, stride ) { +function InterleavedBuffer ( array, stride ) { + this.isInterleavedBuffer = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.array = array; this.stride = stride; @@ -16,9 +19,9 @@ THREE.InterleavedBuffer = function ( array, stride ) { }; -THREE.InterleavedBuffer.prototype = { +InterleavedBuffer.prototype = { - constructor: THREE.InterleavedBuffer, + constructor: InterleavedBuffer, get length () { @@ -88,3 +91,6 @@ THREE.InterleavedBuffer.prototype = { } }; + + +export { InterleavedBuffer }; \ No newline at end of file diff --git a/src/core/InterleavedBufferAttribute.js b/src/core/InterleavedBufferAttribute.js index 4655b4610e03c0..5a870a951f14a7 100644 --- a/src/core/InterleavedBufferAttribute.js +++ b/src/core/InterleavedBufferAttribute.js @@ -1,10 +1,13 @@ +import { _Math } from '../math/Math'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset, normalized ) { +function InterleavedBufferAttribute ( interleavedBuffer, itemSize, offset, normalized ) { + this.isInterleavedBufferAttribute = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.data = interleavedBuffer; this.itemSize = itemSize; @@ -15,9 +18,9 @@ THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offse }; -THREE.InterleavedBufferAttribute.prototype = { +InterleavedBufferAttribute.prototype = { - constructor: THREE.InterleavedBufferAttribute, + constructor: InterleavedBufferAttribute, get length() { @@ -131,3 +134,6 @@ THREE.InterleavedBufferAttribute.prototype = { } }; + + +export { InterleavedBufferAttribute }; \ No newline at end of file diff --git a/src/core/Layers.js b/src/core/Layers.js index 389aa20158efa3..d9f2dc2fabb2a5 100644 --- a/src/core/Layers.js +++ b/src/core/Layers.js @@ -2,15 +2,16 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.Layers = function () { +function Layers () { + this.isLayers = true; this.mask = 1; }; -THREE.Layers.prototype = { +Layers.prototype = { - constructor: THREE.Layers, + constructor: Layers, set: function ( channel ) { @@ -43,3 +44,6 @@ THREE.Layers.prototype = { } }; + + +export { Layers }; \ No newline at end of file diff --git a/src/core/Object3D.js b/src/core/Object3D.js index 0a7fbe3aa28810..520e30e93357f9 100644 --- a/src/core/Object3D.js +++ b/src/core/Object3D.js @@ -1,3 +1,12 @@ +import { Quaternion } from '../math/Quaternion'; +import { Vector3 } from '../math/Vector3'; +import { Matrix4 } from '../math/Matrix4'; +import { EventDispatcher } from './EventDispatcher'; +import { Euler } from '../math/Euler'; +import { Layers } from './Layers'; +import { Matrix3 } from '../math/Matrix3'; +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ * @author mikael emtinger / http://gomo.se/ @@ -6,11 +15,12 @@ * @author elephantatwork / www.elephantatwork.ch */ -THREE.Object3D = function () { +function Object3D () { + this.isObject3D = true; - Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } ); + Object.defineProperty( this, 'id', { value: Object3DIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'Object3D'; @@ -18,12 +28,12 @@ THREE.Object3D = function () { this.parent = null; this.children = []; - this.up = THREE.Object3D.DefaultUp.clone(); + this.up = Object3D.DefaultUp.clone(); - var position = new THREE.Vector3(); - var rotation = new THREE.Euler(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3( 1, 1, 1 ); + var position = new Vector3(); + var rotation = new Euler(); + var quaternion = new Quaternion(); + var scale = new Vector3( 1, 1, 1 ); function onRotationChange() { @@ -58,20 +68,20 @@ THREE.Object3D = function () { value: scale }, modelViewMatrix: { - value: new THREE.Matrix4() + value: new Matrix4() }, normalMatrix: { - value: new THREE.Matrix3() + value: new Matrix3() } } ); - this.matrix = new THREE.Matrix4(); - this.matrixWorld = new THREE.Matrix4(); + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate; + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; this.matrixWorldNeedsUpdate = false; - this.layers = new THREE.Layers(); + this.layers = new Layers(); this.visible = true; this.castShadow = false; @@ -84,10 +94,10 @@ THREE.Object3D = function () { }; -THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 ); -THREE.Object3D.DefaultMatrixAutoUpdate = true; +Object3D.DefaultUp = new Vector3( 0, 1, 0 ); +Object3D.DefaultMatrixAutoUpdate = true; -Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { +Object.assign( Object3D.prototype, EventDispatcher.prototype, { applyMatrix: function ( matrix ) { @@ -132,7 +142,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { // rotate object on axis in object space // axis is assumed to be normalized - var q1 = new THREE.Quaternion(); + var q1 = new Quaternion(); return function rotateOnAxis( axis, angle ) { @@ -148,7 +158,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { rotateX: function () { - var v1 = new THREE.Vector3( 1, 0, 0 ); + var v1 = new Vector3( 1, 0, 0 ); return function rotateX( angle ) { @@ -160,7 +170,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { rotateY: function () { - var v1 = new THREE.Vector3( 0, 1, 0 ); + var v1 = new Vector3( 0, 1, 0 ); return function rotateY( angle ) { @@ -172,7 +182,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { rotateZ: function () { - var v1 = new THREE.Vector3( 0, 0, 1 ); + var v1 = new Vector3( 0, 0, 1 ); return function rotateZ( angle ) { @@ -187,7 +197,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { // translate object by distance along axis in object space // axis is assumed to be normalized - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function translateOnAxis( axis, distance ) { @@ -203,7 +213,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { translateX: function () { - var v1 = new THREE.Vector3( 1, 0, 0 ); + var v1 = new Vector3( 1, 0, 0 ); return function translateX( distance ) { @@ -215,7 +225,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { translateY: function () { - var v1 = new THREE.Vector3( 0, 1, 0 ); + var v1 = new Vector3( 0, 1, 0 ); return function translateY( distance ) { @@ -227,7 +237,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { translateZ: function () { - var v1 = new THREE.Vector3( 0, 0, 1 ); + var v1 = new Vector3( 0, 0, 1 ); return function translateZ( distance ) { @@ -245,7 +255,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { worldToLocal: function () { - var m1 = new THREE.Matrix4(); + var m1 = new Matrix4(); return function worldToLocal( vector ) { @@ -259,7 +269,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { // This routine does not support objects with rotated and/or translated parent(s) - var m1 = new THREE.Matrix4(); + var m1 = new Matrix4(); return function lookAt( vector ) { @@ -292,7 +302,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { } - if ( object instanceof THREE.Object3D ) { + if ( (object && object.isObject3D) ) { if ( object.parent !== null ) { @@ -376,7 +386,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { getWorldPosition: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); this.updateMatrixWorld( true ); @@ -386,12 +396,12 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { getWorldQuaternion: function () { - var position = new THREE.Vector3(); - var scale = new THREE.Vector3(); + var position = new Vector3(); + var scale = new Vector3(); return function getWorldQuaternion( optionalTarget ) { - var result = optionalTarget || new THREE.Quaternion(); + var result = optionalTarget || new Quaternion(); this.updateMatrixWorld( true ); @@ -405,11 +415,11 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { getWorldRotation: function () { - var quaternion = new THREE.Quaternion(); + var quaternion = new Quaternion(); return function getWorldRotation( optionalTarget ) { - var result = optionalTarget || new THREE.Euler(); + var result = optionalTarget || new Euler(); this.getWorldQuaternion( quaternion ); @@ -421,12 +431,12 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { getWorldScale: function () { - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); + var position = new Vector3(); + var quaternion = new Quaternion(); return function getWorldScale( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); this.updateMatrixWorld( true ); @@ -440,11 +450,11 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { getWorldDirection: function () { - var quaternion = new THREE.Quaternion(); + var quaternion = new Quaternion(); return function getWorldDirection( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); this.getWorldQuaternion( quaternion ); @@ -711,4 +721,8 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { } ); -THREE.Object3DIdCount = 0; +var count = 0; +function Object3DIdCount () { return count++; }; + + +export { Object3DIdCount, Object3D }; \ No newline at end of file diff --git a/src/core/Raycaster.js b/src/core/Raycaster.js index 8eda8ffc19d9cf..440b29c62bee40 100644 --- a/src/core/Raycaster.js +++ b/src/core/Raycaster.js @@ -1,135 +1,137 @@ +import { Ray } from '../math/Ray'; + /** * @author mrdoob / http://mrdoob.com/ * @author bhouston / http://clara.io/ * @author stephomi / http://stephaneginier.com/ */ -( function ( THREE ) { - - THREE.Raycaster = function ( origin, direction, near, far ) { +function Raycaster ( origin, direction, near, far ) { + this.isRaycaster = true; - this.ray = new THREE.Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - this.near = near || 0; - this.far = far || Infinity; - - this.params = { - Mesh: {}, - Line: {}, - LOD: {}, - Points: { threshold: 1 }, - Sprite: {} - }; - - Object.defineProperties( this.params, { - PointCloud: { - get: function () { - console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); - return this.Points; - } - } - } ); + this.near = near || 0; + this.far = far || Infinity; + this.params = { + Mesh: {}, + Line: {}, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} }; - function ascSort( a, b ) { + Object.defineProperties( this.params, { + PointCloud: { + get: function () { + console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); + return this.Points; + } + } + } ); + +}; - return a.distance - b.distance; +function ascSort( a, b ) { - } + return a.distance - b.distance; - function intersectObject( object, raycaster, intersects, recursive ) { +} - if ( object.visible === false ) return; +function intersectObject( object, raycaster, intersects, recursive ) { - object.raycast( raycaster, intersects ); + if ( object.visible === false ) return; - if ( recursive === true ) { + object.raycast( raycaster, intersects ); - var children = object.children; + if ( recursive === true ) { - for ( var i = 0, l = children.length; i < l; i ++ ) { + var children = object.children; - intersectObject( children[ i ], raycaster, intersects, true ); + for ( var i = 0, l = children.length; i < l; i ++ ) { - } + intersectObject( children[ i ], raycaster, intersects, true ); } } - // +} - THREE.Raycaster.prototype = { +// - constructor: THREE.Raycaster, +Raycaster.prototype = { - linePrecision: 1, + constructor: Raycaster, - set: function ( origin, direction ) { + linePrecision: 1, - // direction is assumed to be normalized (for accurate distance calculations) + set: function ( origin, direction ) { - this.ray.set( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - }, + this.ray.set( origin, direction ); - setFromCamera: function ( coords, camera ) { + }, - if ( camera instanceof THREE.PerspectiveCamera ) { + setFromCamera: function ( coords, camera ) { - this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); - this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + if ( (camera && camera.isPerspectiveCamera) ) { - } else if ( camera instanceof THREE.OrthographicCamera ) { + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); - this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera - this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); + } else if ( (camera && camera.isOrthographicCamera) ) { - } else { + this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera + this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); - console.error( 'THREE.Raycaster: Unsupported camera type.' ); + } else { - } + console.error( 'THREE.Raycaster: Unsupported camera type.' ); + + } - }, + }, - intersectObject: function ( object, recursive ) { + intersectObject: function ( object, recursive ) { - var intersects = []; + var intersects = []; - intersectObject( object, this, intersects, recursive ); + intersectObject( object, this, intersects, recursive ); - intersects.sort( ascSort ); + intersects.sort( ascSort ); - return intersects; + return intersects; - }, + }, - intersectObjects: function ( objects, recursive ) { + intersectObjects: function ( objects, recursive ) { - var intersects = []; + var intersects = []; - if ( Array.isArray( objects ) === false ) { + if ( Array.isArray( objects ) === false ) { - console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); - return intersects; + console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); + return intersects; - } + } - for ( var i = 0, l = objects.length; i < l; i ++ ) { + for ( var i = 0, l = objects.length; i < l; i ++ ) { - intersectObject( objects[ i ], this, intersects, recursive ); + intersectObject( objects[ i ], this, intersects, recursive ); - } + } - intersects.sort( ascSort ); + intersects.sort( ascSort ); - return intersects; + return intersects; - } + } + +}; - }; -}( THREE ) ); +export { Raycaster }; \ No newline at end of file diff --git a/src/core/Uniform.js b/src/core/Uniform.js index e13a5a0b27a9c3..1c27c24f4a9023 100644 --- a/src/core/Uniform.js +++ b/src/core/Uniform.js @@ -2,7 +2,8 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.Uniform = function ( value ) { +function Uniform ( value ) { + this.isUniform = true; if ( typeof value === 'string' ) { @@ -17,9 +18,9 @@ THREE.Uniform = function ( value ) { }; -THREE.Uniform.prototype = { +Uniform.prototype = { - constructor: THREE.Uniform, + constructor: Uniform, onUpdate: function ( callback ) { @@ -31,3 +32,6 @@ THREE.Uniform.prototype = { } }; + + +export { Uniform }; \ No newline at end of file diff --git a/src/extras/CurveUtils.js b/src/extras/CurveUtils.js index 1c0ea80f63d9a0..bc60235fbc2980 100644 --- a/src/extras/CurveUtils.js +++ b/src/extras/CurveUtils.js @@ -1,8 +1,10 @@ +var CurveUtils; + /** * @author zz85 / http://www.lab4games.net/zz85/blog */ -THREE.CurveUtils = { +CurveUtils = { tangentQuadraticBezier: function ( t, p0, p1, p2 ) { @@ -47,3 +49,6 @@ THREE.CurveUtils = { } }; + + +export { CurveUtils }; \ No newline at end of file diff --git a/src/extras/SceneUtils.js b/src/extras/SceneUtils.js index c86eaa9a6faa8b..d866c90a370b25 100644 --- a/src/extras/SceneUtils.js +++ b/src/extras/SceneUtils.js @@ -1,16 +1,22 @@ +import { Matrix4 } from '../math/Matrix4'; +import { Mesh } from '../objects/Mesh'; +import { Group } from '../objects/Group'; + +var SceneUtils; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.SceneUtils = { +SceneUtils = { createMultiMaterialObject: function ( geometry, materials ) { - var group = new THREE.Group(); + var group = new Group(); for ( var i = 0, l = materials.length; i < l; i ++ ) { - group.add( new THREE.Mesh( geometry, materials[ i ] ) ); + group.add( new Mesh( geometry, materials[ i ] ) ); } @@ -28,7 +34,7 @@ THREE.SceneUtils = { attach: function ( child, scene, parent ) { - var matrixWorldInverse = new THREE.Matrix4(); + var matrixWorldInverse = new Matrix4(); matrixWorldInverse.getInverse( parent.matrixWorld ); child.applyMatrix( matrixWorldInverse ); @@ -38,3 +44,6 @@ THREE.SceneUtils = { } }; + + +export { SceneUtils }; \ No newline at end of file diff --git a/src/extras/ShapeUtils.js b/src/extras/ShapeUtils.js index 795781358b60b9..edf861fa0f8cd0 100644 --- a/src/extras/ShapeUtils.js +++ b/src/extras/ShapeUtils.js @@ -1,8 +1,10 @@ +var ShapeUtils; + /** * @author zz85 / http://www.lab4games.net/zz85/blog */ -THREE.ShapeUtils = { +ShapeUtils = { // calculate area of the contour polygon @@ -105,7 +107,7 @@ THREE.ShapeUtils = { var u, v, w; - if ( THREE.ShapeUtils.area( contour ) > 0.0 ) { + if ( ShapeUtils.area( contour ) > 0.0 ) { for ( v = 0; v < n; v ++ ) verts[ v ] = v; @@ -654,7 +656,7 @@ THREE.ShapeUtils = { // remove holes by cutting paths to holes and adding them to the shape var shapeWithoutHoles = removeHoles( contour, holes ); - var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape + var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape //console.log( "triangles",triangles, triangles.length ); // check all face vertices against all points map @@ -685,7 +687,7 @@ THREE.ShapeUtils = { isClockWise: function ( pts ) { - return THREE.ShapeUtils.area( pts ) < 0; + return ShapeUtils.area( pts ) < 0; }, @@ -763,3 +765,6 @@ THREE.ShapeUtils = { } )() }; + + +export { ShapeUtils }; \ No newline at end of file diff --git a/src/extras/core/Curve.js b/src/extras/core/Curve.js index e869e61f7dc351..6f5843cad37689 100644 --- a/src/extras/core/Curve.js +++ b/src/extras/core/Curve.js @@ -33,13 +33,14 @@ * Abstract Curve base class **************************************************************/ -THREE.Curve = function () { +function Curve () { + this.isCurve = true; }; -THREE.Curve.prototype = { +Curve.prototype = { - constructor: THREE.Curve, + constructor: Curve, // Virtual base class method to overwrite and implement in subclasses // - t [0 .. 1] @@ -273,12 +274,15 @@ THREE.Curve.prototype = { // A Factory method for creating new curve subclasses -THREE.Curve.create = function ( constructor, getPointFunc ) { +Curve.create = function ( constructor, getPointFunc ) { - constructor.prototype = Object.create( THREE.Curve.prototype ); + constructor.prototype = Object.create( Curve.prototype ); constructor.prototype.constructor = constructor; constructor.prototype.getPoint = getPointFunc; return constructor; }; + + +export { Curve }; \ No newline at end of file diff --git a/src/extras/core/CurvePath.js b/src/extras/core/CurvePath.js index 6eb94bfad40c2f..c9df8d79eed09e 100644 --- a/src/extras/core/CurvePath.js +++ b/src/extras/core/CurvePath.js @@ -1,3 +1,8 @@ +import { Curve } from './Curve'; +import { Vector3 } from '../../math/Vector3'; +import { Geometry } from '../../core/Geometry'; +import { LineCurve } from '../curves/LineCurve'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * @@ -8,7 +13,8 @@ * curves, but retains the api of a curve **************************************************************/ -THREE.CurvePath = function () { +function CurvePath () { + this.isCurvePath = true; this.curves = []; @@ -16,9 +22,9 @@ THREE.CurvePath = function () { }; -THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype ), { +CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { - constructor: THREE.CurvePath, + constructor: CurvePath, add: function ( curve ) { @@ -34,7 +40,7 @@ THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype if ( ! startPoint.equals( endPoint ) ) { - this.curves.push( new THREE.LineCurve( endPoint, startPoint ) ); + this.curves.push( new LineCurve( endPoint, startPoint ) ); } @@ -163,9 +169,9 @@ THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) { var curve = curves[ i ]; - var resolution = curve instanceof THREE.EllipseCurve ? divisions * 2 - : curve instanceof THREE.LineCurve ? 1 - : curve instanceof THREE.SplineCurve ? divisions * curve.points.length + var resolution = (curve && curve.isEllipseCurve) ? divisions * 2 + : (curve && curve.isLineCurve) ? 1 + : (curve && curve.isSplineCurve) ? divisions * curve.points.length : divisions; var pts = curve.getPoints( resolution ); @@ -217,12 +223,12 @@ THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype createGeometry: function ( points ) { - var geometry = new THREE.Geometry(); + var geometry = new Geometry(); for ( var i = 0, l = points.length; i < l; i ++ ) { var point = points[ i ]; - geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) ); + geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); } @@ -231,3 +237,6 @@ THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype } } ); + + +export { CurvePath }; \ No newline at end of file diff --git a/src/extras/core/Font.js b/src/extras/core/Font.js index 4f13af583d7e87..619fe7d24a1723 100644 --- a/src/extras/core/Font.js +++ b/src/extras/core/Font.js @@ -1,15 +1,19 @@ +import { ShapeUtils } from '../ShapeUtils'; +import { ShapePath } from './Path'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * @author mrdoob / http://mrdoob.com/ */ -THREE.Font = function ( data ) { +function Font ( data ) { + this.isFont = true; this.data = data; }; -Object.assign( THREE.Font.prototype, { +Object.assign( Font.prototype, { generateShapes: function ( text, size, divisions ) { @@ -40,9 +44,9 @@ Object.assign( THREE.Font.prototype, { if ( ! glyph ) return; - var path = new THREE.ShapePath(); + var path = new ShapePath(); - var pts = [], b2 = THREE.ShapeUtils.b2, b3 = THREE.ShapeUtils.b3; + var pts = [], b2 = ShapeUtils.b2, b3 = ShapeUtils.b3; var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; if ( glyph.o ) { @@ -162,3 +166,6 @@ Object.assign( THREE.Font.prototype, { } } ); + + +export { Font }; \ No newline at end of file diff --git a/src/extras/core/Path.js b/src/extras/core/Path.js index c2246e3a7620ba..7dfdef956f6d6a 100644 --- a/src/extras/core/Path.js +++ b/src/extras/core/Path.js @@ -1,13 +1,20 @@ +import { PathPrototype } from './PathPrototype'; +import { Shape } from './Shape'; +import { ShapeUtils } from '../ShapeUtils'; +import { Vector2 } from '../../math/Vector2'; +import { CurvePath } from './CurvePath'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * Creates free form 2d path using series of points, lines or curves. * **/ -THREE.Path = function ( points ) { +function Path ( points ) { + this.isPath = true; - THREE.CurvePath.call( this ); - this.currentPoint = new THREE.Vector2(); + CurvePath.call( this ); + this.currentPoint = new Vector2(); if ( points ) { @@ -17,140 +24,20 @@ THREE.Path = function ( points ) { }; -THREE.Path.prototype = Object.assign( Object.create( THREE.CurvePath.prototype ), { - - constructor: THREE.Path, - - // Create path using straight lines to connect all points - // - vectors: array of Vector2 - fromPoints: function ( vectors ) { - - this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - - for ( var i = 1, l = vectors.length; i < l; i ++ ) { - - this.lineTo( vectors[ i ].x, vectors[ i ].y ); - - } - - }, - - moveTo: function ( x, y ) { - - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? - - }, - - lineTo: function ( x, y ) { - - var curve = new THREE.LineCurve( this.currentPoint.clone(), new THREE.Vector2( x, y ) ); - this.curves.push( curve ); - - this.currentPoint.set( x, y ); - - }, - - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - - var curve = new THREE.QuadraticBezierCurve( - this.currentPoint.clone(), - new THREE.Vector2( aCPx, aCPy ), - new THREE.Vector2( aX, aY ) - ); - - this.curves.push( curve ); - - this.currentPoint.set( aX, aY ); - - }, - - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - - var curve = new THREE.CubicBezierCurve( - this.currentPoint.clone(), - new THREE.Vector2( aCP1x, aCP1y ), - new THREE.Vector2( aCP2x, aCP2y ), - new THREE.Vector2( aX, aY ) - ); - - this.curves.push( curve ); - - this.currentPoint.set( aX, aY ); - - }, - - splineThru: function ( pts /*Array of Vector*/ ) { - - var npts = [ this.currentPoint.clone() ].concat( pts ); - - var curve = new THREE.SplineCurve( npts ); - this.curves.push( curve ); - - this.currentPoint.copy( pts[ pts.length - 1 ] ); - - }, - - arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; - - this.absarc( aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); - - }, - - absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - - this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - - }, - - ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; - - this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - - }, - - absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - - var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - - if ( this.curves.length > 0 ) { - - // if a previous curve is present, attempt to join - var firstPoint = curve.getPoint( 0 ); - - if ( ! firstPoint.equals( this.currentPoint ) ) { - - this.lineTo( firstPoint.x, firstPoint.y ); - - } - - } - - this.curves.push( curve ); - - var lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); - - } - -} ); +Path.prototype = PathPrototype; +PathPrototype.constructor = Path; // minimal class for proxing functions to Path. Replaces old "extractSubpaths()" -THREE.ShapePath = function() { +function ShapePath() { + this.isShapePath = true; this.subPaths = []; this.currentPath = null; } -THREE.ShapePath.prototype = { +ShapePath.prototype = { moveTo: function ( x, y ) { - this.currentPath = new THREE.Path(); + this.currentPath = new Path(); this.subPaths.push(this.currentPath); this.currentPath.moveTo( x, y ); }, @@ -177,7 +64,7 @@ THREE.ShapePath.prototype = { var tmpPath = inSubpaths[ i ]; - var tmpShape = new THREE.Shape(); + var tmpShape = new Shape(); tmpShape.curves = tmpPath.curves; shapes.push( tmpShape ); @@ -247,7 +134,7 @@ THREE.ShapePath.prototype = { } - var isClockWise = THREE.ShapeUtils.isClockWise; + var isClockWise = ShapeUtils.isClockWise; var subPaths = this.subPaths; if ( subPaths.length === 0 ) return []; @@ -260,7 +147,7 @@ THREE.ShapePath.prototype = { if ( subPaths.length === 1 ) { tmpPath = subPaths[ 0 ]; - tmpShape = new THREE.Shape(); + tmpShape = new Shape(); tmpShape.curves = tmpPath.curves; shapes.push( tmpShape ); return shapes; @@ -292,7 +179,7 @@ THREE.ShapePath.prototype = { if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; - newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints }; + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; newShapes[ mainIdx ].s.curves = tmpPath.curves; if ( holesFirst ) mainIdx ++; @@ -394,3 +281,6 @@ THREE.ShapePath.prototype = { } } + + +export { ShapePath, Path }; \ No newline at end of file diff --git a/src/extras/core/PathPrototype.js b/src/extras/core/PathPrototype.js new file mode 100644 index 00000000000000..d2db1a76208814 --- /dev/null +++ b/src/extras/core/PathPrototype.js @@ -0,0 +1,131 @@ +import { CurvePath } from './CurvePath'; +import { EllipseCurve } from '../curves/EllipseCurve'; +import { SplineCurve } from '../curves/SplineCurve'; +import { Vector2 } from '../../math/Vector2'; +import { CubicBezierCurve } from '../curves/CubicBezierCurve'; +import { QuadraticBezierCurve } from '../curves/QuadraticBezierCurve'; +import { LineCurve } from '../curves/LineCurve'; + +var PathPrototype; + +PathPrototype = Object.assign( Object.create( CurvePath.prototype ), { + + fromPoints: function ( vectors ) { + + this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); + + for ( var i = 1, l = vectors.length; i < l; i ++ ) { + + this.lineTo( vectors[ i ].x, vectors[ i ].y ); + + } + + }, + + moveTo: function ( x, y ) { + + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + + }, + + lineTo: function ( x, y ) { + + var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); + + this.currentPoint.set( x, y ); + + }, + + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + + var curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + }, + + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + var curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + }, + + splineThru: function ( pts /*Array of Vector*/ ) { + + var npts = [ this.currentPoint.clone() ].concat( pts ); + + var curve = new SplineCurve( npts ); + this.curves.push( curve ); + + this.currentPoint.copy( pts[ pts.length - 1 ] ); + + }, + + arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; + + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); + + }, + + absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + }, + + ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; + + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + }, + + absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + if ( this.curves.length > 0 ) { + + // if a previous curve is present, attempt to join + var firstPoint = curve.getPoint( 0 ); + + if ( ! firstPoint.equals( this.currentPoint ) ) { + + this.lineTo( firstPoint.x, firstPoint.y ); + + } + + } + + this.curves.push( curve ); + + var lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); + + } + +} ) + +export { PathPrototype }; \ No newline at end of file diff --git a/src/extras/core/Shape.js b/src/extras/core/Shape.js index b785e068be7b86..a962e31b94d82b 100644 --- a/src/extras/core/Shape.js +++ b/src/extras/core/Shape.js @@ -1,3 +1,8 @@ +import { PathPrototype } from './PathPrototype'; +import { ShapeGeometry } from '../geometries/ShapeGeometry'; +import { ExtrudeGeometry } from '../geometries/ExtrudeGeometry'; +import { Path } from './Path'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * Defines a 2d shape plane using paths. @@ -9,23 +14,24 @@ // STEP 3a - Extract points from each shape, turn to vertices // STEP 3b - Triangulate each shape, add faces. -THREE.Shape = function () { +function Shape () { + this.isShape = true; - THREE.Path.apply( this, arguments ); + Path.apply( this, arguments ); this.holes = []; }; -THREE.Shape.prototype = Object.assign( Object.create( THREE.Path.prototype ), { +Shape.prototype = Object.assign( Object.create( PathPrototype ), { - constructor: THREE.Shape, + constructor: Shape, // Convenience method to return ExtrudeGeometry extrude: function ( options ) { - return new THREE.ExtrudeGeometry( this, options ); + return new ExtrudeGeometry( this, options ); }, @@ -33,7 +39,7 @@ THREE.Shape.prototype = Object.assign( Object.create( THREE.Path.prototype ), { makeGeometry: function ( options ) { - return new THREE.ShapeGeometry( this, options ); + return new ShapeGeometry( this, options ); }, @@ -71,3 +77,6 @@ THREE.Shape.prototype = Object.assign( Object.create( THREE.Path.prototype ), { } } ); + + +export { Shape }; \ No newline at end of file diff --git a/src/extras/curves/ArcCurve.js b/src/extras/curves/ArcCurve.js index 5f7bc9b0f7425d..23fc96ea8c9346 100644 --- a/src/extras/curves/ArcCurve.js +++ b/src/extras/curves/ArcCurve.js @@ -1,12 +1,18 @@ +import { EllipseCurve } from './EllipseCurve'; + /************************************************************** * Arc curve **************************************************************/ -THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { +function ArcCurve ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + this.isArcCurve = this.isEllipseCurve = this.isCurve = true; - THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); }; -THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype ); -THREE.ArcCurve.prototype.constructor = THREE.ArcCurve; +ArcCurve.prototype = Object.create( EllipseCurve.prototype ); +ArcCurve.prototype.constructor = ArcCurve; + + +export { ArcCurve }; \ No newline at end of file diff --git a/src/extras/curves/CatmullRomCurve3.js b/src/extras/curves/CatmullRomCurve3.js index 2b57912fd33c0e..bbe22a76ede2fd 100644 --- a/src/extras/curves/CatmullRomCurve3.js +++ b/src/extras/curves/CatmullRomCurve3.js @@ -1,3 +1,8 @@ +import { Vector3 } from '../../math/Vector3'; +import { Curve } from '../core/Curve'; + +var CatmullRomCurve3; + /** * @author zz85 https://github.com/zz85 * @@ -9,10 +14,10 @@ * curve.tension is used for catmullrom which defaults to 0.5 */ -THREE.CatmullRomCurve3 = ( function() { +CatmullRomCurve3 = ( function() { var - tmp = new THREE.Vector3(), + tmp = new Vector3(), px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly(); @@ -79,7 +84,7 @@ THREE.CatmullRomCurve3 = ( function() { }; // Subclass Three.js curve - return THREE.Curve.create( + return Curve.create( function ( p /* array of Vector3 */ ) { @@ -167,7 +172,7 @@ THREE.CatmullRomCurve3 = ( function() { } - var v = new THREE.Vector3( + var v = new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) @@ -180,3 +185,6 @@ THREE.CatmullRomCurve3 = ( function() { ); } )(); + + +export { CatmullRomCurve3 }; \ No newline at end of file diff --git a/src/extras/curves/ClosedSplineCurve3.js b/src/extras/curves/ClosedSplineCurve3.js index d1d7102192313c..9dea7d1e122bba 100644 --- a/src/extras/curves/ClosedSplineCurve3.js +++ b/src/extras/curves/ClosedSplineCurve3.js @@ -1,16 +1,22 @@ +import { CatmullRomCurve3 } from './CatmullRomCurve3'; + /************************************************************** * Closed Spline 3D curve **************************************************************/ -THREE.ClosedSplineCurve3 = function ( points ) { +function ClosedSplineCurve3 ( points ) { + this.isClosedSplineCurve3 = this.isCatmullRomCurve3 = true; console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' ); - THREE.CatmullRomCurve3.call( this, points ); + CatmullRomCurve3.call( this, points ); this.type = 'catmullrom'; this.closed = true; }; -THREE.ClosedSplineCurve3.prototype = Object.create( THREE.CatmullRomCurve3.prototype ); +ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype ); + + +export { ClosedSplineCurve3 }; \ No newline at end of file diff --git a/src/extras/curves/CubicBezierCurve.js b/src/extras/curves/CubicBezierCurve.js index 3d751bbe23d0cb..557db4d8f065fe 100644 --- a/src/extras/curves/CubicBezierCurve.js +++ b/src/extras/curves/CubicBezierCurve.js @@ -1,8 +1,14 @@ +import { Curve } from '../core/Curve'; +import { Vector2 } from '../../math/Vector2'; +import { CurveUtils } from '../CurveUtils'; +import { ShapeUtils } from '../ShapeUtils'; + /************************************************************** * Cubic Bezier curve **************************************************************/ -THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { +function CubicBezierCurve ( v0, v1, v2, v3 ) { + this.isCubicBezierCurve = this.isCurve = true; this.v0 = v0; this.v1 = v1; @@ -11,27 +17,30 @@ THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { }; -THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve; +CubicBezierCurve.prototype = Object.create( Curve.prototype ); +CubicBezierCurve.prototype.constructor = CubicBezierCurve; -THREE.CubicBezierCurve.prototype.getPoint = function ( t ) { +CubicBezierCurve.prototype.getPoint = function ( t ) { - var b3 = THREE.ShapeUtils.b3; + var b3 = ShapeUtils.b3; - return new THREE.Vector2( + return new Vector2( b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) ); }; -THREE.CubicBezierCurve.prototype.getTangent = function( t ) { +CubicBezierCurve.prototype.getTangent = function( t ) { - var tangentCubicBezier = THREE.CurveUtils.tangentCubicBezier; + var tangentCubicBezier = CurveUtils.tangentCubicBezier; - return new THREE.Vector2( + return new Vector2( tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) ).normalize(); }; + + +export { CubicBezierCurve }; \ No newline at end of file diff --git a/src/extras/curves/CubicBezierCurve3.js b/src/extras/curves/CubicBezierCurve3.js index 1a49b6ae9c314c..05903b6dd6f3b7 100644 --- a/src/extras/curves/CubicBezierCurve3.js +++ b/src/extras/curves/CubicBezierCurve3.js @@ -1,8 +1,14 @@ +import { Vector3 } from '../../math/Vector3'; +import { ShapeUtils } from '../ShapeUtils'; +import { Curve } from '../core/Curve'; + +var CubicBezierCurve3; + /************************************************************** * Cubic Bezier 3D curve **************************************************************/ -THREE.CubicBezierCurve3 = THREE.Curve.create( +CubicBezierCurve3 = Curve.create( function ( v0, v1, v2, v3 ) { @@ -15,9 +21,9 @@ THREE.CubicBezierCurve3 = THREE.Curve.create( function ( t ) { - var b3 = THREE.ShapeUtils.b3; + var b3 = ShapeUtils.b3; - return new THREE.Vector3( + return new Vector3( b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ), b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ) @@ -26,3 +32,6 @@ THREE.CubicBezierCurve3 = THREE.Curve.create( } ); + + +export { CubicBezierCurve3 }; \ No newline at end of file diff --git a/src/extras/curves/EllipseCurve.js b/src/extras/curves/EllipseCurve.js index 64e74616de67b4..f9b5a5f7bb29c1 100644 --- a/src/extras/curves/EllipseCurve.js +++ b/src/extras/curves/EllipseCurve.js @@ -1,8 +1,12 @@ +import { Curve } from '../core/Curve'; +import { Vector2 } from '../../math/Vector2'; + /************************************************************** * Ellipse curve **************************************************************/ -THREE.EllipseCurve = function( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { +function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + this.isEllipseCurve = this.isCurve = true; this.aX = aX; this.aY = aY; @@ -19,10 +23,10 @@ THREE.EllipseCurve = function( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, }; -THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve; +EllipseCurve.prototype = Object.create( Curve.prototype ); +EllipseCurve.prototype.constructor = EllipseCurve; -THREE.EllipseCurve.prototype.getPoint = function( t ) { +EllipseCurve.prototype.getPoint = function( t ) { var twoPi = Math.PI * 2; var deltaAngle = this.aEndAngle - this.aStartAngle; @@ -78,6 +82,9 @@ THREE.EllipseCurve.prototype.getPoint = function( t ) { } - return new THREE.Vector2( x, y ); + return new Vector2( x, y ); }; + + +export { EllipseCurve }; \ No newline at end of file diff --git a/src/extras/curves/LineCurve.js b/src/extras/curves/LineCurve.js index e4326886d3606c..bc44749a71028b 100644 --- a/src/extras/curves/LineCurve.js +++ b/src/extras/curves/LineCurve.js @@ -1,18 +1,21 @@ +import { Curve } from '../core/Curve'; + /************************************************************** * Line **************************************************************/ -THREE.LineCurve = function ( v1, v2 ) { +function LineCurve ( v1, v2 ) { + this.isLineCurve = this.isCurve = true; this.v1 = v1; this.v2 = v2; }; -THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.LineCurve.prototype.constructor = THREE.LineCurve; +LineCurve.prototype = Object.create( Curve.prototype ); +LineCurve.prototype.constructor = LineCurve; -THREE.LineCurve.prototype.getPoint = function ( t ) { +LineCurve.prototype.getPoint = function ( t ) { if ( t === 1 ) { @@ -29,16 +32,19 @@ THREE.LineCurve.prototype.getPoint = function ( t ) { // Line curve is linear, so we can overwrite default getPointAt -THREE.LineCurve.prototype.getPointAt = function ( u ) { +LineCurve.prototype.getPointAt = function ( u ) { return this.getPoint( u ); }; -THREE.LineCurve.prototype.getTangent = function( t ) { +LineCurve.prototype.getTangent = function( t ) { var tangent = this.v2.clone().sub( this.v1 ); return tangent.normalize(); }; + + +export { LineCurve }; \ No newline at end of file diff --git a/src/extras/curves/LineCurve3.js b/src/extras/curves/LineCurve3.js index 0f6fcd3b88f577..de57a71029f79a 100644 --- a/src/extras/curves/LineCurve3.js +++ b/src/extras/curves/LineCurve3.js @@ -1,8 +1,13 @@ +import { Vector3 } from '../../math/Vector3'; +import { Curve } from '../core/Curve'; + +var LineCurve3; + /************************************************************** * Line3D **************************************************************/ -THREE.LineCurve3 = THREE.Curve.create( +LineCurve3 = Curve.create( function ( v1, v2 ) { @@ -19,7 +24,7 @@ THREE.LineCurve3 = THREE.Curve.create( } - var vector = new THREE.Vector3(); + var vector = new Vector3(); vector.subVectors( this.v2, this.v1 ); // diff vector.multiplyScalar( t ); @@ -30,3 +35,6 @@ THREE.LineCurve3 = THREE.Curve.create( } ); + + +export { LineCurve3 }; \ No newline at end of file diff --git a/src/extras/curves/QuadraticBezierCurve.js b/src/extras/curves/QuadraticBezierCurve.js index b8fc978027c2d9..428ed01cf299d8 100644 --- a/src/extras/curves/QuadraticBezierCurve.js +++ b/src/extras/curves/QuadraticBezierCurve.js @@ -1,9 +1,15 @@ +import { Curve } from '../core/Curve'; +import { Vector2 } from '../../math/Vector2'; +import { CurveUtils } from '../CurveUtils'; +import { ShapeUtils } from '../ShapeUtils'; + /************************************************************** * Quadratic Bezier curve **************************************************************/ -THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { +function QuadraticBezierCurve ( v0, v1, v2 ) { + this.isQuadraticBezierCurve = this.isCurve = true; this.v0 = v0; this.v1 = v1; @@ -11,15 +17,15 @@ THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { }; -THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve; +QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); +QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; -THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { +QuadraticBezierCurve.prototype.getPoint = function ( t ) { - var b2 = THREE.ShapeUtils.b2; + var b2 = ShapeUtils.b2; - return new THREE.Vector2( + return new Vector2( b2( t, this.v0.x, this.v1.x, this.v2.x ), b2( t, this.v0.y, this.v1.y, this.v2.y ) ); @@ -27,13 +33,16 @@ THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { }; -THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) { +QuadraticBezierCurve.prototype.getTangent = function( t ) { - var tangentQuadraticBezier = THREE.CurveUtils.tangentQuadraticBezier; + var tangentQuadraticBezier = CurveUtils.tangentQuadraticBezier; - return new THREE.Vector2( + return new Vector2( tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ), tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ) ).normalize(); }; + + +export { QuadraticBezierCurve }; \ No newline at end of file diff --git a/src/extras/curves/QuadraticBezierCurve3.js b/src/extras/curves/QuadraticBezierCurve3.js index 1bdddd131ea59d..c2a6c72c257a6e 100644 --- a/src/extras/curves/QuadraticBezierCurve3.js +++ b/src/extras/curves/QuadraticBezierCurve3.js @@ -1,8 +1,14 @@ +import { Vector3 } from '../../math/Vector3'; +import { ShapeUtils } from '../ShapeUtils'; +import { Curve } from '../core/Curve'; + +var QuadraticBezierCurve3; + /************************************************************** * Quadratic Bezier 3D curve **************************************************************/ -THREE.QuadraticBezierCurve3 = THREE.Curve.create( +QuadraticBezierCurve3 = Curve.create( function ( v0, v1, v2 ) { @@ -14,9 +20,9 @@ THREE.QuadraticBezierCurve3 = THREE.Curve.create( function ( t ) { - var b2 = THREE.ShapeUtils.b2; + var b2 = ShapeUtils.b2; - return new THREE.Vector3( + return new Vector3( b2( t, this.v0.x, this.v1.x, this.v2.x ), b2( t, this.v0.y, this.v1.y, this.v2.y ), b2( t, this.v0.z, this.v1.z, this.v2.z ) @@ -25,3 +31,6 @@ THREE.QuadraticBezierCurve3 = THREE.Curve.create( } ); + + +export { QuadraticBezierCurve3 }; \ No newline at end of file diff --git a/src/extras/curves/SplineCurve.js b/src/extras/curves/SplineCurve.js index 0a84eaacc1c220..e669be3d153d7b 100644 --- a/src/extras/curves/SplineCurve.js +++ b/src/extras/curves/SplineCurve.js @@ -1,17 +1,22 @@ +import { Curve } from '../core/Curve'; +import { Vector2 } from '../../math/Vector2'; +import { CurveUtils } from '../CurveUtils'; + /************************************************************** * Spline curve **************************************************************/ -THREE.SplineCurve = function ( points /* array of Vector2 */ ) { +function SplineCurve ( points /* array of Vector2 */ ) { + this.isSplineCurve = this.isCurve = true; this.points = ( points == undefined ) ? [] : points; }; -THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.SplineCurve.prototype.constructor = THREE.SplineCurve; +SplineCurve.prototype = Object.create( Curve.prototype ); +SplineCurve.prototype.constructor = SplineCurve; -THREE.SplineCurve.prototype.getPoint = function ( t ) { +SplineCurve.prototype.getPoint = function ( t ) { var points = this.points; var point = ( points.length - 1 ) * t; @@ -24,11 +29,14 @@ THREE.SplineCurve.prototype.getPoint = function ( t ) { var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; - var interpolate = THREE.CurveUtils.interpolate; + var interpolate = CurveUtils.interpolate; - return new THREE.Vector2( + return new Vector2( interpolate( point0.x, point1.x, point2.x, point3.x, weight ), interpolate( point0.y, point1.y, point2.y, point3.y, weight ) ); }; + + +export { SplineCurve }; \ No newline at end of file diff --git a/src/extras/curves/SplineCurve3.js b/src/extras/curves/SplineCurve3.js index 1782fcfba40e6b..957780f6777a32 100644 --- a/src/extras/curves/SplineCurve3.js +++ b/src/extras/curves/SplineCurve3.js @@ -1,9 +1,15 @@ +import { Vector3 } from '../../math/Vector3'; +import { CurveUtils } from '../CurveUtils'; +import { Curve } from '../core/Curve'; + +var SplineCurve3; + /************************************************************** * Spline 3D curve **************************************************************/ -THREE.SplineCurve3 = THREE.Curve.create( +SplineCurve3 = Curve.create( function ( points /* array of Vector3 */ ) { @@ -25,9 +31,9 @@ THREE.SplineCurve3 = THREE.Curve.create( var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; - var interpolate = THREE.CurveUtils.interpolate; + var interpolate = CurveUtils.interpolate; - return new THREE.Vector3( + return new Vector3( interpolate( point0.x, point1.x, point2.x, point3.x, weight ), interpolate( point0.y, point1.y, point2.y, point3.y, weight ), interpolate( point0.z, point1.z, point2.z, point3.z, weight ) @@ -36,3 +42,6 @@ THREE.SplineCurve3 = THREE.Curve.create( } ); + + +export { SplineCurve3 }; \ No newline at end of file diff --git a/src/extras/geometries/BoxBufferGeometry.js b/src/extras/geometries/BoxBufferGeometry.js index 46459ba73a9244..f3203a4e165ba9 100644 --- a/src/extras/geometries/BoxBufferGeometry.js +++ b/src/extras/geometries/BoxBufferGeometry.js @@ -1,10 +1,15 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author Mugen87 / https://github.com/Mugen87 */ -THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { +function BoxBufferGeometry ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + this.isBoxBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'BoxBufferGeometry'; @@ -52,10 +57,10 @@ THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, height buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz // build geometry - this.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); // helper functions @@ -100,7 +105,7 @@ THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, height var vertexCounter = 0; var groupCount = 0; - var vector = new THREE.Vector3(); + var vector = new Vector3(); // generate vertices, normals and uvs @@ -190,5 +195,8 @@ THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, height }; -THREE.BoxBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.BoxBufferGeometry.prototype.constructor = THREE.BoxBufferGeometry; +BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; + + +export { BoxBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/BoxGeometry.js b/src/extras/geometries/BoxGeometry.js index 12a69b86305856..b91f355f6ebe3a 100644 --- a/src/extras/geometries/BoxGeometry.js +++ b/src/extras/geometries/BoxGeometry.js @@ -1,11 +1,17 @@ +import { Geometry } from '../../core/Geometry'; +import { BoxBufferGeometry } from './BoxBufferGeometry'; + +var CubeGeometry; + /** * @author mrdoob / http://mrdoob.com/ * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as */ -THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { +function BoxGeometry ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + this.isBoxGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'BoxGeometry'; @@ -18,12 +24,15 @@ THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegmen depthSegments: depthSegments }; - this.fromBufferGeometry( new THREE.BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); + this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); this.mergeVertices(); }; -THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry; +BoxGeometry.prototype = Object.create( Geometry.prototype ); +BoxGeometry.prototype.constructor = BoxGeometry; + +CubeGeometry = BoxGeometry; + -THREE.CubeGeometry = THREE.BoxGeometry; +export { CubeGeometry, BoxGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/CircleBufferGeometry.js b/src/extras/geometries/CircleBufferGeometry.js index f5b2f8b6701215..49835afdadea4c 100644 --- a/src/extras/geometries/CircleBufferGeometry.js +++ b/src/extras/geometries/CircleBufferGeometry.js @@ -1,10 +1,16 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { Sphere } from '../../math/Sphere'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) { +function CircleBufferGeometry ( radius, segments, thetaStart, thetaLength ) { + this.isCircleBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'CircleBufferGeometry'; @@ -54,14 +60,17 @@ THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLengt } - this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + this.boundingSphere = new Sphere( new Vector3(), radius ); }; -THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry; +CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; + + +export { CircleBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/CircleGeometry.js b/src/extras/geometries/CircleGeometry.js index 10e64731a763f4..620df514c8f005 100644 --- a/src/extras/geometries/CircleGeometry.js +++ b/src/extras/geometries/CircleGeometry.js @@ -1,10 +1,14 @@ +import { Geometry } from '../../core/Geometry'; +import { CircleBufferGeometry } from './CircleBufferGeometry'; + /** * @author hughes */ -THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) { +function CircleGeometry ( radius, segments, thetaStart, thetaLength ) { + this.isCircleGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'CircleGeometry'; @@ -15,9 +19,12 @@ THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) { thetaLength: thetaLength }; - this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); + this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); }; -THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry; +CircleGeometry.prototype = Object.create( Geometry.prototype ); +CircleGeometry.prototype.constructor = CircleGeometry; + + +export { CircleGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/ConeBufferGeometry.js b/src/extras/geometries/ConeBufferGeometry.js index 8a1334e0df1c44..51680a499e9be4 100644 --- a/src/extras/geometries/ConeBufferGeometry.js +++ b/src/extras/geometries/ConeBufferGeometry.js @@ -1,13 +1,17 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { CylinderBufferGeometry } from './CylinderBufferGeometry'; + /* * @author: abelnation / http://github.com/abelnation */ -THREE.ConeBufferGeometry = function ( +function ConeBufferGeometry ( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isConeBufferGeometry = this.isBufferGeometry = true; - THREE.CylinderBufferGeometry.call( this, + CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); @@ -25,5 +29,8 @@ THREE.ConeBufferGeometry = function ( }; -THREE.ConeBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.ConeBufferGeometry.prototype.constructor = THREE.ConeBufferGeometry; +ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; + + +export { ConeBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/ConeGeometry.js b/src/extras/geometries/ConeGeometry.js index 12b52bb8ae6435..8c3f7f7ce3ea06 100644 --- a/src/extras/geometries/ConeGeometry.js +++ b/src/extras/geometries/ConeGeometry.js @@ -1,13 +1,16 @@ +import { CylinderGeometry } from './CylinderGeometry'; + /** * @author abelnation / http://github.com/abelnation */ -THREE.ConeGeometry = function ( +function ConeGeometry ( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isConeGeometry = this.isCylinderGeometry = this.isGeometry = true; - THREE.CylinderGeometry.call( this, + CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); @@ -26,5 +29,8 @@ THREE.ConeGeometry = function ( }; -THREE.ConeGeometry.prototype = Object.create( THREE.CylinderGeometry.prototype ); -THREE.ConeGeometry.prototype.constructor = THREE.ConeGeometry; +ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); +ConeGeometry.prototype.constructor = ConeGeometry; + + +export { ConeGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/CylinderBufferGeometry.js b/src/extras/geometries/CylinderBufferGeometry.js index 4664ee615d7c3d..fed02359a25422 100644 --- a/src/extras/geometries/CylinderBufferGeometry.js +++ b/src/extras/geometries/CylinderBufferGeometry.js @@ -1,10 +1,16 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { Vector2 } from '../../math/Vector2'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author Mugen87 / https://github.com/Mugen87 */ -THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { +function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isCylinderBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'CylinderBufferGeometry'; @@ -48,10 +54,10 @@ THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radial // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); // helper variables @@ -114,8 +120,8 @@ THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radial function generateTorso() { var x, y; - var normal = new THREE.Vector3(); - var vertex = new THREE.Vector3(); + var normal = new Vector3(); + var vertex = new Vector3(); var groupCount = 0; @@ -215,8 +221,8 @@ THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radial var x, centerIndexStart, centerIndexEnd; - var uv = new THREE.Vector2(); - var vertex = new THREE.Vector3(); + var uv = new Vector2(); + var vertex = new Vector3(); var groupCount = 0; @@ -319,5 +325,8 @@ THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radial }; -THREE.CylinderBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.CylinderBufferGeometry.prototype.constructor = THREE.CylinderBufferGeometry; +CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; + + +export { CylinderBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/CylinderGeometry.js b/src/extras/geometries/CylinderGeometry.js index 83bfbd42d3b6c1..a0c2de767d2739 100644 --- a/src/extras/geometries/CylinderGeometry.js +++ b/src/extras/geometries/CylinderGeometry.js @@ -1,10 +1,14 @@ +import { Geometry } from '../../core/Geometry'; +import { CylinderBufferGeometry } from './CylinderBufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { +function CylinderGeometry ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isCylinderGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'CylinderGeometry'; @@ -19,10 +23,13 @@ THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegme thetaLength: thetaLength }; - this.fromBufferGeometry( new THREE.CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); + this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); this.mergeVertices(); }; -THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry; +CylinderGeometry.prototype = Object.create( Geometry.prototype ); +CylinderGeometry.prototype.constructor = CylinderGeometry; + + +export { CylinderGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/DodecahedronGeometry.js b/src/extras/geometries/DodecahedronGeometry.js index 0c540cd465ca5e..ac270d5902aead 100644 --- a/src/extras/geometries/DodecahedronGeometry.js +++ b/src/extras/geometries/DodecahedronGeometry.js @@ -1,8 +1,11 @@ +import { PolyhedronGeometry } from './PolyhedronGeometry'; + /** * @author Abe Pazos / https://hamoid.com */ -THREE.DodecahedronGeometry = function ( radius, detail ) { +function DodecahedronGeometry ( radius, detail ) { + this.isDodecahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; var t = ( 1 + Math.sqrt( 5 ) ) / 2; var r = 1 / t; @@ -43,7 +46,7 @@ THREE.DodecahedronGeometry = function ( radius, detail ) { 1, 12, 14, 1, 14, 5, 1, 5, 9 ]; - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); this.type = 'DodecahedronGeometry'; @@ -54,5 +57,8 @@ THREE.DodecahedronGeometry = function ( radius, detail ) { }; -THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry; +DodecahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); +DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; + + +export { DodecahedronGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/EdgesGeometry.js b/src/extras/geometries/EdgesGeometry.js index 7515bce8413ed1..937854fdd049ea 100644 --- a/src/extras/geometries/EdgesGeometry.js +++ b/src/extras/geometries/EdgesGeometry.js @@ -1,14 +1,20 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { BufferAttribute } from '../../core/BufferAttribute'; +import { Geometry } from '../../core/Geometry'; +import { _Math } from '../../math/Math'; + /** * @author WestLangley / http://github.com/WestLangley */ -THREE.EdgesGeometry = function ( geometry, thresholdAngle ) { +function EdgesGeometry ( geometry, thresholdAngle ) { + this.isEdgesGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; - var thresholdDot = Math.cos( THREE.Math.DEG2RAD * thresholdAngle ); + var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle ); var edge = [ 0, 0 ], hash = {}; @@ -22,9 +28,9 @@ THREE.EdgesGeometry = function ( geometry, thresholdAngle ) { var geometry2; - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { - geometry2 = new THREE.Geometry(); + geometry2 = new Geometry(); geometry2.fromBufferGeometry( geometry ); } else { @@ -87,9 +93,12 @@ THREE.EdgesGeometry = function ( geometry, thresholdAngle ) { } - this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) ); + this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) ); }; -THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry; +EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); +EdgesGeometry.prototype.constructor = EdgesGeometry; + + +export { EdgesGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/ExtrudeGeometry.js b/src/extras/geometries/ExtrudeGeometry.js index ce4a6a3cd192ba..c7be71da812bd0 100644 --- a/src/extras/geometries/ExtrudeGeometry.js +++ b/src/extras/geometries/ExtrudeGeometry.js @@ -1,3 +1,10 @@ +import { Geometry } from '../../core/Geometry'; +import { Vector2 } from '../../math/Vector2'; +import { Face3 } from '../../core/Face3'; +import { Vector3 } from '../../math/Vector3'; +import { ShapeUtils } from '../ShapeUtils'; +import { TubeGeometry } from './TubeGeometry'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * @@ -22,7 +29,8 @@ * } **/ -THREE.ExtrudeGeometry = function ( shapes, options ) { +function ExtrudeGeometry ( shapes, options ) { + this.isExtrudeGeometry = this.isGeometry = true; if ( typeof( shapes ) === "undefined" ) { @@ -31,7 +39,7 @@ THREE.ExtrudeGeometry = function ( shapes, options ) { } - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'ExtrudeGeometry'; @@ -51,10 +59,10 @@ THREE.ExtrudeGeometry = function ( shapes, options ) { }; -THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry; +ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); +ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; -THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { +ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { var sl = shapes.length; @@ -67,7 +75,7 @@ THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { }; -THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { +ExtrudeGeometry.prototype.addShape = function ( shape, options ) { var amount = options.amount !== undefined ? options.amount : 100; @@ -85,7 +93,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { var extrudePts, extrudeByPath = false; // Use default WorldUVGenerator if no UV generators are specified. - var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator; + var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator; var splineTube, binormal, normal, position2; if ( extrudePath ) { @@ -100,13 +108,13 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { // Reuse TNB from TubeGeomtry for now. // TODO1 - have a .isClosed in spline? - splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false ); + splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false ); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - binormal = new THREE.Vector3(); - normal = new THREE.Vector3(); - position2 = new THREE.Vector3(); + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); } @@ -132,7 +140,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { var vertices = shapePoints.shape; var holes = shapePoints.holes; - var reverse = ! THREE.ShapeUtils.isClockWise( vertices ); + var reverse = ! ShapeUtils.isClockWise( vertices ); if ( reverse ) { @@ -144,7 +152,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { ahole = holes[ h ]; - if ( THREE.ShapeUtils.isClockWise( ahole ) ) { + if ( ShapeUtils.isClockWise( ahole ) ) { holes[ h ] = ahole.reverse(); @@ -157,7 +165,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { } - var faces = THREE.ShapeUtils.triangulateShape( vertices, holes ); + var faces = ShapeUtils.triangulateShape( vertices, holes ); /* Vertices */ @@ -243,7 +251,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); if ( v_trans_lensq <= 2 ) { - return new THREE.Vector2( v_trans_x, v_trans_y ); + return new Vector2( v_trans_x, v_trans_y ); } else { @@ -304,7 +312,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { } - return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); } @@ -616,7 +624,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { function v( x, y, z ) { - scope.vertices.push( new THREE.Vector3( x, y, z ) ); + scope.vertices.push( new Vector3( x, y, z ) ); } @@ -626,7 +634,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { b += shapesOffset; c += shapesOffset; - scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) ); + scope.faces.push( new Face3( a, b, c, null, null, 0 ) ); var uvs = uvgen.generateTopUV( scope, a, b, c ); @@ -641,8 +649,8 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { c += shapesOffset; d += shapesOffset; - scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) ); - scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) ); + scope.faces.push( new Face3( a, b, d, null, null, 1 ) ); + scope.faces.push( new Face3( b, c, d, null, null, 1 ) ); var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); @@ -653,7 +661,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { }; -THREE.ExtrudeGeometry.WorldUVGenerator = { +ExtrudeGeometry.WorldUVGenerator = { generateTopUV: function ( geometry, indexA, indexB, indexC ) { @@ -664,9 +672,9 @@ THREE.ExtrudeGeometry.WorldUVGenerator = { var c = vertices[ indexC ]; return [ - new THREE.Vector2( a.x, a.y ), - new THREE.Vector2( b.x, b.y ), - new THREE.Vector2( c.x, c.y ) + new Vector2( a.x, a.y ), + new Vector2( b.x, b.y ), + new Vector2( c.x, c.y ) ]; }, @@ -683,22 +691,25 @@ THREE.ExtrudeGeometry.WorldUVGenerator = { if ( Math.abs( a.y - b.y ) < 0.01 ) { return [ - new THREE.Vector2( a.x, 1 - a.z ), - new THREE.Vector2( b.x, 1 - b.z ), - new THREE.Vector2( c.x, 1 - c.z ), - new THREE.Vector2( d.x, 1 - d.z ) + new Vector2( a.x, 1 - a.z ), + new Vector2( b.x, 1 - b.z ), + new Vector2( c.x, 1 - c.z ), + new Vector2( d.x, 1 - d.z ) ]; } else { return [ - new THREE.Vector2( a.y, 1 - a.z ), - new THREE.Vector2( b.y, 1 - b.z ), - new THREE.Vector2( c.y, 1 - c.z ), - new THREE.Vector2( d.y, 1 - d.z ) + new Vector2( a.y, 1 - a.z ), + new Vector2( b.y, 1 - b.z ), + new Vector2( c.y, 1 - c.z ), + new Vector2( d.y, 1 - d.z ) ]; } } }; + + +export { ExtrudeGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/IcosahedronGeometry.js b/src/extras/geometries/IcosahedronGeometry.js index c562c626bdaf8e..587e743dd2e79f 100644 --- a/src/extras/geometries/IcosahedronGeometry.js +++ b/src/extras/geometries/IcosahedronGeometry.js @@ -1,8 +1,11 @@ +import { PolyhedronGeometry } from './PolyhedronGeometry'; + /** * @author timothypratley / https://github.com/timothypratley */ -THREE.IcosahedronGeometry = function ( radius, detail ) { +function IcosahedronGeometry ( radius, detail ) { + this.isIcosahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; var t = ( 1 + Math.sqrt( 5 ) ) / 2; @@ -19,7 +22,7 @@ THREE.IcosahedronGeometry = function ( radius, detail ) { 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 ]; - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); this.type = 'IcosahedronGeometry'; @@ -30,5 +33,8 @@ THREE.IcosahedronGeometry = function ( radius, detail ) { }; -THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry; +IcosahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); +IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; + + +export { IcosahedronGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/LatheBufferGeometry.js b/src/extras/geometries/LatheBufferGeometry.js index a7353ced5544a4..fb936b01fca0cb 100644 --- a/src/extras/geometries/LatheBufferGeometry.js +++ b/src/extras/geometries/LatheBufferGeometry.js @@ -1,3 +1,9 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { Vector2 } from '../../math/Vector2'; +import { BufferAttribute } from '../../core/BufferAttribute'; +import { _Math } from '../../math/Math'; + /** * @author Mugen87 / https://github.com/Mugen87 */ @@ -9,9 +15,10 @@ // phiLength - the radian (0 to 2PI) range of the lathed section // 2PI is a closed lathe, less than 2PI is a portion. -THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) { +function LatheBufferGeometry ( points, segments, phiStart, phiLength ) { + this.isLatheBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'LatheBufferGeometry'; @@ -27,23 +34,23 @@ THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) { phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ] - phiLength = THREE.Math.clamp( phiLength, 0, Math.PI * 2 ); + phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 ); // these are used to calculate buffer length var vertexCount = ( segments + 1 ) * points.length; var indexCount = segments * points.length * 2 * 3; // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); // helper variables var index = 0, indexOffset = 0, base; var inversePointLength = 1.0 / ( points.length - 1 ); var inverseSegments = 1.0 / segments; - var vertex = new THREE.Vector3(); - var uv = new THREE.Vector2(); + var vertex = new Vector3(); + var uv = new Vector2(); var i, j; // generate vertices and uvs @@ -119,9 +126,9 @@ THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) { if( phiLength === Math.PI * 2 ) { var normals = this.attributes.normal.array; - var n1 = new THREE.Vector3(); - var n2 = new THREE.Vector3(); - var n = new THREE.Vector3(); + var n1 = new Vector3(); + var n2 = new Vector3(); + var n = new Vector3(); // this is the buffer offset for the last line of vertices base = segments * points.length * 3; @@ -152,5 +159,8 @@ THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) { }; -THREE.LatheBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.LatheBufferGeometry.prototype.constructor = THREE.LatheBufferGeometry; +LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; + + +export { LatheBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/LatheGeometry.js b/src/extras/geometries/LatheGeometry.js index 5e46d75b35e204..3146acb8418728 100644 --- a/src/extras/geometries/LatheGeometry.js +++ b/src/extras/geometries/LatheGeometry.js @@ -1,3 +1,6 @@ +import { Geometry } from '../../core/Geometry'; +import { LatheBufferGeometry } from './LatheBufferGeometry'; + /** * @author astrodud / http://astrodud.isgreat.org/ * @author zz85 / https://github.com/zz85 @@ -11,9 +14,10 @@ // phiLength - the radian (0 to 2PI) range of the lathed section // 2PI is a closed lathe, less than 2PI is a portion. -THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) { +function LatheGeometry ( points, segments, phiStart, phiLength ) { + this.isLatheGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'LatheGeometry'; @@ -24,10 +28,13 @@ THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) { phiLength: phiLength }; - this.fromBufferGeometry( new THREE.LatheBufferGeometry( points, segments, phiStart, phiLength ) ); + this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); this.mergeVertices(); }; -THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry; +LatheGeometry.prototype = Object.create( Geometry.prototype ); +LatheGeometry.prototype.constructor = LatheGeometry; + + +export { LatheGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/OctahedronGeometry.js b/src/extras/geometries/OctahedronGeometry.js index 491aa8b8a286c1..b38c0c8e8d7110 100644 --- a/src/extras/geometries/OctahedronGeometry.js +++ b/src/extras/geometries/OctahedronGeometry.js @@ -1,8 +1,11 @@ +import { PolyhedronGeometry } from './PolyhedronGeometry'; + /** * @author timothypratley / https://github.com/timothypratley */ -THREE.OctahedronGeometry = function ( radius, detail ) { +function OctahedronGeometry ( radius, detail ) { + this.isOctahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; var vertices = [ 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1 @@ -12,7 +15,7 @@ THREE.OctahedronGeometry = function ( radius, detail ) { 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 ]; - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); this.type = 'OctahedronGeometry'; @@ -23,5 +26,8 @@ THREE.OctahedronGeometry = function ( radius, detail ) { }; -THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry; +OctahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); +OctahedronGeometry.prototype.constructor = OctahedronGeometry; + + +export { OctahedronGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/ParametricGeometry.js b/src/extras/geometries/ParametricGeometry.js index 23b886b0ee148e..0eacf32b94c498 100644 --- a/src/extras/geometries/ParametricGeometry.js +++ b/src/extras/geometries/ParametricGeometry.js @@ -1,3 +1,7 @@ +import { Geometry } from '../../core/Geometry'; +import { Face3 } from '../../core/Face3'; +import { Vector2 } from '../../math/Vector2'; + /** * @author zz85 / https://github.com/zz85 * Parametric Surfaces Geometry @@ -7,9 +11,10 @@ * */ -THREE.ParametricGeometry = function ( func, slices, stacks ) { +function ParametricGeometry ( func, slices, stacks ) { + this.isParametricGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'ParametricGeometry'; @@ -55,15 +60,15 @@ THREE.ParametricGeometry = function ( func, slices, stacks ) { c = ( i + 1 ) * sliceCount + j + 1; d = ( i + 1 ) * sliceCount + j; - uva = new THREE.Vector2( j / slices, i / stacks ); - uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks ); - uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); - uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks ); + uva = new Vector2( j / slices, i / stacks ); + uvb = new Vector2( ( j + 1 ) / slices, i / stacks ); + uvc = new Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); + uvd = new Vector2( j / slices, ( i + 1 ) / stacks ); - faces.push( new THREE.Face3( a, b, d ) ); + faces.push( new Face3( a, b, d ) ); uvs.push( [ uva, uvb, uvd ] ); - faces.push( new THREE.Face3( b, c, d ) ); + faces.push( new Face3( b, c, d ) ); uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); } @@ -81,5 +86,8 @@ THREE.ParametricGeometry = function ( func, slices, stacks ) { }; -THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry; +ParametricGeometry.prototype = Object.create( Geometry.prototype ); +ParametricGeometry.prototype.constructor = ParametricGeometry; + + +export { ParametricGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/PlaneBufferGeometry.js b/src/extras/geometries/PlaneBufferGeometry.js index 132d021983aaca..f2b185c7bc03af 100644 --- a/src/extras/geometries/PlaneBufferGeometry.js +++ b/src/extras/geometries/PlaneBufferGeometry.js @@ -1,11 +1,15 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author mrdoob / http://mrdoob.com/ * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as */ -THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) { +function PlaneBufferGeometry ( width, height, widthSegments, heightSegments ) { + this.isPlaneBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'PlaneBufferGeometry'; @@ -85,12 +89,15 @@ THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegme } - this.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); }; -THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry; +PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; + + +export { PlaneBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/PlaneGeometry.js b/src/extras/geometries/PlaneGeometry.js index c8698ba095d7df..af5f75a1fe1666 100644 --- a/src/extras/geometries/PlaneGeometry.js +++ b/src/extras/geometries/PlaneGeometry.js @@ -1,11 +1,15 @@ +import { Geometry } from '../../core/Geometry'; +import { PlaneBufferGeometry } from './PlaneBufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as */ -THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) { +function PlaneGeometry ( width, height, widthSegments, heightSegments ) { + this.isPlaneGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'PlaneGeometry'; @@ -16,9 +20,12 @@ THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) heightSegments: heightSegments }; - this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); + this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); }; -THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry; +PlaneGeometry.prototype = Object.create( Geometry.prototype ); +PlaneGeometry.prototype.constructor = PlaneGeometry; + + +export { PlaneGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/PolyhedronGeometry.js b/src/extras/geometries/PolyhedronGeometry.js index 47c1a1e7b7d437..c6c2f1f706d02f 100644 --- a/src/extras/geometries/PolyhedronGeometry.js +++ b/src/extras/geometries/PolyhedronGeometry.js @@ -1,12 +1,19 @@ +import { Geometry } from '../../core/Geometry'; +import { Vector2 } from '../../math/Vector2'; +import { Face3 } from '../../core/Face3'; +import { Vector3 } from '../../math/Vector3'; +import { Sphere } from '../../math/Sphere'; + /** * @author clockworkgeek / https://github.com/clockworkgeek * @author timothypratley / https://github.com/timothypratley * @author WestLangley / http://github.com/WestLangley */ -THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { +function PolyhedronGeometry ( vertices, indices, radius, detail ) { + this.isPolyhedronGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'PolyhedronGeometry'; @@ -24,7 +31,7 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { for ( var i = 0, l = vertices.length; i < l; i += 3 ) { - prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); + prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); } @@ -38,11 +45,11 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { var v2 = p[ indices[ i + 1 ] ]; var v3 = p[ indices[ i + 2 ] ]; - faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); + faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); } - var centroid = new THREE.Vector3(); + var centroid = new Vector3(); for ( var i = 0, l = faces.length; i < l; i ++ ) { @@ -92,7 +99,7 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { this.computeFaceNormals(); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + this.boundingSphere = new Sphere( new Vector3(), radius ); // Project vector onto sphere's surface @@ -106,7 +113,7 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { var u = azimuth( vector ) / 2 / Math.PI + 0.5; var v = inclination( vector ) / Math.PI + 0.5; - vertex.uv = new THREE.Vector2( u, 1 - v ); + vertex.uv = new Vector2( u, 1 - v ); return vertex; @@ -117,7 +124,7 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { function make( v1, v2, v3 ) { - var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); + var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); that.faces.push( face ); centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); @@ -224,8 +231,8 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { function correctUV( uv, vector, azimuth ) { - if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y ); - if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y ); + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new Vector2( uv.x - 1, uv.y ); + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new Vector2( azimuth / 2 / Math.PI + 0.5, uv.y ); return uv.clone(); } @@ -233,5 +240,8 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { }; -THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry; +PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); +PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; + + +export { PolyhedronGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/RingBufferGeometry.js b/src/extras/geometries/RingBufferGeometry.js index 33a5115dbb7ed9..d9d448457503f5 100644 --- a/src/extras/geometries/RingBufferGeometry.js +++ b/src/extras/geometries/RingBufferGeometry.js @@ -1,10 +1,16 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector2 } from '../../math/Vector2'; +import { Vector3 } from '../../math/Vector3'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author Mugen87 / https://github.com/Mugen87 */ -THREE.RingBufferGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { +function RingBufferGeometry ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + this.isRingBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'RingBufferGeometry'; @@ -31,17 +37,17 @@ THREE.RingBufferGeometry = function ( innerRadius, outerRadius, thetaSegments, p var indexCount = thetaSegments * phiSegments * 2 * 3; // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); // some helper variables var index = 0, indexOffset = 0, segment; var radius = innerRadius; var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - var vertex = new THREE.Vector3(); - var uv = new THREE.Vector2(); + var vertex = new Vector3(); + var uv = new Vector2(); var j, i; // generate vertices, normals and uvs @@ -116,5 +122,8 @@ THREE.RingBufferGeometry = function ( innerRadius, outerRadius, thetaSegments, p }; -THREE.RingBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.RingBufferGeometry.prototype.constructor = THREE.RingBufferGeometry; +RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +RingBufferGeometry.prototype.constructor = RingBufferGeometry; + + +export { RingBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/RingGeometry.js b/src/extras/geometries/RingGeometry.js index f3304f7740c3c7..9705e08e278c57 100644 --- a/src/extras/geometries/RingGeometry.js +++ b/src/extras/geometries/RingGeometry.js @@ -1,10 +1,14 @@ +import { Geometry } from '../../core/Geometry'; +import { RingBufferGeometry } from './RingBufferGeometry'; + /** * @author Kaleb Murphy */ -THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { +function RingGeometry ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + this.isRingGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'RingGeometry'; @@ -17,9 +21,12 @@ THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegm thetaLength: thetaLength }; - this.fromBufferGeometry( new THREE.RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); + this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); }; -THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.RingGeometry.prototype.constructor = THREE.RingGeometry; +RingGeometry.prototype = Object.create( Geometry.prototype ); +RingGeometry.prototype.constructor = RingGeometry; + + +export { RingGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/ShapeGeometry.js b/src/extras/geometries/ShapeGeometry.js index f9989695f4ebcd..f7fcb54de321ac 100644 --- a/src/extras/geometries/ShapeGeometry.js +++ b/src/extras/geometries/ShapeGeometry.js @@ -1,3 +1,9 @@ +import { Geometry } from '../../core/Geometry'; +import { Face3 } from '../../core/Face3'; +import { Vector3 } from '../../math/Vector3'; +import { ShapeUtils } from '../ShapeUtils'; +import { ExtrudeGeometry } from './ExtrudeGeometry'; + /** * @author jonobr1 / http://jonobr1.com * @@ -14,9 +20,10 @@ * } **/ -THREE.ShapeGeometry = function ( shapes, options ) { +function ShapeGeometry ( shapes, options ) { + this.isShapeGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'ShapeGeometry'; @@ -28,13 +35,13 @@ THREE.ShapeGeometry = function ( shapes, options ) { }; -THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry; +ShapeGeometry.prototype = Object.create( Geometry.prototype ); +ShapeGeometry.prototype.constructor = ShapeGeometry; /** * Add an array of shapes to THREE.ShapeGeometry. */ -THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { +ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { for ( var i = 0, l = shapes.length; i < l; i ++ ) { @@ -49,13 +56,13 @@ THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { /** * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. */ -THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { +ShapeGeometry.prototype.addShape = function ( shape, options ) { if ( options === undefined ) options = {}; var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; var material = options.material; - var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; + var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; // @@ -67,7 +74,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { var vertices = shapePoints.shape; var holes = shapePoints.holes; - var reverse = ! THREE.ShapeUtils.isClockWise( vertices ); + var reverse = ! ShapeUtils.isClockWise( vertices ); if ( reverse ) { @@ -79,7 +86,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { hole = holes[ i ]; - if ( THREE.ShapeUtils.isClockWise( hole ) ) { + if ( ShapeUtils.isClockWise( hole ) ) { holes[ i ] = hole.reverse(); @@ -91,7 +98,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { } - var faces = THREE.ShapeUtils.triangulateShape( vertices, holes ); + var faces = ShapeUtils.triangulateShape( vertices, holes ); // Vertices @@ -111,7 +118,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { vert = vertices[ i ]; - this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) ); + this.vertices.push( new Vector3( vert.x, vert.y, 0 ) ); } @@ -123,9 +130,12 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { var b = face[ 1 ] + shapesOffset; var c = face[ 2 ] + shapesOffset; - this.faces.push( new THREE.Face3( a, b, c, null, null, material ) ); + this.faces.push( new Face3( a, b, c, null, null, material ) ); this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); } }; + + +export { ShapeGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/SphereBufferGeometry.js b/src/extras/geometries/SphereBufferGeometry.js index e95a0e30ada1fa..d4cb6914f659bc 100644 --- a/src/extras/geometries/SphereBufferGeometry.js +++ b/src/extras/geometries/SphereBufferGeometry.js @@ -1,11 +1,17 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { Sphere } from '../../math/Sphere'; +import { Uint16Attribute, Uint32Attribute, BufferAttribute } from '../../core/BufferAttribute'; + /** * @author benaadams / https://twitter.com/ben_a_adams * based on THREE.SphereGeometry */ -THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { +function SphereBufferGeometry ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + this.isSphereBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'SphereBufferGeometry'; @@ -34,11 +40,11 @@ THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, p var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) ); - var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - var index = 0, vertices = [], normal = new THREE.Vector3(); + var index = 0, vertices = [], normal = new Vector3(); for ( var y = 0; y <= heightSegments; y ++ ) { @@ -88,14 +94,17 @@ THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, p } - this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) ); + this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) ); this.addAttribute( 'position', positions ); this.addAttribute( 'normal', normals ); this.addAttribute( 'uv', uvs ); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + this.boundingSphere = new Sphere( new Vector3(), radius ); }; -THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry; +SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; + + +export { SphereBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/SphereGeometry.js b/src/extras/geometries/SphereGeometry.js index c48de23561cacf..96d58123da6007 100644 --- a/src/extras/geometries/SphereGeometry.js +++ b/src/extras/geometries/SphereGeometry.js @@ -1,10 +1,14 @@ +import { Geometry } from '../../core/Geometry'; +import { SphereBufferGeometry } from './SphereBufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { +function SphereGeometry ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + this.isSphereGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'SphereGeometry'; @@ -18,9 +22,12 @@ THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStar thetaLength: thetaLength }; - this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); + this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); }; -THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry; +SphereGeometry.prototype = Object.create( Geometry.prototype ); +SphereGeometry.prototype.constructor = SphereGeometry; + + +export { SphereGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TetrahedronGeometry.js b/src/extras/geometries/TetrahedronGeometry.js index cf3fad8a723a54..efa5093c666ab7 100644 --- a/src/extras/geometries/TetrahedronGeometry.js +++ b/src/extras/geometries/TetrahedronGeometry.js @@ -1,8 +1,11 @@ +import { PolyhedronGeometry } from './PolyhedronGeometry'; + /** * @author timothypratley / https://github.com/timothypratley */ -THREE.TetrahedronGeometry = function ( radius, detail ) { +function TetrahedronGeometry ( radius, detail ) { + this.isTetrahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; var vertices = [ 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 @@ -12,7 +15,7 @@ THREE.TetrahedronGeometry = function ( radius, detail ) { 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 ]; - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); this.type = 'TetrahedronGeometry'; @@ -23,5 +26,8 @@ THREE.TetrahedronGeometry = function ( radius, detail ) { }; -THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry; +TetrahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); +TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; + + +export { TetrahedronGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TextGeometry.js b/src/extras/geometries/TextGeometry.js index 049166f3e844a6..50664fb9fa0777 100644 --- a/src/extras/geometries/TextGeometry.js +++ b/src/extras/geometries/TextGeometry.js @@ -1,3 +1,6 @@ +import { ExtrudeGeometry } from './ExtrudeGeometry'; +import { Geometry } from '../../core/Geometry'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * @author alteredq / http://alteredqualia.com/ @@ -17,16 +20,17 @@ * } */ -THREE.TextGeometry = function ( text, parameters ) { +function TextGeometry ( text, parameters ) { + this.isTextGeometry = this.isExtrudeGeometry = this.isGeometry = true; parameters = parameters || {}; var font = parameters.font; - if ( font instanceof THREE.Font === false ) { + if ( (font && font.isFont) === false ) { console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); - return new THREE.Geometry(); + return new Geometry(); } @@ -42,11 +46,14 @@ THREE.TextGeometry = function ( text, parameters ) { if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; - THREE.ExtrudeGeometry.call( this, shapes, parameters ); + ExtrudeGeometry.call( this, shapes, parameters ); this.type = 'TextGeometry'; }; -THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype ); -THREE.TextGeometry.prototype.constructor = THREE.TextGeometry; +TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype ); +TextGeometry.prototype.constructor = TextGeometry; + + +export { TextGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TorusBufferGeometry.js b/src/extras/geometries/TorusBufferGeometry.js index 5c55aebc52636a..833bec1d884b40 100644 --- a/src/extras/geometries/TorusBufferGeometry.js +++ b/src/extras/geometries/TorusBufferGeometry.js @@ -1,10 +1,15 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { BufferAttribute } from '../../core/BufferAttribute'; +import { Vector3 } from '../../math/Vector3'; + /** * @author Mugen87 / https://github.com/Mugen87 */ -THREE.TorusBufferGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) { +function TorusBufferGeometry ( radius, tube, radialSegments, tubularSegments, arc ) { + this.isTorusBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'TorusBufferGeometry'; @@ -38,9 +43,9 @@ THREE.TorusBufferGeometry = function ( radius, tube, radialSegments, tubularSegm var indexBufferOffset = 0; // helper variables - var center = new THREE.Vector3(); - var vertex = new THREE.Vector3(); - var normal = new THREE.Vector3(); + var center = new Vector3(); + var vertex = new Vector3(); + var normal = new Vector3(); var j, i; @@ -115,12 +120,15 @@ THREE.TorusBufferGeometry = function ( radius, tube, radialSegments, tubularSegm } // build geometry - this.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); }; -THREE.TorusBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.TorusBufferGeometry.prototype.constructor = THREE.TorusBufferGeometry; +TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; + + +export { TorusBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TorusGeometry.js b/src/extras/geometries/TorusGeometry.js index adf567027c9b11..1d126a20396ef4 100644 --- a/src/extras/geometries/TorusGeometry.js +++ b/src/extras/geometries/TorusGeometry.js @@ -1,12 +1,16 @@ +import { Geometry } from '../../core/Geometry'; +import { TorusBufferGeometry } from './TorusBufferGeometry'; + /** * @author oosmoxiecode * @author mrdoob / http://mrdoob.com/ * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888 */ -THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) { +function TorusGeometry ( radius, tube, radialSegments, tubularSegments, arc ) { + this.isTorusGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'TorusGeometry'; @@ -18,9 +22,12 @@ THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc: arc }; - this.fromBufferGeometry( new THREE.TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); + this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); }; -THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry; +TorusGeometry.prototype = Object.create( Geometry.prototype ); +TorusGeometry.prototype.constructor = TorusGeometry; + + +export { TorusGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TorusKnotBufferGeometry.js b/src/extras/geometries/TorusKnotBufferGeometry.js index 49245daec75c2e..e3e0cdb15ae05f 100644 --- a/src/extras/geometries/TorusKnotBufferGeometry.js +++ b/src/extras/geometries/TorusKnotBufferGeometry.js @@ -1,11 +1,17 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { Vector2 } from '../../math/Vector2'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author Mugen87 / https://github.com/Mugen87 * * see: http://www.blackpawn.com/texts/pqtorus/ */ -THREE.TorusKnotBufferGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q ) { +function TorusKnotBufferGeometry ( radius, tube, tubularSegments, radialSegments, p, q ) { + this.isTorusKnotBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'TorusKnotBufferGeometry'; @@ -30,24 +36,24 @@ THREE.TorusKnotBufferGeometry = function ( radius, tube, tubularSegments, radial var indexCount = radialSegments * tubularSegments * 2 * 3; // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); // helper variables var i, j, index = 0, indexOffset = 0; - var vertex = new THREE.Vector3(); - var normal = new THREE.Vector3(); - var uv = new THREE.Vector2(); + var vertex = new Vector3(); + var normal = new Vector3(); + var uv = new Vector2(); - var P1 = new THREE.Vector3(); - var P2 = new THREE.Vector3(); + var P1 = new Vector3(); + var P2 = new Vector3(); - var B = new THREE.Vector3(); - var T = new THREE.Vector3(); - var N = new THREE.Vector3(); + var B = new Vector3(); + var T = new Vector3(); + var N = new Vector3(); // generate vertices, normals and uvs @@ -160,5 +166,8 @@ THREE.TorusKnotBufferGeometry = function ( radius, tube, tubularSegments, radial }; -THREE.TorusKnotBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.TorusKnotBufferGeometry.prototype.constructor = THREE.TorusKnotBufferGeometry; +TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; + + +export { TorusKnotBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TorusKnotGeometry.js b/src/extras/geometries/TorusKnotGeometry.js index cd8209b27b4737..f62713ce4a3885 100644 --- a/src/extras/geometries/TorusKnotGeometry.js +++ b/src/extras/geometries/TorusKnotGeometry.js @@ -1,10 +1,14 @@ +import { Geometry } from '../../core/Geometry'; +import { TorusKnotBufferGeometry } from './TorusKnotBufferGeometry'; + /** * @author oosmoxiecode */ -THREE.TorusKnotGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { +function TorusKnotGeometry ( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { + this.isTorusKnotGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'TorusKnotGeometry'; @@ -19,10 +23,13 @@ THREE.TorusKnotGeometry = function ( radius, tube, tubularSegments, radialSegmen if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); - this.fromBufferGeometry( new THREE.TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); + this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); this.mergeVertices(); }; -THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry; +TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); +TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; + + +export { TorusKnotGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TubeGeometry.js b/src/extras/geometries/TubeGeometry.js index 502b9d1bb06214..963b4b1b1c311a 100644 --- a/src/extras/geometries/TubeGeometry.js +++ b/src/extras/geometries/TubeGeometry.js @@ -1,3 +1,10 @@ +import { Geometry } from '../../core/Geometry'; +import { _Math } from '../../math/Math'; +import { Vector3 } from '../../math/Vector3'; +import { Matrix4 } from '../../math/Matrix4'; +import { Face3 } from '../../core/Face3'; +import { Vector2 } from '../../math/Vector2'; + /** * @author WestLangley / https://github.com/WestLangley * @author zz85 / https://github.com/zz85 @@ -12,9 +19,10 @@ * http://www.cs.indiana.edu/pub/techreports/TR425.pdf */ -THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) { +function TubeGeometry ( path, segments, radius, radialSegments, closed, taper ) { + this.isTubeGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'TubeGeometry'; @@ -31,7 +39,7 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, radius = radius || 1; radialSegments = radialSegments || 8; closed = closed || false; - taper = taper || THREE.TubeGeometry.NoTaper; + taper = taper || TubeGeometry.NoTaper; var grid = []; @@ -46,13 +54,13 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, u, v, r, cx, cy, - pos, pos2 = new THREE.Vector3(), + pos, pos2 = new Vector3(), i, j, ip, jp, a, b, c, d, uva, uvb, uvc, uvd; - var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ), + var frames = new TubeGeometry.FrenetFrames( path, segments, closed ), tangents = frames.tangents, normals = frames.normals, binormals = frames.binormals; @@ -64,7 +72,7 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, function vert( x, y, z ) { - return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1; + return scope.vertices.push( new Vector3( x, y, z ) ) - 1; } @@ -117,15 +125,15 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, c = grid[ ip ][ jp ]; d = grid[ i ][ jp ]; - uva = new THREE.Vector2( i / segments, j / radialSegments ); - uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments ); - uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments ); - uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments ); + uva = new Vector2( i / segments, j / radialSegments ); + uvb = new Vector2( ( i + 1 ) / segments, j / radialSegments ); + uvc = new Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments ); + uvd = new Vector2( i / segments, ( j + 1 ) / radialSegments ); - this.faces.push( new THREE.Face3( a, b, d ) ); + this.faces.push( new Face3( a, b, d ) ); this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - this.faces.push( new THREE.Face3( b, c, d ) ); + this.faces.push( new Face3( b, c, d ) ); this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); } @@ -137,32 +145,32 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, }; -THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry; +TubeGeometry.prototype = Object.create( Geometry.prototype ); +TubeGeometry.prototype.constructor = TubeGeometry; -THREE.TubeGeometry.NoTaper = function ( u ) { +TubeGeometry.NoTaper = function ( u ) { return 1; }; -THREE.TubeGeometry.SinusoidalTaper = function ( u ) { +TubeGeometry.SinusoidalTaper = function ( u ) { return Math.sin( Math.PI * u ); }; // For computing of Frenet frames, exposing the tangents, normals and binormals the spline -THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { +TubeGeometry.FrenetFrames = function ( path, segments, closed ) { - var normal = new THREE.Vector3(), + var normal = new Vector3(), tangents = [], normals = [], binormals = [], - vec = new THREE.Vector3(), - mat = new THREE.Matrix4(), + vec = new Vector3(), + mat = new Matrix4(), numpoints = segments + 1, theta, @@ -219,8 +227,8 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { // select an initial normal vector perpendicular to the first tangent vector, // and in the direction of the smallest tangent xyz component - normals[ 0 ] = new THREE.Vector3(); - binormals[ 0 ] = new THREE.Vector3(); + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); smallest = Number.MAX_VALUE; tx = Math.abs( tangents[ 0 ].x ); ty = Math.abs( tangents[ 0 ].y ); @@ -268,7 +276,7 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { vec.normalize(); - theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); @@ -283,7 +291,7 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { if ( closed ) { - theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); + theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); theta /= ( numpoints - 1 ); if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { @@ -303,3 +311,6 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { } }; + + +export { TubeGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/WireframeGeometry.js b/src/extras/geometries/WireframeGeometry.js index 4d417be10afb83..52363f2a27e5cf 100644 --- a/src/extras/geometries/WireframeGeometry.js +++ b/src/extras/geometries/WireframeGeometry.js @@ -1,10 +1,14 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WireframeGeometry = function ( geometry ) { +function WireframeGeometry ( geometry ) { + this.isWireframeGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); var edge = [ 0, 0 ], hash = {}; @@ -16,7 +20,7 @@ THREE.WireframeGeometry = function ( geometry ) { var keys = [ 'a', 'b', 'c' ]; - if ( geometry instanceof THREE.Geometry ) { + if ( (geometry && geometry.isGeometry) ) { var vertices = geometry.vertices; var faces = geometry.faces; @@ -67,9 +71,9 @@ THREE.WireframeGeometry = function ( geometry ) { } - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - } else if ( geometry instanceof THREE.BufferGeometry ) { + } else if ( (geometry && geometry.isBufferGeometry) ) { if ( geometry.index !== null ) { @@ -138,7 +142,7 @@ THREE.WireframeGeometry = function ( geometry ) { } - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); } else { @@ -170,7 +174,7 @@ THREE.WireframeGeometry = function ( geometry ) { } - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); } @@ -178,5 +182,8 @@ THREE.WireframeGeometry = function ( geometry ) { }; -THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry; +WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); +WireframeGeometry.prototype.constructor = WireframeGeometry; + + +export { WireframeGeometry }; \ No newline at end of file diff --git a/src/extras/helpers/ArrowHelper.js b/src/extras/helpers/ArrowHelper.js index 802fd1f11713d2..8e777e07b10c67 100644 --- a/src/extras/helpers/ArrowHelper.js +++ b/src/extras/helpers/ArrowHelper.js @@ -1,3 +1,15 @@ +import { Vector3 } from '../../math/Vector3'; +import { Object3D } from '../../core/Object3D'; +import { CylinderBufferGeometry } from '../geometries/CylinderBufferGeometry'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; +import { MeshBasicMaterial } from '../../materials/MeshBasicMaterial'; +import { Mesh } from '../../objects/Mesh'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Line } from '../../objects/Line'; + +var ArrowHelper; + /** * @author WestLangley / http://github.com/WestLangley * @author zz85 / http://github.com/zz85 @@ -14,19 +26,19 @@ * headWidth - Number */ -THREE.ArrowHelper = ( function () { +ArrowHelper = ( function () { - var lineGeometry = new THREE.BufferGeometry(); - lineGeometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + var lineGeometry = new BufferGeometry(); + lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); - var coneGeometry = new THREE.CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); + var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); coneGeometry.translate( 0, - 0.5, 0 ); return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { // dir is assumed to be normalized - THREE.Object3D.call( this ); + Object3D.call( this ); if ( color === undefined ) color = 0xffff00; if ( length === undefined ) length = 1; @@ -35,11 +47,11 @@ THREE.ArrowHelper = ( function () { this.position.copy( origin ); - this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) ); + this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) ); this.line.matrixAutoUpdate = false; this.add( this.line ); - this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) ); + this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) ); this.cone.matrixAutoUpdate = false; this.add( this.cone ); @@ -50,12 +62,12 @@ THREE.ArrowHelper = ( function () { }() ); -THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper; +ArrowHelper.prototype = Object.create( Object3D.prototype ); +ArrowHelper.prototype.constructor = ArrowHelper; -THREE.ArrowHelper.prototype.setDirection = ( function () { +ArrowHelper.prototype.setDirection = ( function () { - var axis = new THREE.Vector3(); + var axis = new Vector3(); var radians; return function setDirection( dir ) { @@ -84,7 +96,7 @@ THREE.ArrowHelper.prototype.setDirection = ( function () { }() ); -THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { +ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { if ( headLength === undefined ) headLength = 0.2 * length; if ( headWidth === undefined ) headWidth = 0.2 * headLength; @@ -98,9 +110,12 @@ THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth }; -THREE.ArrowHelper.prototype.setColor = function ( color ) { +ArrowHelper.prototype.setColor = function ( color ) { this.line.material.color.copy( color ); this.cone.material.color.copy( color ); }; + + +export { ArrowHelper }; \ No newline at end of file diff --git a/src/extras/helpers/AxisHelper.js b/src/extras/helpers/AxisHelper.js index 4e16b37e00ce99..a3bf3a188c51ae 100644 --- a/src/extras/helpers/AxisHelper.js +++ b/src/extras/helpers/AxisHelper.js @@ -1,9 +1,16 @@ +import { LineSegments } from '../../objects/LineSegments'; +import { VertexColors } from '../../constants'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { BufferAttribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author sroucheray / http://sroucheray.org/ * @author mrdoob / http://mrdoob.com/ */ -THREE.AxisHelper = function ( size ) { +function AxisHelper ( size ) { + this.isAxisHelper = this.isLineSegments = true; size = size || 1; @@ -19,15 +26,18 @@ THREE.AxisHelper = function ( size ) { 0, 0, 1, 0, 0.6, 1 ] ); - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) ); - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); - THREE.LineSegments.call( this, geometry, material ); + LineSegments.call( this, geometry, material ); }; -THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.AxisHelper.prototype.constructor = THREE.AxisHelper; +AxisHelper.prototype = Object.create( LineSegments.prototype ); +AxisHelper.prototype.constructor = AxisHelper; + + +export { AxisHelper }; \ No newline at end of file diff --git a/src/extras/helpers/BoundingBoxHelper.js b/src/extras/helpers/BoundingBoxHelper.js index b299e8187620fc..23e64a2eff0aae 100644 --- a/src/extras/helpers/BoundingBoxHelper.js +++ b/src/extras/helpers/BoundingBoxHelper.js @@ -1,25 +1,31 @@ +import { Mesh } from '../../objects/Mesh'; +import { MeshBasicMaterial } from '../../materials/MeshBasicMaterial'; +import { BoxGeometry } from '../geometries/BoxGeometry'; +import { Box3 } from '../../math/Box3'; + /** * @author WestLangley / http://github.com/WestLangley */ // a helper to show the world-axis-aligned bounding box for an object -THREE.BoundingBoxHelper = function ( object, hex ) { +function BoundingBoxHelper ( object, hex ) { + this.isBoundingBoxHelper = this.isMesh = true; var color = ( hex !== undefined ) ? hex : 0x888888; this.object = object; - this.box = new THREE.Box3(); + this.box = new Box3(); - THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) ); + Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) ); }; -THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype ); -THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper; +BoundingBoxHelper.prototype = Object.create( Mesh.prototype ); +BoundingBoxHelper.prototype.constructor = BoundingBoxHelper; -THREE.BoundingBoxHelper.prototype.update = function () { +BoundingBoxHelper.prototype.update = function () { this.box.setFromObject( this.object ); @@ -28,3 +34,6 @@ THREE.BoundingBoxHelper.prototype.update = function () { this.box.center( this.position ); }; + + +export { BoundingBoxHelper }; \ No newline at end of file diff --git a/src/extras/helpers/BoxHelper.js b/src/extras/helpers/BoxHelper.js index ee03890f7f9540..1106d62bff1363 100644 --- a/src/extras/helpers/BoxHelper.js +++ b/src/extras/helpers/BoxHelper.js @@ -1,19 +1,26 @@ +import { Box3 } from '../../math/Box3'; +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { BufferAttribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.BoxHelper = function ( object, color ) { +function BoxHelper ( object, color ) { + this.isBoxHelper = this.isLineSegments = true; if ( color === undefined ) color = 0xffff00; var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); var positions = new Float32Array( 8 * 3 ); - var geometry = new THREE.BufferGeometry(); - geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + var geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ) ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); if ( object !== undefined ) { @@ -23,16 +30,16 @@ THREE.BoxHelper = function ( object, color ) { }; -THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.BoxHelper.prototype.constructor = THREE.BoxHelper; +BoxHelper.prototype = Object.create( LineSegments.prototype ); +BoxHelper.prototype.constructor = BoxHelper; -THREE.BoxHelper.prototype.update = ( function () { +BoxHelper.prototype.update = ( function () { - var box = new THREE.Box3(); + var box = new Box3(); return function update( object ) { - if ( object instanceof THREE.Box3 ) { + if ( (object && object.isBox3) ) { box.copy( object ); @@ -82,3 +89,6 @@ THREE.BoxHelper.prototype.update = ( function () { }; } )(); + + +export { BoxHelper }; \ No newline at end of file diff --git a/src/extras/helpers/CameraHelper.js b/src/extras/helpers/CameraHelper.js index 07fda0f1dd389d..8675556f2eadc8 100644 --- a/src/extras/helpers/CameraHelper.js +++ b/src/extras/helpers/CameraHelper.js @@ -1,3 +1,11 @@ +import { Camera } from '../../cameras/Camera'; +import { Vector3 } from '../../math/Vector3'; +import { LineSegments } from '../../objects/LineSegments'; +import { Color } from '../../math/Color'; +import { FaceColors } from '../../constants'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Geometry } from '../../core/Geometry'; + /** * @author alteredq / http://alteredqualia.com/ * @@ -7,10 +15,11 @@ * http://evanw.github.com/lightgl.js/tests/shadowmap.html */ -THREE.CameraHelper = function ( camera ) { +function CameraHelper ( camera ) { + this.isCameraHelper = this.isLineSegments = true; - var geometry = new THREE.Geometry(); - var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } ); + var geometry = new Geometry(); + var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } ); var pointMap = {}; @@ -78,8 +87,8 @@ THREE.CameraHelper = function ( camera ) { function addPoint( id, hex ) { - geometry.vertices.push( new THREE.Vector3() ); - geometry.colors.push( new THREE.Color( hex ) ); + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( hex ) ); if ( pointMap[ id ] === undefined ) { @@ -91,7 +100,7 @@ THREE.CameraHelper = function ( camera ) { } - THREE.LineSegments.call( this, geometry, material ); + LineSegments.call( this, geometry, material ); this.camera = camera; if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); @@ -105,15 +114,15 @@ THREE.CameraHelper = function ( camera ) { }; -THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.CameraHelper.prototype.constructor = THREE.CameraHelper; +CameraHelper.prototype = Object.create( LineSegments.prototype ); +CameraHelper.prototype.constructor = CameraHelper; -THREE.CameraHelper.prototype.update = function () { +CameraHelper.prototype.update = function () { var geometry, pointMap; - var vector = new THREE.Vector3(); - var camera = new THREE.Camera(); + var vector = new Vector3(); + var camera = new Camera(); function setPoint( point, x, y, z ) { @@ -187,3 +196,6 @@ THREE.CameraHelper.prototype.update = function () { }; }(); + + +export { CameraHelper }; \ No newline at end of file diff --git a/src/extras/helpers/DirectionalLightHelper.js b/src/extras/helpers/DirectionalLightHelper.js index 0443bd942196ad..52b9b487e0ef53 100644 --- a/src/extras/helpers/DirectionalLightHelper.js +++ b/src/extras/helpers/DirectionalLightHelper.js @@ -1,12 +1,20 @@ +import { Vector3 } from '../../math/Vector3'; +import { Object3D } from '../../core/Object3D'; +import { Line } from '../../objects/Line'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ -THREE.DirectionalLightHelper = function ( light, size ) { +function DirectionalLightHelper ( light, size ) { + this.isDirectionalLightHelper = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.light = light; this.light.updateMatrixWorld(); @@ -16,8 +24,8 @@ THREE.DirectionalLightHelper = function ( light, size ) { if ( size === undefined ) size = 1; - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( [ + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ - size, size, 0, size, size, 0, size, - size, 0, @@ -25,23 +33,23 @@ THREE.DirectionalLightHelper = function ( light, size ) { - size, size, 0 ], 3 ) ); - var material = new THREE.LineBasicMaterial( { fog: false } ); + var material = new LineBasicMaterial( { fog: false } ); - this.add( new THREE.Line( geometry, material ) ); + this.add( new Line( geometry, material ) ); - geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); - this.add( new THREE.Line( geometry, material )); + this.add( new Line( geometry, material )); this.update(); }; -THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper; +DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); +DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; -THREE.DirectionalLightHelper.prototype.dispose = function () { +DirectionalLightHelper.prototype.dispose = function () { var lightPlane = this.children[ 0 ]; var targetLine = this.children[ 1 ]; @@ -53,11 +61,11 @@ THREE.DirectionalLightHelper.prototype.dispose = function () { }; -THREE.DirectionalLightHelper.prototype.update = function () { +DirectionalLightHelper.prototype.update = function () { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var v3 = new THREE.Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); + var v3 = new Vector3(); return function update() { @@ -77,3 +85,6 @@ THREE.DirectionalLightHelper.prototype.update = function () { }; }(); + + +export { DirectionalLightHelper }; \ No newline at end of file diff --git a/src/extras/helpers/EdgesHelper.js b/src/extras/helpers/EdgesHelper.js index 051e314efd5762..8211da3db52bae 100644 --- a/src/extras/helpers/EdgesHelper.js +++ b/src/extras/helpers/EdgesHelper.js @@ -1,3 +1,7 @@ +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { EdgesGeometry } from '../geometries/EdgesGeometry'; + /** * @author WestLangley / http://github.com/WestLangley * @param object THREE.Mesh whose geometry will be used @@ -8,16 +12,20 @@ * an edge is only rendered if the angle is at least 10 degrees. */ -THREE.EdgesHelper = function ( object, hex, thresholdAngle ) { +function EdgesHelper ( object, hex, thresholdAngle ) { + this.isEdgesHelper = this.isLineSegments = true; var color = ( hex !== undefined ) ? hex : 0xffffff; - THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) ); + LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) ); this.matrix = object.matrixWorld; this.matrixAutoUpdate = false; }; -THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper; +EdgesHelper.prototype = Object.create( LineSegments.prototype ); +EdgesHelper.prototype.constructor = EdgesHelper; + + +export { EdgesHelper }; \ No newline at end of file diff --git a/src/extras/helpers/FaceNormalsHelper.js b/src/extras/helpers/FaceNormalsHelper.js index 1868ab0bec1d9c..a6ef79b1d5e7a3 100644 --- a/src/extras/helpers/FaceNormalsHelper.js +++ b/src/extras/helpers/FaceNormalsHelper.js @@ -1,9 +1,17 @@ +import { Matrix3 } from '../../math/Matrix3'; +import { Vector3 } from '../../math/Vector3'; +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ -THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { +function FaceNormalsHelper ( object, size, hex, linewidth ) { + this.isFaceNormalsHelper = this.isLineSegments = true; // FaceNormalsHelper only supports THREE.Geometry @@ -21,7 +29,7 @@ THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { var objGeometry = this.object.geometry; - if ( objGeometry instanceof THREE.Geometry ) { + if ( (objGeometry && objGeometry.isGeometry) ) { nNormals = objGeometry.faces.length; @@ -33,13 +41,13 @@ THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { // - var geometry = new THREE.BufferGeometry(); + var geometry = new BufferGeometry(); - var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 ); + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); geometry.addAttribute( 'position', positions ); - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); // @@ -48,14 +56,14 @@ THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { }; -THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper; +FaceNormalsHelper.prototype = Object.create( LineSegments.prototype ); +FaceNormalsHelper.prototype.constructor = FaceNormalsHelper; -THREE.FaceNormalsHelper.prototype.update = ( function () { +FaceNormalsHelper.prototype.update = ( function () { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var normalMatrix = new THREE.Matrix3(); + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); return function update() { @@ -108,3 +116,6 @@ THREE.FaceNormalsHelper.prototype.update = ( function () { }; }() ); + + +export { FaceNormalsHelper }; \ No newline at end of file diff --git a/src/extras/helpers/GridHelper.js b/src/extras/helpers/GridHelper.js index eb794f5dad3b1f..45fb6af3e9f94e 100644 --- a/src/extras/helpers/GridHelper.js +++ b/src/extras/helpers/GridHelper.js @@ -1,12 +1,20 @@ +import { LineSegments } from '../../objects/LineSegments'; +import { VertexColors } from '../../constants'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Color } from '../../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.GridHelper = function ( size, divisions, color1, color2 ) { +function GridHelper ( size, divisions, color1, color2 ) { + this.isGridHelper = this.isLineSegments = true; divisions = divisions || 1; - color1 = new THREE.Color( color1 !== undefined ? color1 : 0x444444 ); - color2 = new THREE.Color( color2 !== undefined ? color2 : 0x888888 ); + color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); + color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); var center = divisions / 2; var step = ( size * 2 ) / divisions; @@ -26,21 +34,24 @@ THREE.GridHelper = function ( size, divisions, color1, color2 ) { } - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new THREE.Float32Attribute( colors, 3 ) ); + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) ); - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); - THREE.LineSegments.call( this, geometry, material ); + LineSegments.call( this, geometry, material ); }; -THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.GridHelper.prototype.constructor = THREE.GridHelper; +GridHelper.prototype = Object.create( LineSegments.prototype ); +GridHelper.prototype.constructor = GridHelper; -THREE.GridHelper.prototype.setColors = function () { +GridHelper.prototype.setColors = function () { console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); }; + + +export { GridHelper }; \ No newline at end of file diff --git a/src/extras/helpers/HemisphereLightHelper.js b/src/extras/helpers/HemisphereLightHelper.js index 034d81f04dbc77..45c73cb2fc1c44 100644 --- a/src/extras/helpers/HemisphereLightHelper.js +++ b/src/extras/helpers/HemisphereLightHelper.js @@ -1,11 +1,20 @@ +import { Vector3 } from '../../math/Vector3'; +import { Object3D } from '../../core/Object3D'; +import { Mesh } from '../../objects/Mesh'; +import { FaceColors } from '../../constants'; +import { MeshBasicMaterial } from '../../materials/MeshBasicMaterial'; +import { SphereGeometry } from '../geometries/SphereGeometry'; +import { Color } from '../../math/Color'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.HemisphereLightHelper = function ( light, sphereSize ) { +function HemisphereLightHelper ( light, sphereSize ) { + this.isHemisphereLightHelper = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.light = light; this.light.updateMatrixWorld(); @@ -13,9 +22,9 @@ THREE.HemisphereLightHelper = function ( light, sphereSize ) { this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; - this.colors = [ new THREE.Color(), new THREE.Color() ]; + this.colors = [ new Color(), new Color() ]; - var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 ); + var geometry = new SphereGeometry( sphereSize, 4, 2 ); geometry.rotateX( - Math.PI / 2 ); for ( var i = 0, il = 8; i < il; i ++ ) { @@ -24,28 +33,28 @@ THREE.HemisphereLightHelper = function ( light, sphereSize ) { } - var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } ); + var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } ); - this.lightSphere = new THREE.Mesh( geometry, material ); + this.lightSphere = new Mesh( geometry, material ); this.add( this.lightSphere ); this.update(); }; -THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper; +HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); +HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; -THREE.HemisphereLightHelper.prototype.dispose = function () { +HemisphereLightHelper.prototype.dispose = function () { this.lightSphere.geometry.dispose(); this.lightSphere.material.dispose(); }; -THREE.HemisphereLightHelper.prototype.update = function () { +HemisphereLightHelper.prototype.update = function () { - var vector = new THREE.Vector3(); + var vector = new Vector3(); return function update() { @@ -58,3 +67,6 @@ THREE.HemisphereLightHelper.prototype.update = function () { }; }(); + + +export { HemisphereLightHelper }; \ No newline at end of file diff --git a/src/extras/helpers/PointLightHelper.js b/src/extras/helpers/PointLightHelper.js index 40742519746b25..edcf1d3035d0de 100644 --- a/src/extras/helpers/PointLightHelper.js +++ b/src/extras/helpers/PointLightHelper.js @@ -1,18 +1,23 @@ +import { Mesh } from '../../objects/Mesh'; +import { MeshBasicMaterial } from '../../materials/MeshBasicMaterial'; +import { SphereBufferGeometry } from '../geometries/SphereBufferGeometry'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.PointLightHelper = function ( light, sphereSize ) { +function PointLightHelper ( light, sphereSize ) { + this.isPointLightHelper = this.isMesh = true; this.light = light; this.light.updateMatrixWorld(); - var geometry = new THREE.SphereBufferGeometry( sphereSize, 4, 2 ); - var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); + var geometry = new SphereBufferGeometry( sphereSize, 4, 2 ); + var material = new MeshBasicMaterial( { wireframe: true, fog: false } ); material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - THREE.Mesh.call( this, geometry, material ); + Mesh.call( this, geometry, material ); this.matrix = this.light.matrixWorld; this.matrixAutoUpdate = false; @@ -41,17 +46,17 @@ THREE.PointLightHelper = function ( light, sphereSize ) { }; -THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype ); -THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper; +PointLightHelper.prototype = Object.create( Mesh.prototype ); +PointLightHelper.prototype.constructor = PointLightHelper; -THREE.PointLightHelper.prototype.dispose = function () { +PointLightHelper.prototype.dispose = function () { this.geometry.dispose(); this.material.dispose(); }; -THREE.PointLightHelper.prototype.update = function () { +PointLightHelper.prototype.update = function () { this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); @@ -71,3 +76,6 @@ THREE.PointLightHelper.prototype.update = function () { */ }; + + +export { PointLightHelper }; \ No newline at end of file diff --git a/src/extras/helpers/SkeletonHelper.js b/src/extras/helpers/SkeletonHelper.js index 169dd1e24118c1..f20d5c5aa8e3f2 100644 --- a/src/extras/helpers/SkeletonHelper.js +++ b/src/extras/helpers/SkeletonHelper.js @@ -1,3 +1,11 @@ +import { LineSegments } from '../../objects/LineSegments'; +import { Matrix4 } from '../../math/Matrix4'; +import { VertexColors } from '../../constants'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Color } from '../../math/Color'; +import { Vector3 } from '../../math/Vector3'; +import { Geometry } from '../../core/Geometry'; + /** * @author Sean Griffin / http://twitter.com/sgrif * @author Michael Guerrero / http://realitymeltdown.com @@ -5,22 +13,23 @@ * @author ikerr / http://verold.com */ -THREE.SkeletonHelper = function ( object ) { +function SkeletonHelper ( object ) { + this.isSkeletonHelper = this.isLineSegments = true; this.bones = this.getBoneList( object ); - var geometry = new THREE.Geometry(); + var geometry = new Geometry(); for ( var i = 0; i < this.bones.length; i ++ ) { var bone = this.bones[ i ]; - if ( bone.parent instanceof THREE.Bone ) { + if ( (bone.parent && bone.parent.isBone) ) { - geometry.vertices.push( new THREE.Vector3() ); - geometry.vertices.push( new THREE.Vector3() ); - geometry.colors.push( new THREE.Color( 0, 0, 1 ) ); - geometry.colors.push( new THREE.Color( 0, 1, 0 ) ); + geometry.vertices.push( new Vector3() ); + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( 0, 0, 1 ) ); + geometry.colors.push( new Color( 0, 1, 0 ) ); } @@ -28,9 +37,9 @@ THREE.SkeletonHelper = function ( object ) { geometry.dynamic = true; - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } ); + var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } ); - THREE.LineSegments.call( this, geometry, material ); + LineSegments.call( this, geometry, material ); this.root = object; @@ -42,14 +51,14 @@ THREE.SkeletonHelper = function ( object ) { }; -THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper; +SkeletonHelper.prototype = Object.create( LineSegments.prototype ); +SkeletonHelper.prototype.constructor = SkeletonHelper; -THREE.SkeletonHelper.prototype.getBoneList = function( object ) { +SkeletonHelper.prototype.getBoneList = function( object ) { var boneList = []; - if ( object instanceof THREE.Bone ) { + if ( (object && object.isBone) ) { boneList.push( object ); @@ -65,13 +74,13 @@ THREE.SkeletonHelper.prototype.getBoneList = function( object ) { }; -THREE.SkeletonHelper.prototype.update = function () { +SkeletonHelper.prototype.update = function () { var geometry = this.geometry; - var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld ); + var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld ); - var boneMatrix = new THREE.Matrix4(); + var boneMatrix = new Matrix4(); var j = 0; @@ -79,7 +88,7 @@ THREE.SkeletonHelper.prototype.update = function () { var bone = this.bones[ i ]; - if ( bone.parent instanceof THREE.Bone ) { + if ( (bone.parent && bone.parent.isBone) ) { boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); @@ -98,3 +107,6 @@ THREE.SkeletonHelper.prototype.update = function () { geometry.computeBoundingSphere(); }; + + +export { SkeletonHelper }; \ No newline at end of file diff --git a/src/extras/helpers/SpotLightHelper.js b/src/extras/helpers/SpotLightHelper.js index 8caea9848d52e9..7b2a0f9bdca6da 100644 --- a/src/extras/helpers/SpotLightHelper.js +++ b/src/extras/helpers/SpotLightHelper.js @@ -1,12 +1,20 @@ +import { Vector3 } from '../../math/Vector3'; +import { Object3D } from '../../core/Object3D'; +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ -THREE.SpotLightHelper = function ( light ) { +function SpotLightHelper ( light ) { + this.isSpotLightHelper = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.light = light; this.light.updateMatrixWorld(); @@ -14,7 +22,7 @@ THREE.SpotLightHelper = function ( light ) { this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; - var geometry = new THREE.BufferGeometry(); + var geometry = new BufferGeometry(); var positions = [ 0, 0, 0, 0, 0, 1, @@ -36,31 +44,31 @@ THREE.SpotLightHelper = function ( light ) { } - geometry.addAttribute( 'position', new THREE.Float32Attribute( positions, 3 ) ); + geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) ); - var material = new THREE.LineBasicMaterial( { fog: false } ); + var material = new LineBasicMaterial( { fog: false } ); - this.cone = new THREE.LineSegments( geometry, material ); + this.cone = new LineSegments( geometry, material ); this.add( this.cone ); this.update(); }; -THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper; +SpotLightHelper.prototype = Object.create( Object3D.prototype ); +SpotLightHelper.prototype.constructor = SpotLightHelper; -THREE.SpotLightHelper.prototype.dispose = function () { +SpotLightHelper.prototype.dispose = function () { this.cone.geometry.dispose(); this.cone.material.dispose(); }; -THREE.SpotLightHelper.prototype.update = function () { +SpotLightHelper.prototype.update = function () { - var vector = new THREE.Vector3(); - var vector2 = new THREE.Vector3(); + var vector = new Vector3(); + var vector2 = new Vector3(); return function update() { @@ -79,3 +87,6 @@ THREE.SpotLightHelper.prototype.update = function () { }; }(); + + +export { SpotLightHelper }; \ No newline at end of file diff --git a/src/extras/helpers/VertexNormalsHelper.js b/src/extras/helpers/VertexNormalsHelper.js index 3121b52a16e42e..a7f2e668e57117 100644 --- a/src/extras/helpers/VertexNormalsHelper.js +++ b/src/extras/helpers/VertexNormalsHelper.js @@ -1,9 +1,17 @@ +import { Matrix3 } from '../../math/Matrix3'; +import { Vector3 } from '../../math/Vector3'; +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ -THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { +function VertexNormalsHelper ( object, size, hex, linewidth ) { + this.isVertexNormalsHelper = this.isLineSegments = true; this.object = object; @@ -19,11 +27,11 @@ THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { var objGeometry = this.object.geometry; - if ( objGeometry instanceof THREE.Geometry ) { + if ( (objGeometry && objGeometry.isGeometry) ) { nNormals = objGeometry.faces.length * 3; - } else if ( objGeometry instanceof THREE.BufferGeometry ) { + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { nNormals = objGeometry.attributes.normal.count; @@ -31,13 +39,13 @@ THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { // - var geometry = new THREE.BufferGeometry(); + var geometry = new BufferGeometry(); - var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 ); + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); geometry.addAttribute( 'position', positions ); - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); // @@ -47,14 +55,14 @@ THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { }; -THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper; +VertexNormalsHelper.prototype = Object.create( LineSegments.prototype ); +VertexNormalsHelper.prototype.constructor = VertexNormalsHelper; -THREE.VertexNormalsHelper.prototype.update = ( function () { +VertexNormalsHelper.prototype.update = ( function () { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var normalMatrix = new THREE.Matrix3(); + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); return function update() { @@ -72,7 +80,7 @@ THREE.VertexNormalsHelper.prototype.update = ( function () { var objGeometry = this.object.geometry; - if ( objGeometry instanceof THREE.Geometry ) { + if ( (objGeometry && objGeometry.isGeometry) ) { var vertices = objGeometry.vertices; @@ -106,7 +114,7 @@ THREE.VertexNormalsHelper.prototype.update = ( function () { } - } else if ( objGeometry instanceof THREE.BufferGeometry ) { + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { var objPos = objGeometry.attributes.position; @@ -143,3 +151,6 @@ THREE.VertexNormalsHelper.prototype.update = ( function () { }; }() ); + + +export { VertexNormalsHelper }; \ No newline at end of file diff --git a/src/extras/helpers/WireframeHelper.js b/src/extras/helpers/WireframeHelper.js index 5fcdf90f76753b..42d7d8eca911b0 100644 --- a/src/extras/helpers/WireframeHelper.js +++ b/src/extras/helpers/WireframeHelper.js @@ -1,17 +1,25 @@ +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { WireframeGeometry } from '../geometries/WireframeGeometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WireframeHelper = function ( object, hex ) { +function WireframeHelper ( object, hex ) { + this.isWireframeHelper = this.isLineSegments = true; var color = ( hex !== undefined ) ? hex : 0xffffff; - THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) ); + LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) ); this.matrix = object.matrixWorld; this.matrixAutoUpdate = false; }; -THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper; +WireframeHelper.prototype = Object.create( LineSegments.prototype ); +WireframeHelper.prototype.constructor = WireframeHelper; + + +export { WireframeHelper }; \ No newline at end of file diff --git a/src/extras/objects/ImmediateRenderObject.js b/src/extras/objects/ImmediateRenderObject.js index e5d447b5499f65..aeef3325f7d71f 100644 --- a/src/extras/objects/ImmediateRenderObject.js +++ b/src/extras/objects/ImmediateRenderObject.js @@ -1,15 +1,21 @@ +import { Object3D } from '../../core/Object3D'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.ImmediateRenderObject = function ( material ) { +function ImmediateRenderObject ( material ) { + this.isImmediateRenderObject = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.material = material; this.render = function ( renderCallback ) {}; }; -THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject; +ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); +ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; + + +export { ImmediateRenderObject }; \ No newline at end of file diff --git a/src/extras/objects/MorphBlendMesh.js b/src/extras/objects/MorphBlendMesh.js index fa3cfce9fc28d7..5d47f9b86fb666 100644 --- a/src/extras/objects/MorphBlendMesh.js +++ b/src/extras/objects/MorphBlendMesh.js @@ -1,10 +1,14 @@ +import { Mesh } from '../../objects/Mesh'; +import { _Math } from '../../math/Math'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.MorphBlendMesh = function( geometry, material ) { +function MorphBlendMesh( geometry, material ) { + this.isMorphBlendMesh = this.isMesh = true; - THREE.Mesh.call( this, geometry, material ); + Mesh.call( this, geometry, material ); this.animationsMap = {}; this.animationsList = []; @@ -26,10 +30,10 @@ THREE.MorphBlendMesh = function( geometry, material ) { }; -THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype ); -THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh; +MorphBlendMesh.prototype = Object.create( Mesh.prototype ); +MorphBlendMesh.prototype.constructor = MorphBlendMesh; -THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { +MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { var animation = { @@ -60,7 +64,7 @@ THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fp }; -THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { +MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { var pattern = /([a-z]+)_?(\d+)/i; @@ -101,7 +105,7 @@ THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { }; -THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { +MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { var animation = this.animationsMap[ name ]; @@ -114,7 +118,7 @@ THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) }; -THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { +MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { var animation = this.animationsMap[ name ]; @@ -127,7 +131,7 @@ THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) }; -THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { +MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { var animation = this.animationsMap[ name ]; @@ -140,7 +144,7 @@ THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { }; -THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { +MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { var animation = this.animationsMap[ name ]; @@ -153,7 +157,7 @@ THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration }; -THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { +MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { var animation = this.animationsMap[ name ]; @@ -165,7 +169,7 @@ THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { }; -THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { +MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { var animation = this.animationsMap[ name ]; @@ -177,7 +181,7 @@ THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { }; -THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { +MorphBlendMesh.prototype.getAnimationTime = function ( name ) { var time = 0; @@ -193,7 +197,7 @@ THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { }; -THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { +MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { var duration = - 1; @@ -209,7 +213,7 @@ THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { }; -THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { +MorphBlendMesh.prototype.playAnimation = function ( name ) { var animation = this.animationsMap[ name ]; @@ -226,7 +230,7 @@ THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { }; -THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { +MorphBlendMesh.prototype.stopAnimation = function ( name ) { var animation = this.animationsMap[ name ]; @@ -238,7 +242,7 @@ THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { }; -THREE.MorphBlendMesh.prototype.update = function ( delta ) { +MorphBlendMesh.prototype.update = function ( delta ) { for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { @@ -280,7 +284,7 @@ THREE.MorphBlendMesh.prototype.update = function ( delta ) { } - var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); + var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); var weight = animation.weight; if ( keyframe !== animation.currentFrame ) { @@ -313,3 +317,6 @@ THREE.MorphBlendMesh.prototype.update = function ( delta ) { } }; + + +export { MorphBlendMesh }; \ No newline at end of file diff --git a/src/lights/AmbientLight.js b/src/lights/AmbientLight.js index 3135fdf9fa2d8e..485c585892399f 100644 --- a/src/lights/AmbientLight.js +++ b/src/lights/AmbientLight.js @@ -1,10 +1,13 @@ +import { Light } from './Light'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.AmbientLight = function ( color, intensity ) { +function AmbientLight ( color, intensity ) { + this.isAmbientLight = true; - THREE.Light.call( this, color, intensity ); + Light.call( this, color, intensity ); this.type = 'AmbientLight'; @@ -12,8 +15,11 @@ THREE.AmbientLight = function ( color, intensity ) { }; -THREE.AmbientLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { +AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: THREE.AmbientLight + constructor: AmbientLight } ); + + +export { AmbientLight }; \ No newline at end of file diff --git a/src/lights/DirectionalLight.js b/src/lights/DirectionalLight.js index 406aba28218633..fc807ba767f6e1 100644 --- a/src/lights/DirectionalLight.js +++ b/src/lights/DirectionalLight.js @@ -1,30 +1,35 @@ +import { Light } from './Light'; +import { DirectionalLightShadow } from './DirectionalLightShadow'; +import { Object3D } from '../core/Object3D'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.DirectionalLight = function ( color, intensity ) { +function DirectionalLight ( color, intensity ) { + this.isDirectionalLight = true; - THREE.Light.call( this, color, intensity ); + Light.call( this, color, intensity ); this.type = 'DirectionalLight'; - this.position.copy( THREE.Object3D.DefaultUp ); + this.position.copy( Object3D.DefaultUp ); this.updateMatrix(); - this.target = new THREE.Object3D(); + this.target = new Object3D(); - this.shadow = new THREE.DirectionalLightShadow(); + this.shadow = new DirectionalLightShadow(); }; -THREE.DirectionalLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { +DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: THREE.DirectionalLight, + constructor: DirectionalLight, copy: function ( source ) { - THREE.Light.prototype.copy.call( this, source ); + Light.prototype.copy.call( this, source ); this.target = source.target.clone(); @@ -35,3 +40,6 @@ THREE.DirectionalLight.prototype = Object.assign( Object.create( THREE.Light.pro } } ); + + +export { DirectionalLight }; \ No newline at end of file diff --git a/src/lights/DirectionalLightShadow.js b/src/lights/DirectionalLightShadow.js index f446f4d6a6ab59..de772fb07a1fc4 100644 --- a/src/lights/DirectionalLightShadow.js +++ b/src/lights/DirectionalLightShadow.js @@ -1,15 +1,22 @@ +import { LightShadow } from './LightShadow'; +import { OrthographicCamera } from '../cameras/OrthographicCamera'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.DirectionalLightShadow = function ( light ) { +function DirectionalLightShadow ( light ) { + this.isDirectionalLightShadow = true; - THREE.LightShadow.call( this, new THREE.OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); }; -THREE.DirectionalLightShadow.prototype = Object.assign( Object.create( THREE.LightShadow.prototype ), { +DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - constructor: THREE.DirectionalLightShadow + constructor: DirectionalLightShadow } ); + + +export { DirectionalLightShadow }; \ No newline at end of file diff --git a/src/lights/HemisphereLight.js b/src/lights/HemisphereLight.js index 4f6269cf4bcbb6..9d08bb24f7166a 100644 --- a/src/lights/HemisphereLight.js +++ b/src/lights/HemisphereLight.js @@ -1,29 +1,34 @@ +import { Light } from './Light'; +import { Color } from '../math/Color'; +import { Object3D } from '../core/Object3D'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) { +function HemisphereLight ( skyColor, groundColor, intensity ) { + this.isHemisphereLight = true; - THREE.Light.call( this, skyColor, intensity ); + Light.call( this, skyColor, intensity ); this.type = 'HemisphereLight'; this.castShadow = undefined; - this.position.copy( THREE.Object3D.DefaultUp ); + this.position.copy( Object3D.DefaultUp ); this.updateMatrix(); - this.groundColor = new THREE.Color( groundColor ); + this.groundColor = new Color( groundColor ); }; -THREE.HemisphereLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { +HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: THREE.HemisphereLight, + constructor: HemisphereLight, copy: function ( source ) { - THREE.Light.prototype.copy.call( this, source ); + Light.prototype.copy.call( this, source ); this.groundColor.copy( source.groundColor ); @@ -32,3 +37,6 @@ THREE.HemisphereLight.prototype = Object.assign( Object.create( THREE.Light.prot } } ); + + +export { HemisphereLight }; \ No newline at end of file diff --git a/src/lights/Light.js b/src/lights/Light.js index 5e215acc01ef10..fe5cb367a41596 100644 --- a/src/lights/Light.js +++ b/src/lights/Light.js @@ -1,28 +1,32 @@ +import { Object3D } from '../core/Object3D'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Light = function ( color, intensity ) { +function Light ( color, intensity ) { + this.isLight = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Light'; - this.color = new THREE.Color( color ); + this.color = new Color( color ); this.intensity = intensity !== undefined ? intensity : 1; this.receiveShadow = undefined; }; -THREE.Light.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Light.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Light, + constructor: Light, copy: function ( source ) { - THREE.Object3D.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source ); this.color.copy( source.color ); this.intensity = source.intensity; @@ -33,7 +37,7 @@ THREE.Light.prototype = Object.assign( Object.create( THREE.Object3D.prototype ) toJSON: function ( meta ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var data = Object3D.prototype.toJSON.call( this, meta ); data.object.color = this.color.getHex(); data.object.intensity = this.intensity; @@ -50,3 +54,6 @@ THREE.Light.prototype = Object.assign( Object.create( THREE.Object3D.prototype ) } } ); + + +export { Light }; \ No newline at end of file diff --git a/src/lights/LightShadow.js b/src/lights/LightShadow.js index 7e2409c991bbd5..1033a41844aba5 100644 --- a/src/lights/LightShadow.js +++ b/src/lights/LightShadow.js @@ -1,22 +1,26 @@ +import { Matrix4 } from '../math/Matrix4'; +import { Vector2 } from '../math/Vector2'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.LightShadow = function ( camera ) { +function LightShadow ( camera ) { + this.isLightShadow = true; this.camera = camera; this.bias = 0; this.radius = 1; - this.mapSize = new THREE.Vector2( 512, 512 ); + this.mapSize = new Vector2( 512, 512 ); this.map = null; - this.matrix = new THREE.Matrix4(); + this.matrix = new Matrix4(); }; -Object.assign( THREE.LightShadow.prototype, { +Object.assign( LightShadow.prototype, { copy: function ( source ) { @@ -38,3 +42,6 @@ Object.assign( THREE.LightShadow.prototype, { } } ); + + +export { LightShadow }; \ No newline at end of file diff --git a/src/lights/PointLight.js b/src/lights/PointLight.js index 64df91bb17726f..d1a87c9d238dd1 100644 --- a/src/lights/PointLight.js +++ b/src/lights/PointLight.js @@ -1,11 +1,16 @@ +import { Light } from './Light'; +import { PerspectiveCamera } from '../cameras/PerspectiveCamera'; +import { LightShadow } from './LightShadow'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.PointLight = function ( color, intensity, distance, decay ) { +function PointLight ( color, intensity, distance, decay ) { + this.isPointLight = true; - THREE.Light.call( this, color, intensity ); + Light.call( this, color, intensity ); this.type = 'PointLight'; @@ -26,17 +31,17 @@ THREE.PointLight = function ( color, intensity, distance, decay ) { this.distance = ( distance !== undefined ) ? distance : 0; this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) ); + this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); }; -THREE.PointLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { +PointLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: THREE.PointLight, + constructor: PointLight, copy: function ( source ) { - THREE.Light.prototype.copy.call( this, source ); + Light.prototype.copy.call( this, source ); this.distance = source.distance; this.decay = source.decay; @@ -48,3 +53,6 @@ THREE.PointLight.prototype = Object.assign( Object.create( THREE.Light.prototype } } ); + + +export { PointLight }; \ No newline at end of file diff --git a/src/lights/SpotLight.js b/src/lights/SpotLight.js index 3becdcd725aca1..d6597709d5ad8f 100644 --- a/src/lights/SpotLight.js +++ b/src/lights/SpotLight.js @@ -1,17 +1,22 @@ +import { Light } from './Light'; +import { SpotLightShadow } from './SpotLightShadow'; +import { Object3D } from '../core/Object3D'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.SpotLight = function ( color, intensity, distance, angle, penumbra, decay ) { +function SpotLight ( color, intensity, distance, angle, penumbra, decay ) { + this.isSpotLight = true; - THREE.Light.call( this, color, intensity ); + Light.call( this, color, intensity ); this.type = 'SpotLight'; - this.position.copy( THREE.Object3D.DefaultUp ); + this.position.copy( Object3D.DefaultUp ); this.updateMatrix(); - this.target = new THREE.Object3D(); + this.target = new Object3D(); Object.defineProperty( this, 'power', { get: function () { @@ -31,17 +36,17 @@ THREE.SpotLight = function ( color, intensity, distance, angle, penumbra, decay this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - this.shadow = new THREE.SpotLightShadow(); + this.shadow = new SpotLightShadow(); }; -THREE.SpotLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { +SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: THREE.SpotLight, + constructor: SpotLight, copy: function ( source ) { - THREE.Light.prototype.copy.call( this, source ); + Light.prototype.copy.call( this, source ); this.distance = source.distance; this.angle = source.angle; @@ -57,3 +62,6 @@ THREE.SpotLight.prototype = Object.assign( Object.create( THREE.Light.prototype } } ); + + +export { SpotLight }; \ No newline at end of file diff --git a/src/lights/SpotLightShadow.js b/src/lights/SpotLightShadow.js index 42416844473bdf..15bc3a5d12d9a8 100644 --- a/src/lights/SpotLightShadow.js +++ b/src/lights/SpotLightShadow.js @@ -1,20 +1,25 @@ +import { LightShadow } from './LightShadow'; +import { _Math } from '../math/Math'; +import { PerspectiveCamera } from '../cameras/PerspectiveCamera'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.SpotLightShadow = function () { +function SpotLightShadow () { + this.isSpotLightShadow = true; - THREE.LightShadow.call( this, new THREE.PerspectiveCamera( 50, 1, 0.5, 500 ) ); + LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); }; -THREE.SpotLightShadow.prototype = Object.assign( Object.create( THREE.LightShadow.prototype ), { +SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - constructor: THREE.SpotLightShadow, + constructor: SpotLightShadow, update: function ( light ) { - var fov = THREE.Math.RAD2DEG * 2 * light.angle; + var fov = _Math.RAD2DEG * 2 * light.angle; var aspect = this.mapSize.width / this.mapSize.height; var far = light.distance || 500; @@ -32,3 +37,6 @@ THREE.SpotLightShadow.prototype = Object.assign( Object.create( THREE.LightShado } } ); + + +export { SpotLightShadow }; \ No newline at end of file diff --git a/src/loaders/AnimationLoader.js b/src/loaders/AnimationLoader.js index aada51b26ab694..cbd807397780da 100644 --- a/src/loaders/AnimationLoader.js +++ b/src/loaders/AnimationLoader.js @@ -1,20 +1,25 @@ +import { AnimationClip } from '../animation/AnimationClip'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author bhouston / http://clara.io/ */ -THREE.AnimationLoader = function ( manager ) { +function AnimationLoader ( manager ) { + this.isAnimationLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.AnimationLoader.prototype, { +Object.assign( AnimationLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var loader = new THREE.XHRLoader( scope.manager ); + var loader = new XHRLoader( scope.manager ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); @@ -29,7 +34,7 @@ Object.assign( THREE.AnimationLoader.prototype, { for ( var i = 0; i < json.length; i ++ ) { - var clip = THREE.AnimationClip.parse( json[ i ] ); + var clip = AnimationClip.parse( json[ i ] ); animations.push( clip ); @@ -40,3 +45,6 @@ Object.assign( THREE.AnimationLoader.prototype, { } } ); + + +export { AnimationLoader }; \ No newline at end of file diff --git a/src/loaders/AudioLoader.js b/src/loaders/AudioLoader.js index ebaff2ee6fac72..8f0573b079c782 100644 --- a/src/loaders/AudioLoader.js +++ b/src/loaders/AudioLoader.js @@ -1,22 +1,27 @@ +import { getAudioContext } from '../audio/AudioContext'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author Reece Aaron Lecrivain / http://reecenotes.com/ */ -THREE.AudioLoader = function ( manager ) { +function AudioLoader ( manager ) { + this.isAudioLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.AudioLoader.prototype, { +Object.assign( AudioLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { - var loader = new THREE.XHRLoader( this.manager ); + var loader = new XHRLoader( this.manager ); loader.setResponseType( 'arraybuffer' ); loader.load( url, function ( buffer ) { - var context = THREE.AudioContext; + var context = getAudioContext(); context.decodeAudioData( buffer, function ( audioBuffer ) { @@ -29,3 +34,6 @@ Object.assign( THREE.AudioLoader.prototype, { } } ); + + +export { AudioLoader }; \ No newline at end of file diff --git a/src/loaders/BinaryTextureLoader.js b/src/loaders/BinaryTextureLoader.js index d0062d96f73e77..be22309b98186e 100644 --- a/src/loaders/BinaryTextureLoader.js +++ b/src/loaders/BinaryTextureLoader.js @@ -1,27 +1,33 @@ +import { LinearFilter, LinearMipMapLinearFilter, ClampToEdgeWrapping } from '../constants'; +import { XHRLoader } from './XHRLoader'; +import { DataTexture } from '../textures/DataTexture'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author Nikos M. / https://github.com/foo123/ * * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) */ -THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) { +var DataTextureLoader = BinaryTextureLoader; +function BinaryTextureLoader ( manager ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; // override in sub classes this._parser = null; }; -Object.assign( THREE.BinaryTextureLoader.prototype, { +Object.assign( BinaryTextureLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var texture = new THREE.DataTexture(); + var texture = new DataTexture(); - var loader = new THREE.XHRLoader( this.manager ); + var loader = new XHRLoader( this.manager ); loader.setResponseType( 'arraybuffer' ); loader.load( url, function ( buffer ) { @@ -42,11 +48,11 @@ Object.assign( THREE.BinaryTextureLoader.prototype, { } - texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping; - texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping; + texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping; - texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter; - texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter; + texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter; + texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter; texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; @@ -69,7 +75,7 @@ Object.assign( THREE.BinaryTextureLoader.prototype, { if ( 1 === texData.mipmapCount ) { - texture.minFilter = THREE.LinearFilter; + texture.minFilter = LinearFilter; } @@ -85,3 +91,6 @@ Object.assign( THREE.BinaryTextureLoader.prototype, { } } ); + + +export { BinaryTextureLoader, DataTextureLoader }; \ No newline at end of file diff --git a/src/loaders/BufferGeometryLoader.js b/src/loaders/BufferGeometryLoader.js index 120d2b2bdaa17e..06edbc7699a51a 100644 --- a/src/loaders/BufferGeometryLoader.js +++ b/src/loaders/BufferGeometryLoader.js @@ -1,20 +1,28 @@ +import { Sphere } from '../math/Sphere'; +import { Vector3 } from '../math/Vector3'; +import { BufferAttribute } from '../core/BufferAttribute'; +import { BufferGeometry } from '../core/BufferGeometry'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.BufferGeometryLoader = function ( manager ) { +function BufferGeometryLoader ( manager ) { + this.isBufferGeometryLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.BufferGeometryLoader.prototype, { +Object.assign( BufferGeometryLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var loader = new THREE.XHRLoader( scope.manager ); + var loader = new XHRLoader( scope.manager ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); @@ -25,7 +33,7 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { parse: function ( json ) { - var geometry = new THREE.BufferGeometry(); + var geometry = new BufferGeometry(); var index = json.data.index; @@ -44,7 +52,7 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { if ( index !== undefined ) { var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); - geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); } @@ -55,7 +63,7 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { var attribute = attributes[ key ]; var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); - geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); + geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); } @@ -77,7 +85,7 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { if ( boundingSphere !== undefined ) { - var center = new THREE.Vector3(); + var center = new Vector3(); if ( boundingSphere.center !== undefined ) { @@ -85,7 +93,7 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { } - geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius ); + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); } @@ -94,3 +102,6 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { } } ); + + +export { BufferGeometryLoader }; \ No newline at end of file diff --git a/src/loaders/Cache.js b/src/loaders/Cache.js index 081efd99d263e8..d8172f547126d7 100644 --- a/src/loaders/Cache.js +++ b/src/loaders/Cache.js @@ -1,8 +1,10 @@ +var Cache; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Cache = { +Cache = { enabled: false, @@ -41,3 +43,6 @@ THREE.Cache = { } }; + + +export { Cache }; \ No newline at end of file diff --git a/src/loaders/CompressedTextureLoader.js b/src/loaders/CompressedTextureLoader.js index 9bd1d082e760c0..de47f67431aef6 100644 --- a/src/loaders/CompressedTextureLoader.js +++ b/src/loaders/CompressedTextureLoader.js @@ -1,19 +1,25 @@ +import { LinearFilter } from '../constants'; +import { XHRLoader } from './XHRLoader'; +import { CompressedTexture } from '../textures/CompressedTexture'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ * * Abstract Base class to block based textures loader (dds, pvr, ...) */ -THREE.CompressedTextureLoader = function ( manager ) { +function CompressedTextureLoader ( manager ) { + this.isCompressedTextureLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; // override in sub classes this._parser = null; }; -Object.assign( THREE.CompressedTextureLoader.prototype, { +Object.assign( CompressedTextureLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { @@ -21,10 +27,10 @@ Object.assign( THREE.CompressedTextureLoader.prototype, { var images = []; - var texture = new THREE.CompressedTexture(); + var texture = new CompressedTexture(); texture.image = images; - var loader = new THREE.XHRLoader( this.manager ); + var loader = new XHRLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); @@ -46,7 +52,7 @@ Object.assign( THREE.CompressedTextureLoader.prototype, { if ( loaded === 6 ) { if ( texDatas.mipmapCount === 1 ) - texture.minFilter = THREE.LinearFilter; + texture.minFilter = LinearFilter; texture.format = texDatas.format; texture.needsUpdate = true; @@ -106,7 +112,7 @@ Object.assign( THREE.CompressedTextureLoader.prototype, { if ( texDatas.mipmapCount === 1 ) { - texture.minFilter = THREE.LinearFilter; + texture.minFilter = LinearFilter; } @@ -131,3 +137,6 @@ Object.assign( THREE.CompressedTextureLoader.prototype, { } } ); + + +export { CompressedTextureLoader }; \ No newline at end of file diff --git a/src/loaders/CubeTextureLoader.js b/src/loaders/CubeTextureLoader.js index 22c57532a2f64c..3adf142ec98a7f 100644 --- a/src/loaders/CubeTextureLoader.js +++ b/src/loaders/CubeTextureLoader.js @@ -1,20 +1,25 @@ +import { ImageLoader } from './ImageLoader'; +import { CubeTexture } from '../textures/CubeTexture'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.CubeTextureLoader = function ( manager ) { +function CubeTextureLoader ( manager ) { + this.isCubeTextureLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.CubeTextureLoader.prototype, { +Object.assign( CubeTextureLoader.prototype, { load: function ( urls, onLoad, onProgress, onError ) { - var texture = new THREE.CubeTexture(); + var texture = new CubeTexture(); - var loader = new THREE.ImageLoader( this.manager ); + var loader = new ImageLoader( this.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.setPath( this.path ); @@ -65,3 +70,6 @@ Object.assign( THREE.CubeTextureLoader.prototype, { } } ); + + +export { CubeTextureLoader }; \ No newline at end of file diff --git a/src/loaders/FontLoader.js b/src/loaders/FontLoader.js index 8115ee357c224f..d4f0a5b310c94a 100644 --- a/src/loaders/FontLoader.js +++ b/src/loaders/FontLoader.js @@ -1,20 +1,25 @@ +import { Font } from '../extras/core/Font'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.FontLoader = function ( manager ) { +function FontLoader ( manager ) { + this.isFontLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.FontLoader.prototype, { +Object.assign( FontLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var loader = new THREE.XHRLoader( this.manager ); + var loader = new XHRLoader( this.manager ); loader.load( url, function ( text ) { var json; @@ -40,8 +45,11 @@ Object.assign( THREE.FontLoader.prototype, { parse: function ( json ) { - return new THREE.Font( json ); + return new Font( json ); } } ); + + +export { FontLoader }; \ No newline at end of file diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index d4e7989ffce6af..2b870a00c205a1 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -1,14 +1,18 @@ +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.ImageLoader = function ( manager ) { +function ImageLoader ( manager ) { + this.isImageLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.ImageLoader.prototype, { +Object.assign( ImageLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { @@ -31,7 +35,7 @@ Object.assign( THREE.ImageLoader.prototype, { } else { - var loader = new THREE.XHRLoader(); + var loader = new XHRLoader(); loader.setPath( this.path ); loader.setResponseType( 'blob' ); loader.load( url, function ( blob ) { @@ -63,3 +67,6 @@ Object.assign( THREE.ImageLoader.prototype, { } } ); + + +export { ImageLoader }; \ No newline at end of file diff --git a/src/loaders/JSONLoader.js b/src/loaders/JSONLoader.js index 06c656ed129c7a..a7d932e3012523 100644 --- a/src/loaders/JSONLoader.js +++ b/src/loaders/JSONLoader.js @@ -1,9 +1,21 @@ +import { Loader } from './Loader'; +import { AnimationClip } from '../animation/AnimationClip'; +import { Vector3 } from '../math/Vector3'; +import { Vector4 } from '../math/Vector4'; +import { Color } from '../math/Color'; +import { Vector2 } from '../math/Vector2'; +import { Face3 } from '../core/Face3'; +import { Geometry } from '../core/Geometry'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.JSONLoader = function ( manager ) { +function JSONLoader ( manager ) { + this.isJSONLoader = true; if ( typeof manager === 'boolean' ) { @@ -12,21 +24,21 @@ THREE.JSONLoader = function ( manager ) { } - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; this.withCredentials = false; }; -Object.assign( THREE.JSONLoader.prototype, { +Object.assign( JSONLoader.prototype, { load: function( url, onLoad, onProgress, onError ) { var scope = this; - var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url ); + var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url ); - var loader = new THREE.XHRLoader( this.manager ); + var loader = new XHRLoader( this.manager ); loader.setWithCredentials( this.withCredentials ); loader.load( url, function ( text ) { @@ -72,7 +84,7 @@ Object.assign( THREE.JSONLoader.prototype, { parse: function ( json, texturePath ) { - var geometry = new THREE.Geometry(), + var geometry = new Geometry(), scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; parseModel( scale ); @@ -139,7 +151,7 @@ Object.assign( THREE.JSONLoader.prototype, { while ( offset < zLength ) { - vertex = new THREE.Vector3(); + vertex = new Vector3(); vertex.x = vertices[ offset ++ ] * scale; vertex.y = vertices[ offset ++ ] * scale; @@ -169,12 +181,12 @@ Object.assign( THREE.JSONLoader.prototype, { if ( isQuad ) { - faceA = new THREE.Face3(); + faceA = new Face3(); faceA.a = faces[ offset ]; faceA.b = faces[ offset + 1 ]; faceA.c = faces[ offset + 3 ]; - faceB = new THREE.Face3(); + faceB = new Face3(); faceB.a = faces[ offset + 1 ]; faceB.b = faces[ offset + 2 ]; faceB.c = faces[ offset + 3 ]; @@ -209,7 +221,7 @@ Object.assign( THREE.JSONLoader.prototype, { u = uvLayer[ uvIndex * 2 ]; v = uvLayer[ uvIndex * 2 + 1 ]; - uv = new THREE.Vector2( u, v ); + uv = new Vector2( u, v ); if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); @@ -240,7 +252,7 @@ Object.assign( THREE.JSONLoader.prototype, { normalIndex = faces[ offset ++ ] * 3; - normal = new THREE.Vector3( + normal = new Vector3( normals[ normalIndex ++ ], normals[ normalIndex ++ ], normals[ normalIndex ] @@ -273,8 +285,8 @@ Object.assign( THREE.JSONLoader.prototype, { colorIndex = faces[ offset ++ ]; hex = colors[ colorIndex ]; - if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); - if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); + if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) ); + if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) ); } @@ -285,7 +297,7 @@ Object.assign( THREE.JSONLoader.prototype, { } else { - face = new THREE.Face3(); + face = new Face3(); face.a = faces[ offset ++ ]; face.b = faces[ offset ++ ]; face.c = faces[ offset ++ ]; @@ -316,7 +328,7 @@ Object.assign( THREE.JSONLoader.prototype, { u = uvLayer[ uvIndex * 2 ]; v = uvLayer[ uvIndex * 2 + 1 ]; - uv = new THREE.Vector2( u, v ); + uv = new Vector2( u, v ); geometry.faceVertexUvs[ i ][ fi ].push( uv ); @@ -344,7 +356,7 @@ Object.assign( THREE.JSONLoader.prototype, { normalIndex = faces[ offset ++ ] * 3; - normal = new THREE.Vector3( + normal = new Vector3( normals[ normalIndex ++ ], normals[ normalIndex ++ ], normals[ normalIndex ] @@ -370,7 +382,7 @@ Object.assign( THREE.JSONLoader.prototype, { for ( i = 0; i < 3; i ++ ) { colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); + face.vertexColors.push( new Color( colors[ colorIndex ] ) ); } @@ -397,7 +409,7 @@ Object.assign( THREE.JSONLoader.prototype, { var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; - geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) ); + geometry.skinWeights.push( new Vector4( x, y, z, w ) ); } @@ -412,7 +424,7 @@ Object.assign( THREE.JSONLoader.prototype, { var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; - geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) ); + geometry.skinIndices.push( new Vector4( a, b, c, d ) ); } @@ -444,7 +456,7 @@ Object.assign( THREE.JSONLoader.prototype, { for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) { - var vertex = new THREE.Vector3(); + var vertex = new Vector3(); vertex.x = srcVertices[ v ] * scale; vertex.y = srcVertices[ v + 1 ] * scale; vertex.z = srcVertices[ v + 2 ] * scale; @@ -503,7 +515,7 @@ Object.assign( THREE.JSONLoader.prototype, { for ( var i = 0; i < animations.length; i ++ ) { - var clip = THREE.AnimationClip.parseAnimation( animations[ i ], geometry.bones ); + var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones ); if ( clip ) outputAnimations.push( clip ); } @@ -512,7 +524,7 @@ Object.assign( THREE.JSONLoader.prototype, { if ( geometry.morphTargets ) { // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary. - var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); + var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); outputAnimations = outputAnimations.concat( morphAnimationClips ); } @@ -527,7 +539,7 @@ Object.assign( THREE.JSONLoader.prototype, { } else { - var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); + var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); return { geometry: geometry, materials: materials }; @@ -536,3 +548,6 @@ Object.assign( THREE.JSONLoader.prototype, { } } ); + + +export { JSONLoader }; \ No newline at end of file diff --git a/src/loaders/Loader.js b/src/loaders/Loader.js index 04162b65410e64..a08db2eaa05c4b 100644 --- a/src/loaders/Loader.js +++ b/src/loaders/Loader.js @@ -1,8 +1,15 @@ +import { FaceColors, VertexColors, DoubleSide, BackSide, MirroredRepeatWrapping, RepeatWrapping } from '../constants'; +import { _Math } from '../math/Math'; +import { MaterialLoader } from './MaterialLoader'; +import { TextureLoader } from './TextureLoader'; +import { Color } from '../math/Color'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.Loader = function () { +function Loader () { + this.isLoader = true; this.onLoadStart = function () {}; this.onLoadProgress = function () {}; @@ -10,9 +17,9 @@ THREE.Loader = function () { }; -THREE.Loader.prototype = { +Loader.prototype = { - constructor: THREE.Loader, + constructor: Loader, crossOrigin: undefined, @@ -48,9 +55,9 @@ THREE.Loader.prototype = { return function createMaterial( m, texturePath, crossOrigin ) { - if ( color === undefined ) color = new THREE.Color(); - if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader(); - if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader(); + if ( color === undefined ) color = new Color(); + if ( textureLoader === undefined ) textureLoader = new TextureLoader(); + if ( materialLoader === undefined ) materialLoader = new MaterialLoader(); // convert from old material format @@ -59,7 +66,7 @@ THREE.Loader.prototype = { function loadTexture( path, repeat, offset, wrap, anisotropy ) { var fullPath = texturePath + path; - var loader = THREE.Loader.Handlers.get( fullPath ); + var loader = Loader.Handlers.get( fullPath ); var texture; @@ -78,8 +85,8 @@ THREE.Loader.prototype = { texture.repeat.fromArray( repeat ); - if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; + if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping; + if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping; } @@ -91,11 +98,11 @@ THREE.Loader.prototype = { if ( wrap !== undefined ) { - if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping; - if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping; + if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping; + if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping; - if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping; - if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping; + if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping; + if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping; } @@ -105,7 +112,7 @@ THREE.Loader.prototype = { } - var uuid = THREE.Math.generateUUID(); + var uuid = _Math.generateUUID(); textures[ uuid ] = texture; @@ -116,7 +123,7 @@ THREE.Loader.prototype = { // var json = { - uuid: THREE.Math.generateUUID(), + uuid: _Math.generateUUID(), type: 'MeshLambertMaterial' }; @@ -244,10 +251,10 @@ THREE.Loader.prototype = { case 'mapAlphaAnisotropy': break; case 'flipSided': - json.side = THREE.BackSide; + json.side = BackSide; break; case 'doubleSided': - json.side = THREE.DoubleSide; + json.side = DoubleSide; break; case 'transparency': console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' ); @@ -264,8 +271,8 @@ THREE.Loader.prototype = { json[ name ] = value; break; case 'vertexColors': - if ( value === true ) json.vertexColors = THREE.VertexColors; - if ( value === 'face' ) json.vertexColors = THREE.FaceColors; + if ( value === true ) json.vertexColors = VertexColors; + if ( value === 'face' ) json.vertexColors = FaceColors; break; default: console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); @@ -289,7 +296,7 @@ THREE.Loader.prototype = { }; -THREE.Loader.Handlers = { +Loader.Handlers = { handlers: [], @@ -321,3 +328,6 @@ THREE.Loader.Handlers = { } }; + + +export { Loader }; \ No newline at end of file diff --git a/src/loaders/LoadingManager.js b/src/loaders/LoadingManager.js index 72a14cc40d44e5..42a85e83898467 100644 --- a/src/loaders/LoadingManager.js +++ b/src/loaders/LoadingManager.js @@ -1,8 +1,11 @@ +var DefaultLoadingManager; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.LoadingManager = function ( onLoad, onProgress, onError ) { +function LoadingManager ( onLoad, onProgress, onError ) { + this.isLoadingManager = true; var scope = this; @@ -67,4 +70,7 @@ THREE.LoadingManager = function ( onLoad, onProgress, onError ) { }; -THREE.DefaultLoadingManager = new THREE.LoadingManager(); +DefaultLoadingManager = new LoadingManager(); + + +export { DefaultLoadingManager, LoadingManager }; \ No newline at end of file diff --git a/src/loaders/MaterialLoader.js b/src/loaders/MaterialLoader.js index 171fcb59ea9126..1d63fabf7e9102 100644 --- a/src/loaders/MaterialLoader.js +++ b/src/loaders/MaterialLoader.js @@ -1,21 +1,27 @@ +import { MultiplyOperation } from '../constants'; +import { Vector2 } from '../math/Vector2'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.MaterialLoader = function ( manager ) { +function MaterialLoader ( manager ) { + this.isMaterialLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; this.textures = {}; }; -Object.assign( THREE.MaterialLoader.prototype, { +Object.assign( MaterialLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var loader = new THREE.XHRLoader( scope.manager ); + var loader = new XHRLoader( scope.manager ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); @@ -103,7 +109,7 @@ Object.assign( THREE.MaterialLoader.prototype, { } - material.normalScale = new THREE.Vector2().fromArray( normalScale ); + material.normalScale = new Vector2().fromArray( normalScale ); } @@ -122,7 +128,7 @@ Object.assign( THREE.MaterialLoader.prototype, { if ( json.envMap !== undefined ) { material.envMap = this.getTexture( json.envMap ); - material.combine = THREE.MultiplyOperation; + material.combine = MultiplyOperation; } @@ -151,3 +157,6 @@ Object.assign( THREE.MaterialLoader.prototype, { } } ); + + +export { MaterialLoader }; \ No newline at end of file diff --git a/src/loaders/ObjectLoader.js b/src/loaders/ObjectLoader.js old mode 100755 new mode 100644 index a5d68991609af9..26380f883969b3 --- a/src/loaders/ObjectLoader.js +++ b/src/loaders/ObjectLoader.js @@ -1,15 +1,42 @@ +import { Matrix4 } from '../math/Matrix4'; +import { Object3D } from '../core/Object3D'; +import { Group } from '../objects/Group'; +import { Sprite } from '../objects/Sprite'; +import { Points } from '../objects/Points'; +import { Line } from '../objects/Line'; +import { LOD } from '../objects/LOD'; +import { Mesh } from '../objects/Mesh'; +import { SkinnedMesh } from '../objects/SkinnedMesh'; +import { HemisphereLight } from '../lights/HemisphereLight'; +import { SpotLight } from '../lights/SpotLight'; +import { PointLight } from '../lights/PointLight'; +import { DirectionalLight } from '../lights/DirectionalLight'; +import { AmbientLight } from '../lights/AmbientLight'; +import { OrthographicCamera } from '../cameras/OrthographicCamera'; +import { PerspectiveCamera } from '../cameras/PerspectiveCamera'; +import { Scene } from '../scenes/Scene'; +import { Texture } from '../textures/Texture'; +import { ImageLoader } from './ImageLoader'; +import { LoadingManager, DefaultLoadingManager } from './LoadingManager'; +import { AnimationClip } from '../animation/AnimationClip'; +import { MaterialLoader } from './MaterialLoader'; +import { BufferGeometryLoader } from './BufferGeometryLoader'; +import { JSONLoader } from './JSONLoader'; +import { XHRLoader } from './XHRLoader'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.ObjectLoader = function ( manager ) { +function ObjectLoader ( manager ) { + this.isObjectLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; this.texturePath = ''; }; -Object.assign( THREE.ObjectLoader.prototype, { +Object.assign( ObjectLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { @@ -21,7 +48,7 @@ Object.assign( THREE.ObjectLoader.prototype, { var scope = this; - var loader = new THREE.XHRLoader( scope.manager ); + var loader = new XHRLoader( scope.manager ); loader.load( url, function ( text ) { scope.parse( JSON.parse( text ), onLoad ); @@ -79,8 +106,8 @@ Object.assign( THREE.ObjectLoader.prototype, { if ( json !== undefined ) { - var geometryLoader = new THREE.JSONLoader(); - var bufferGeometryLoader = new THREE.BufferGeometryLoader(); + var geometryLoader = new JSONLoader(); + var bufferGeometryLoader = new BufferGeometryLoader(); for ( var i = 0, l = json.length; i < l; i ++ ) { @@ -279,7 +306,7 @@ Object.assign( THREE.ObjectLoader.prototype, { if ( json !== undefined ) { - var loader = new THREE.MaterialLoader(); + var loader = new MaterialLoader(); loader.setTextures( textures ); for ( var i = 0, l = json.length; i < l; i ++ ) { @@ -301,7 +328,7 @@ Object.assign( THREE.ObjectLoader.prototype, { for ( var i = 0; i < json.length; i ++ ) { - var clip = THREE.AnimationClip.parse( json[ i ] ); + var clip = AnimationClip.parse( json[ i ] ); animations.push( clip ); @@ -330,9 +357,9 @@ Object.assign( THREE.ObjectLoader.prototype, { if ( json !== undefined && json.length > 0 ) { - var manager = new THREE.LoadingManager( onLoad ); + var manager = new LoadingManager( onLoad ); - var loader = new THREE.ImageLoader( manager ); + var loader = new ImageLoader( manager ); loader.setCrossOrigin( this.crossOrigin ); for ( var i = 0, l = json.length; i < l; i ++ ) { @@ -382,7 +409,7 @@ Object.assign( THREE.ObjectLoader.prototype, { } - var texture = new THREE.Texture( images[ data.image ] ); + var texture = new Texture( images[ data.image ] ); texture.needsUpdate = true; texture.uuid = data.uuid; @@ -418,7 +445,7 @@ Object.assign( THREE.ObjectLoader.prototype, { parseObject: function () { - var matrix = new THREE.Matrix4(); + var matrix = new Matrix4(); return function parseObject( data, geometries, materials ) { @@ -454,13 +481,13 @@ Object.assign( THREE.ObjectLoader.prototype, { case 'Scene': - object = new THREE.Scene(); + object = new Scene(); break; case 'PerspectiveCamera': - object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); if ( data.focus !== undefined ) object.focus = data.focus; if ( data.zoom !== undefined ) object.zoom = data.zoom; @@ -472,37 +499,37 @@ Object.assign( THREE.ObjectLoader.prototype, { case 'OrthographicCamera': - object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); break; case 'AmbientLight': - object = new THREE.AmbientLight( data.color, data.intensity ); + object = new AmbientLight( data.color, data.intensity ); break; case 'DirectionalLight': - object = new THREE.DirectionalLight( data.color, data.intensity ); + object = new DirectionalLight( data.color, data.intensity ); break; case 'PointLight': - object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay ); + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); break; case 'SpotLight': - object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); break; case 'HemisphereLight': - object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); break; @@ -513,11 +540,11 @@ Object.assign( THREE.ObjectLoader.prototype, { if ( geometry.bones && geometry.bones.length > 0 ) { - object = new THREE.SkinnedMesh( geometry, material ); + object = new SkinnedMesh( geometry, material ); } else { - object = new THREE.Mesh( geometry, material ); + object = new Mesh( geometry, material ); } @@ -525,38 +552,38 @@ Object.assign( THREE.ObjectLoader.prototype, { case 'LOD': - object = new THREE.LOD(); + object = new LOD(); break; case 'Line': - object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); break; case 'PointCloud': case 'Points': - object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); break; case 'Sprite': - object = new THREE.Sprite( getMaterial( data.material ) ); + object = new Sprite( getMaterial( data.material ) ); break; case 'Group': - object = new THREE.Group(); + object = new Group(); break; default: - object = new THREE.Object3D(); + object = new Object3D(); } @@ -618,3 +645,6 @@ Object.assign( THREE.ObjectLoader.prototype, { }() } ); + + +export { ObjectLoader }; \ No newline at end of file diff --git a/src/loaders/TextureLoader.js b/src/loaders/TextureLoader.js index c81645c64ab64f..4721d255fd4608 100644 --- a/src/loaders/TextureLoader.js +++ b/src/loaders/TextureLoader.js @@ -1,20 +1,26 @@ +import { RGBAFormat, RGBFormat } from '../constants'; +import { ImageLoader } from './ImageLoader'; +import { Texture } from '../textures/Texture'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.TextureLoader = function ( manager ) { +function TextureLoader ( manager ) { + this.isTextureLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.TextureLoader.prototype, { +Object.assign( TextureLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { - var texture = new THREE.Texture(); + var texture = new Texture(); - var loader = new THREE.ImageLoader( this.manager ); + var loader = new ImageLoader( this.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.setPath( this.path ); loader.load( url, function ( image ) { @@ -22,7 +28,7 @@ Object.assign( THREE.TextureLoader.prototype, { // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; - texture.format = isJPEG ? THREE.RGBFormat : THREE.RGBAFormat; + texture.format = isJPEG ? RGBFormat : RGBAFormat; texture.image = image; texture.needsUpdate = true; @@ -53,3 +59,6 @@ Object.assign( THREE.TextureLoader.prototype, { } } ); + + +export { TextureLoader }; \ No newline at end of file diff --git a/src/loaders/XHRLoader.js b/src/loaders/XHRLoader.js index cddb0290cc49ae..85f48769d03278 100644 --- a/src/loaders/XHRLoader.js +++ b/src/loaders/XHRLoader.js @@ -1,14 +1,18 @@ +import { Cache } from './Cache'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.XHRLoader = function ( manager ) { +function XHRLoader ( manager ) { + this.isXHRLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.XHRLoader.prototype, { +Object.assign( XHRLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { @@ -16,7 +20,7 @@ Object.assign( THREE.XHRLoader.prototype, { var scope = this; - var cached = THREE.Cache.get( url ); + var cached = Cache.get( url ); if ( cached !== undefined ) { @@ -42,7 +46,7 @@ Object.assign( THREE.XHRLoader.prototype, { var response = event.target.response; - THREE.Cache.add( url, response ); + Cache.add( url, response ); if ( this.status === 200 ) { @@ -122,3 +126,6 @@ Object.assign( THREE.XHRLoader.prototype, { } } ); + + +export { XHRLoader }; \ No newline at end of file diff --git a/src/materials/LineBasicMaterial.js b/src/materials/LineBasicMaterial.js index 06fd3bbd6b381b..3bbd876b9da2af 100644 --- a/src/materials/LineBasicMaterial.js +++ b/src/materials/LineBasicMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -12,13 +15,14 @@ * } */ -THREE.LineBasicMaterial = function ( parameters ) { +function LineBasicMaterial ( parameters ) { + this.isLineBasicMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'LineBasicMaterial'; - this.color = new THREE.Color( 0xffffff ); + this.color = new Color( 0xffffff ); this.linewidth = 1; this.linecap = 'round'; @@ -30,12 +34,12 @@ THREE.LineBasicMaterial = function ( parameters ) { }; -THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial; +LineBasicMaterial.prototype = Object.create( Material.prototype ); +LineBasicMaterial.prototype.constructor = LineBasicMaterial; -THREE.LineBasicMaterial.prototype.copy = function ( source ) { +LineBasicMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); @@ -46,3 +50,6 @@ THREE.LineBasicMaterial.prototype.copy = function ( source ) { return this; }; + + +export { LineBasicMaterial }; \ No newline at end of file diff --git a/src/materials/LineDashedMaterial.js b/src/materials/LineDashedMaterial.js index 26b2e304cbfd30..331b35b5aaa7e7 100644 --- a/src/materials/LineDashedMaterial.js +++ b/src/materials/LineDashedMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { Color } from '../math/Color'; + /** * @author alteredq / http://alteredqualia.com/ * @@ -13,13 +16,14 @@ * } */ -THREE.LineDashedMaterial = function ( parameters ) { +function LineDashedMaterial ( parameters ) { + this.isLineDashedMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'LineDashedMaterial'; - this.color = new THREE.Color( 0xffffff ); + this.color = new Color( 0xffffff ); this.linewidth = 1; @@ -33,12 +37,12 @@ THREE.LineDashedMaterial = function ( parameters ) { }; -THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial; +LineDashedMaterial.prototype = Object.create( Material.prototype ); +LineDashedMaterial.prototype.constructor = LineDashedMaterial; -THREE.LineDashedMaterial.prototype.copy = function ( source ) { +LineDashedMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); @@ -51,3 +55,6 @@ THREE.LineDashedMaterial.prototype.copy = function ( source ) { return this; }; + + +export { LineDashedMaterial }; \ No newline at end of file diff --git a/src/materials/Material.js b/src/materials/Material.js index 028b87a2fcaa9e..0648f315a10ce7 100644 --- a/src/materials/Material.js +++ b/src/materials/Material.js @@ -1,13 +1,18 @@ +import { EventDispatcher } from '../core/EventDispatcher'; +import { NoColors, FrontSide, SmoothShading, NormalBlending, LessEqualDepth, AddEquation, OneMinusSrcAlphaFactor, SrcAlphaFactor } from '../constants'; +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Material = function () { +function Material () { + this.isMaterial = true; - Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } ); + Object.defineProperty( this, 'id', { value: MaterialIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'Material'; @@ -15,22 +20,22 @@ THREE.Material = function () { this.fog = true; this.lights = true; - this.blending = THREE.NormalBlending; - this.side = THREE.FrontSide; - this.shading = THREE.SmoothShading; // THREE.FlatShading, THREE.SmoothShading - this.vertexColors = THREE.NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors + this.blending = NormalBlending; + this.side = FrontSide; + this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading + this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors this.opacity = 1; this.transparent = false; - this.blendSrc = THREE.SrcAlphaFactor; - this.blendDst = THREE.OneMinusSrcAlphaFactor; - this.blendEquation = THREE.AddEquation; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; this.blendSrcAlpha = null; this.blendDstAlpha = null; this.blendEquationAlpha = null; - this.depthFunc = THREE.LessEqualDepth; + this.depthFunc = LessEqualDepth; this.depthTest = true; this.depthWrite = true; @@ -56,9 +61,9 @@ THREE.Material = function () { }; -THREE.Material.prototype = { +Material.prototype = { - constructor: THREE.Material, + constructor: Material, get needsUpdate() { @@ -97,11 +102,11 @@ THREE.Material.prototype = { } - if ( currentValue instanceof THREE.Color ) { + if ( (currentValue && currentValue.isColor) ) { currentValue.set( newValue ); - } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) { + } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) { currentValue.copy( newValue ); @@ -147,44 +152,44 @@ THREE.Material.prototype = { if ( this.name !== '' ) data.name = this.name; - if ( this.color instanceof THREE.Color ) data.color = this.color.getHex(); + if ( (this.color && this.color.isColor) ) data.color = this.color.getHex(); if ( this.roughness !== undefined ) data.roughness = this.roughness; if ( this.metalness !== undefined ) data.metalness = this.metalness; - if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex(); - if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex(); + if ( (this.emissive && this.emissive.isColor) ) data.emissive = this.emissive.getHex(); + if ( (this.specular && this.specular.isColor) ) data.specular = this.specular.getHex(); if ( this.shininess !== undefined ) data.shininess = this.shininess; - if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid; - if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; - if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid; - if ( this.bumpMap instanceof THREE.Texture ) { + if ( (this.map && this.map.isTexture) ) data.map = this.map.toJSON( meta ).uuid; + if ( (this.alphaMap && this.alphaMap.isTexture) ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + if ( (this.lightMap && this.lightMap.isTexture) ) data.lightMap = this.lightMap.toJSON( meta ).uuid; + if ( (this.bumpMap && this.bumpMap.isTexture) ) { data.bumpMap = this.bumpMap.toJSON( meta ).uuid; data.bumpScale = this.bumpScale; } - if ( this.normalMap instanceof THREE.Texture ) { + if ( (this.normalMap && this.normalMap.isTexture) ) { data.normalMap = this.normalMap.toJSON( meta ).uuid; data.normalScale = this.normalScale.toArray(); } - if ( this.displacementMap instanceof THREE.Texture ) { + if ( (this.displacementMap && this.displacementMap.isTexture) ) { data.displacementMap = this.displacementMap.toJSON( meta ).uuid; data.displacementScale = this.displacementScale; data.displacementBias = this.displacementBias; } - if ( this.roughnessMap instanceof THREE.Texture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; - if ( this.metalnessMap instanceof THREE.Texture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; + if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; + if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; - if ( this.emissiveMap instanceof THREE.Texture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; - if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid; + if ( (this.emissiveMap && this.emissiveMap.isTexture) ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; + if ( (this.specularMap && this.specularMap.isTexture) ) data.specularMap = this.specularMap.toJSON( meta ).uuid; - if ( this.envMap instanceof THREE.Texture ) { + if ( (this.envMap && this.envMap.isTexture) ) { data.envMap = this.envMap.toJSON( meta ).uuid; data.reflectivity = this.reflectivity; // Scale behind envMap @@ -194,10 +199,10 @@ THREE.Material.prototype = { if ( this.size !== undefined ) data.size = this.size; if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; - if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending; - if ( this.shading !== THREE.SmoothShading ) data.shading = this.shading; - if ( this.side !== THREE.FrontSide ) data.side = this.side; - if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors; + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.shading !== SmoothShading ) data.shading = this.shading; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors; if ( this.opacity < 1 ) data.opacity = this.opacity; if ( this.transparent === true ) data.transparent = this.transparent; @@ -320,6 +325,10 @@ THREE.Material.prototype = { }; -Object.assign( THREE.Material.prototype, THREE.EventDispatcher.prototype ); +Object.assign( Material.prototype, EventDispatcher.prototype ); + +var count = 0; +function MaterialIdCount () { return count++; }; + -THREE.MaterialIdCount = 0; +export { MaterialIdCount, Material }; \ No newline at end of file diff --git a/src/materials/MeshBasicMaterial.js b/src/materials/MeshBasicMaterial.js index ef1dd3ab9358c5..b220b26e79e968 100644 --- a/src/materials/MeshBasicMaterial.js +++ b/src/materials/MeshBasicMaterial.js @@ -1,3 +1,7 @@ +import { Material } from './Material'; +import { MultiplyOperation } from '../constants'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -31,13 +35,14 @@ * } */ -THREE.MeshBasicMaterial = function ( parameters ) { +function MeshBasicMaterial ( parameters ) { + this.isMeshBasicMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'MeshBasicMaterial'; - this.color = new THREE.Color( 0xffffff ); // emissive + this.color = new Color( 0xffffff ); // emissive this.map = null; @@ -49,7 +54,7 @@ THREE.MeshBasicMaterial = function ( parameters ) { this.alphaMap = null; this.envMap = null; - this.combine = THREE.MultiplyOperation; + this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -67,12 +72,12 @@ THREE.MeshBasicMaterial = function ( parameters ) { }; -THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial; +MeshBasicMaterial.prototype = Object.create( Material.prototype ); +MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; -THREE.MeshBasicMaterial.prototype.copy = function ( source ) { +MeshBasicMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); @@ -101,3 +106,6 @@ THREE.MeshBasicMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshBasicMaterial }; \ No newline at end of file diff --git a/src/materials/MeshDepthMaterial.js b/src/materials/MeshDepthMaterial.js index 0813dc2a563fa7..915969064ca712 100644 --- a/src/materials/MeshDepthMaterial.js +++ b/src/materials/MeshDepthMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { BasicDepthPacking } from '../constants'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -21,13 +24,14 @@ * } */ -THREE.MeshDepthMaterial = function ( parameters ) { +function MeshDepthMaterial ( parameters ) { + this.isMeshDepthMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'MeshDepthMaterial'; - this.depthPacking = THREE.BasicDepthPacking; + this.depthPacking = BasicDepthPacking; this.skinning = false; this.morphTargets = false; @@ -50,12 +54,12 @@ THREE.MeshDepthMaterial = function ( parameters ) { }; -THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial; +MeshDepthMaterial.prototype = Object.create( Material.prototype ); +MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; -THREE.MeshDepthMaterial.prototype.copy = function ( source ) { +MeshDepthMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.depthPacking = source.depthPacking; @@ -76,3 +80,6 @@ THREE.MeshDepthMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshDepthMaterial }; \ No newline at end of file diff --git a/src/materials/MeshLambertMaterial.js b/src/materials/MeshLambertMaterial.js index 6ea4094f69c3c6..915ed026059952 100644 --- a/src/materials/MeshLambertMaterial.js +++ b/src/materials/MeshLambertMaterial.js @@ -1,3 +1,7 @@ +import { Material } from './Material'; +import { MultiplyOperation } from '../constants'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -36,13 +40,14 @@ * } */ -THREE.MeshLambertMaterial = function ( parameters ) { +function MeshLambertMaterial ( parameters ) { + this.isMeshLambertMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'MeshLambertMaterial'; - this.color = new THREE.Color( 0xffffff ); // diffuse + this.color = new Color( 0xffffff ); // diffuse this.map = null; @@ -52,7 +57,7 @@ THREE.MeshLambertMaterial = function ( parameters ) { this.aoMap = null; this.aoMapIntensity = 1.0; - this.emissive = new THREE.Color( 0x000000 ); + this.emissive = new Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; @@ -61,7 +66,7 @@ THREE.MeshLambertMaterial = function ( parameters ) { this.alphaMap = null; this.envMap = null; - this.combine = THREE.MultiplyOperation; + this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -78,12 +83,12 @@ THREE.MeshLambertMaterial = function ( parameters ) { }; -THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial; +MeshLambertMaterial.prototype = Object.create( Material.prototype ); +MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; -THREE.MeshLambertMaterial.prototype.copy = function ( source ) { +MeshLambertMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); @@ -120,3 +125,6 @@ THREE.MeshLambertMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshLambertMaterial }; \ No newline at end of file diff --git a/src/materials/MeshNormalMaterial.js b/src/materials/MeshNormalMaterial.js index d85582ef8ef3d8..dc0fc88db66fb9 100644 --- a/src/materials/MeshNormalMaterial.js +++ b/src/materials/MeshNormalMaterial.js @@ -1,3 +1,5 @@ +import { Material } from './Material'; + /** * @author mrdoob / http://mrdoob.com/ * @@ -9,9 +11,10 @@ * } */ -THREE.MeshNormalMaterial = function ( parameters ) { +function MeshNormalMaterial ( parameters ) { + this.isMeshNormalMaterial = this.isMaterial = true; - THREE.Material.call( this, parameters ); + Material.call( this, parameters ); this.type = 'MeshNormalMaterial'; @@ -26,12 +29,12 @@ THREE.MeshNormalMaterial = function ( parameters ) { }; -THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial; +MeshNormalMaterial.prototype = Object.create( Material.prototype ); +MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; -THREE.MeshNormalMaterial.prototype.copy = function ( source ) { +MeshNormalMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; @@ -39,3 +42,6 @@ THREE.MeshNormalMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshNormalMaterial }; \ No newline at end of file diff --git a/src/materials/MeshPhongMaterial.js b/src/materials/MeshPhongMaterial.js index 0ab6b8bfa77735..fc8fff1d5856cc 100644 --- a/src/materials/MeshPhongMaterial.js +++ b/src/materials/MeshPhongMaterial.js @@ -1,3 +1,8 @@ +import { Material } from './Material'; +import { MultiplyOperation } from '../constants'; +import { Vector2 } from '../math/Vector2'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -48,14 +53,15 @@ * } */ -THREE.MeshPhongMaterial = function ( parameters ) { +function MeshPhongMaterial ( parameters ) { + this.isMeshPhongMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'MeshPhongMaterial'; - this.color = new THREE.Color( 0xffffff ); // diffuse - this.specular = new THREE.Color( 0x111111 ); + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); this.shininess = 30; this.map = null; @@ -66,7 +72,7 @@ THREE.MeshPhongMaterial = function ( parameters ) { this.aoMap = null; this.aoMapIntensity = 1.0; - this.emissive = new THREE.Color( 0x000000 ); + this.emissive = new Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; @@ -74,7 +80,7 @@ THREE.MeshPhongMaterial = function ( parameters ) { this.bumpScale = 1; this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); + this.normalScale = new Vector2( 1, 1 ); this.displacementMap = null; this.displacementScale = 1; @@ -85,7 +91,7 @@ THREE.MeshPhongMaterial = function ( parameters ) { this.alphaMap = null; this.envMap = null; - this.combine = THREE.MultiplyOperation; + this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -102,12 +108,12 @@ THREE.MeshPhongMaterial = function ( parameters ) { }; -THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial; +MeshPhongMaterial.prototype = Object.create( Material.prototype ); +MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; -THREE.MeshPhongMaterial.prototype.copy = function ( source ) { +MeshPhongMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.specular.copy( source.specular ); @@ -156,3 +162,6 @@ THREE.MeshPhongMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshPhongMaterial }; \ No newline at end of file diff --git a/src/materials/MeshPhysicalMaterial.js b/src/materials/MeshPhysicalMaterial.js index 021b0bd8d83fce..a539c53a90654f 100644 --- a/src/materials/MeshPhysicalMaterial.js +++ b/src/materials/MeshPhysicalMaterial.js @@ -1,3 +1,5 @@ +import { MeshStandardMaterial } from './MeshStandardMaterial'; + /** * @author WestLangley / http://github.com/WestLangley * @@ -6,9 +8,10 @@ * } */ -THREE.MeshPhysicalMaterial = function ( parameters ) { +function MeshPhysicalMaterial ( parameters ) { + this.isMeshPhysicalMaterial = this.isMeshStandardMaterial = this.isMaterial = true; - THREE.MeshStandardMaterial.call( this ); + MeshStandardMaterial.call( this ); this.defines = { 'PHYSICAL': '' }; @@ -23,12 +26,12 @@ THREE.MeshPhysicalMaterial = function ( parameters ) { }; -THREE.MeshPhysicalMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype ); -THREE.MeshPhysicalMaterial.prototype.constructor = THREE.MeshPhysicalMaterial; +MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); +MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; -THREE.MeshPhysicalMaterial.prototype.copy = function ( source ) { +MeshPhysicalMaterial.prototype.copy = function ( source ) { - THREE.MeshStandardMaterial.prototype.copy.call( this, source ); + MeshStandardMaterial.prototype.copy.call( this, source ); this.defines = { 'PHYSICAL': '' }; @@ -40,3 +43,6 @@ THREE.MeshPhysicalMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshPhysicalMaterial }; \ No newline at end of file diff --git a/src/materials/MeshStandardMaterial.js b/src/materials/MeshStandardMaterial.js index 82950c86657c9f..ec1ea9b2b8d10c 100644 --- a/src/materials/MeshStandardMaterial.js +++ b/src/materials/MeshStandardMaterial.js @@ -1,3 +1,7 @@ +import { Material } from './Material'; +import { Vector2 } from '../math/Vector2'; +import { Color } from '../math/Color'; + /** * @author WestLangley / http://github.com/WestLangley * @@ -49,15 +53,16 @@ * } */ -THREE.MeshStandardMaterial = function ( parameters ) { +function MeshStandardMaterial ( parameters ) { + this.isMeshStandardMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.defines = { 'STANDARD': '' }; this.type = 'MeshStandardMaterial'; - this.color = new THREE.Color( 0xffffff ); // diffuse + this.color = new Color( 0xffffff ); // diffuse this.roughness = 0.5; this.metalness = 0.5; @@ -69,7 +74,7 @@ THREE.MeshStandardMaterial = function ( parameters ) { this.aoMap = null; this.aoMapIntensity = 1.0; - this.emissive = new THREE.Color( 0x000000 ); + this.emissive = new Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; @@ -77,7 +82,7 @@ THREE.MeshStandardMaterial = function ( parameters ) { this.bumpScale = 1; this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); + this.normalScale = new Vector2( 1, 1 ); this.displacementMap = null; this.displacementScale = 1; @@ -107,12 +112,12 @@ THREE.MeshStandardMaterial = function ( parameters ) { }; -THREE.MeshStandardMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshStandardMaterial.prototype.constructor = THREE.MeshStandardMaterial; +MeshStandardMaterial.prototype = Object.create( Material.prototype ); +MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; -THREE.MeshStandardMaterial.prototype.copy = function ( source ) { +MeshStandardMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.defines = { 'STANDARD': '' }; @@ -165,3 +170,6 @@ THREE.MeshStandardMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshStandardMaterial }; \ No newline at end of file diff --git a/src/materials/MultiMaterial.js b/src/materials/MultiMaterial.js index 3aff3fbdd502aa..add0775060b578 100644 --- a/src/materials/MultiMaterial.js +++ b/src/materials/MultiMaterial.js @@ -1,10 +1,13 @@ +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.MultiMaterial = function ( materials ) { +function MultiMaterial ( materials ) { + this.isMultiMaterial = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.type = 'MultiMaterial'; @@ -14,9 +17,9 @@ THREE.MultiMaterial = function ( materials ) { }; -THREE.MultiMaterial.prototype = { +MultiMaterial.prototype = { - constructor: THREE.MultiMaterial, + constructor: MultiMaterial, toJSON: function ( meta ) { @@ -65,3 +68,6 @@ THREE.MultiMaterial.prototype = { } }; + + +export { MultiMaterial }; \ No newline at end of file diff --git a/src/materials/PointsMaterial.js b/src/materials/PointsMaterial.js index c036dbe7465b8d..b3c2ad1b999ba0 100644 --- a/src/materials/PointsMaterial.js +++ b/src/materials/PointsMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -12,13 +15,14 @@ * } */ -THREE.PointsMaterial = function ( parameters ) { +function PointsMaterial ( parameters ) { + this.isPointsMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'PointsMaterial'; - this.color = new THREE.Color( 0xffffff ); + this.color = new Color( 0xffffff ); this.map = null; @@ -31,12 +35,12 @@ THREE.PointsMaterial = function ( parameters ) { }; -THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial; +PointsMaterial.prototype = Object.create( Material.prototype ); +PointsMaterial.prototype.constructor = PointsMaterial; -THREE.PointsMaterial.prototype.copy = function ( source ) { +PointsMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); @@ -48,3 +52,6 @@ THREE.PointsMaterial.prototype.copy = function ( source ) { return this; }; + + +export { PointsMaterial }; \ No newline at end of file diff --git a/src/materials/RawShaderMaterial.js b/src/materials/RawShaderMaterial.js index 130edcaa3b3fa4..801799d01e2114 100644 --- a/src/materials/RawShaderMaterial.js +++ b/src/materials/RawShaderMaterial.js @@ -1,14 +1,20 @@ +import { ShaderMaterial } from './ShaderMaterial'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.RawShaderMaterial = function ( parameters ) { +function RawShaderMaterial ( parameters ) { + this.isRawShaderMaterial = this.isShaderMaterial = this.isMaterial = true; - THREE.ShaderMaterial.call( this, parameters ); + ShaderMaterial.call( this, parameters ); this.type = 'RawShaderMaterial'; }; -THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); -THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial; +RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); +RawShaderMaterial.prototype.constructor = RawShaderMaterial; + + +export { RawShaderMaterial }; \ No newline at end of file diff --git a/src/materials/ShaderMaterial.js b/src/materials/ShaderMaterial.js index b4592cd3898462..9922c549dbc422 100644 --- a/src/materials/ShaderMaterial.js +++ b/src/materials/ShaderMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { UniformsUtils } from '../renderers/shaders/UniformsUtils'; + /** * @author alteredq / http://alteredqualia.com/ * @@ -19,9 +22,10 @@ * } */ -THREE.ShaderMaterial = function ( parameters ) { +function ShaderMaterial ( parameters ) { + this.isShaderMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'ShaderMaterial'; @@ -75,17 +79,17 @@ THREE.ShaderMaterial = function ( parameters ) { }; -THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial; +ShaderMaterial.prototype = Object.create( Material.prototype ); +ShaderMaterial.prototype.constructor = ShaderMaterial; -THREE.ShaderMaterial.prototype.copy = function ( source ) { +ShaderMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.fragmentShader = source.fragmentShader; this.vertexShader = source.vertexShader; - this.uniforms = THREE.UniformsUtils.clone( source.uniforms ); + this.uniforms = UniformsUtils.clone( source.uniforms ); this.defines = source.defines; @@ -106,9 +110,9 @@ THREE.ShaderMaterial.prototype.copy = function ( source ) { }; -THREE.ShaderMaterial.prototype.toJSON = function ( meta ) { +ShaderMaterial.prototype.toJSON = function ( meta ) { - var data = THREE.Material.prototype.toJSON.call( this, meta ); + var data = Material.prototype.toJSON.call( this, meta ); data.uniforms = this.uniforms; data.vertexShader = this.vertexShader; @@ -117,3 +121,6 @@ THREE.ShaderMaterial.prototype.toJSON = function ( meta ) { return data; }; + + +export { ShaderMaterial }; \ No newline at end of file diff --git a/src/materials/ShadowMaterial.js b/src/materials/ShadowMaterial.js index 86d800676cbab4..9575e975267792 100644 --- a/src/materials/ShadowMaterial.js +++ b/src/materials/ShadowMaterial.js @@ -1,18 +1,24 @@ +import { ShaderMaterial } from './ShaderMaterial'; +import { ShaderChunk } from '../renderers/shaders/ShaderChunk'; +import { UniformsLib } from '../renderers/shaders/UniformsLib'; +import { UniformsUtils } from '../renderers/shaders/UniformsUtils'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.ShadowMaterial = function () { +function ShadowMaterial () { + this.isShadowMaterial = this.isShaderMaterial = this.isMaterial = true; - THREE.ShaderMaterial.call( this, { - uniforms: THREE.UniformsUtils.merge( [ - THREE.UniformsLib[ "lights" ], + ShaderMaterial.call( this, { + uniforms: UniformsUtils.merge( [ + UniformsLib[ "lights" ], { opacity: { value: 1.0 } } ] ), - vertexShader: THREE.ShaderChunk[ 'shadow_vert' ], - fragmentShader: THREE.ShaderChunk[ 'shadow_frag' ] + vertexShader: ShaderChunk[ 'shadow_vert' ], + fragmentShader: ShaderChunk[ 'shadow_frag' ] } ); this.lights = true; @@ -32,5 +38,8 @@ THREE.ShadowMaterial = function () { }; -THREE.ShadowMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); -THREE.ShadowMaterial.prototype.constructor = THREE.ShadowMaterial; +ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype ); +ShadowMaterial.prototype.constructor = ShadowMaterial; + + +export { ShadowMaterial }; \ No newline at end of file diff --git a/src/materials/SpriteMaterial.js b/src/materials/SpriteMaterial.js index e56c1947ca53e9..637c82bb5aa469 100644 --- a/src/materials/SpriteMaterial.js +++ b/src/materials/SpriteMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { Color } from '../math/Color'; + /** * @author alteredq / http://alteredqualia.com/ * @@ -11,13 +14,14 @@ * } */ -THREE.SpriteMaterial = function ( parameters ) { +function SpriteMaterial ( parameters ) { + this.isSpriteMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'SpriteMaterial'; - this.color = new THREE.Color( 0xffffff ); + this.color = new Color( 0xffffff ); this.map = null; this.rotation = 0; @@ -29,12 +33,12 @@ THREE.SpriteMaterial = function ( parameters ) { }; -THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial; +SpriteMaterial.prototype = Object.create( Material.prototype ); +SpriteMaterial.prototype.constructor = SpriteMaterial; -THREE.SpriteMaterial.prototype.copy = function ( source ) { +SpriteMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.map = source.map; @@ -44,3 +48,6 @@ THREE.SpriteMaterial.prototype.copy = function ( source ) { return this; }; + + +export { SpriteMaterial }; \ No newline at end of file diff --git a/src/math/Box2.js b/src/math/Box2.js index 7dfa62ab547d52..2f676e86bb5f4c 100644 --- a/src/math/Box2.js +++ b/src/math/Box2.js @@ -1,17 +1,20 @@ +import { Vector2 } from './Vector2'; + /** * @author bhouston / http://clara.io */ -THREE.Box2 = function ( min, max ) { +function Box2 ( min, max ) { + this.isBox2 = true; - this.min = ( min !== undefined ) ? min : new THREE.Vector2( + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity ); + this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); }; -THREE.Box2.prototype = { +Box2.prototype = { - constructor: THREE.Box2, + constructor: Box2, set: function ( min, max ) { @@ -38,7 +41,7 @@ THREE.Box2.prototype = { setFromCenterAndSize: function () { - var v1 = new THREE.Vector2(); + var v1 = new Vector2(); return function setFromCenterAndSize( center, size ) { @@ -86,14 +89,14 @@ THREE.Box2.prototype = { center: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector2(); + var result = optionalTarget || new Vector2(); return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); }, size: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector2(); + var result = optionalTarget || new Vector2(); return result.subVectors( this.max, this.min ); }, @@ -156,7 +159,7 @@ THREE.Box2.prototype = { // This can potentially have a divide by zero if the box // has a size dimension of 0. - var result = optionalTarget || new THREE.Vector2(); + var result = optionalTarget || new Vector2(); return result.set( ( point.x - this.min.x ) / ( this.max.x - this.min.x ), @@ -182,14 +185,14 @@ THREE.Box2.prototype = { clampPoint: function ( point, optionalTarget ) { - var result = optionalTarget || new THREE.Vector2(); + var result = optionalTarget || new Vector2(); return result.copy( point ).clamp( this.min, this.max ); }, distanceToPoint: function () { - var v1 = new THREE.Vector2(); + var v1 = new Vector2(); return function distanceToPoint( point ) { @@ -234,3 +237,6 @@ THREE.Box2.prototype = { } }; + + +export { Box2 }; \ No newline at end of file diff --git a/src/math/Box3.js b/src/math/Box3.js index cf93582b2afce4..07cef70754f4db 100644 --- a/src/math/Box3.js +++ b/src/math/Box3.js @@ -1,18 +1,22 @@ +import { Vector3 } from './Vector3'; +import { Sphere } from './Sphere'; + /** * @author bhouston / http://clara.io * @author WestLangley / http://github.com/WestLangley */ -THREE.Box3 = function ( min, max ) { +function Box3 ( min, max ) { + this.isBox3 = true; - this.min = ( min !== undefined ) ? min : new THREE.Vector3( + Infinity, + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity ); + this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); }; -THREE.Box3.prototype = { +Box3.prototype = { - constructor: THREE.Box3, + constructor: Box3, set: function ( min, max ) { @@ -70,7 +74,7 @@ THREE.Box3.prototype = { setFromCenterAndSize: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function setFromCenterAndSize( center, size ) { @@ -90,7 +94,7 @@ THREE.Box3.prototype = { // Computes the world-axis-aligned bounding box of an object (including its children), // accounting for both the object's, and children's, world transforms - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function setFromObject( object ) { @@ -106,7 +110,7 @@ THREE.Box3.prototype = { if ( geometry !== undefined ) { - if ( geometry instanceof THREE.Geometry ) { + if ( (geometry && geometry.isGeometry) ) { var vertices = geometry.vertices; @@ -119,7 +123,7 @@ THREE.Box3.prototype = { } - } else if ( geometry instanceof THREE.BufferGeometry ) { + } else if ( (geometry && geometry.isBufferGeometry) ) { var attribute = geometry.attributes.position; @@ -127,7 +131,7 @@ THREE.Box3.prototype = { var array, offset, stride; - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { array = attribute.data.array; offset = attribute.offset; @@ -198,14 +202,14 @@ THREE.Box3.prototype = { center: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); }, size: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.subVectors( this.max, this.min ); }, @@ -270,7 +274,7 @@ THREE.Box3.prototype = { // This can potentially have a divide by zero if the box // has a size dimension of 0. - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.set( ( point.x - this.min.x ) / ( this.max.x - this.min.x ), @@ -302,7 +306,7 @@ THREE.Box3.prototype = { return function intersectsSphere( sphere ) { - if ( closestPoint === undefined ) closestPoint = new THREE.Vector3(); + if ( closestPoint === undefined ) closestPoint = new Vector3(); // Find the point on the AABB closest to the sphere center. this.clampPoint( sphere.center, closestPoint ); @@ -363,14 +367,14 @@ THREE.Box3.prototype = { clampPoint: function ( point, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.copy( point ).clamp( this.min, this.max ); }, distanceToPoint: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function distanceToPoint( point ) { @@ -383,11 +387,11 @@ THREE.Box3.prototype = { getBoundingSphere: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function getBoundingSphere( optionalTarget ) { - var result = optionalTarget || new THREE.Sphere(); + var result = optionalTarget || new Sphere(); result.center = this.center(); result.radius = this.size( v1 ).length() * 0.5; @@ -422,14 +426,14 @@ THREE.Box3.prototype = { applyMatrix4: function () { var points = [ - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3() + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() ]; return function applyMatrix4( matrix ) { @@ -471,3 +475,6 @@ THREE.Box3.prototype = { } }; + + +export { Box3 }; \ No newline at end of file diff --git a/src/math/Color.js b/src/math/Color.js index 1e566cde6a7ad7..d303b8444ce13a 100644 --- a/src/math/Color.js +++ b/src/math/Color.js @@ -1,8 +1,13 @@ +import { _Math } from './Math'; + +var ColorKeywords; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Color = function ( r, g, b ) { +function Color ( r, g, b ) { + this.isColor = true; if ( g === undefined && b === undefined ) { @@ -15,15 +20,15 @@ THREE.Color = function ( r, g, b ) { }; -THREE.Color.prototype = { +Color.prototype = { - constructor: THREE.Color, + constructor: Color, r: 1, g: 1, b: 1, set: function ( value ) { - if ( value instanceof THREE.Color ) { + if ( (value && value.isColor) ) { this.copy( value ); @@ -87,9 +92,9 @@ THREE.Color.prototype = { return function setHSL( h, s, l ) { // h,s,l ranges are in 0.0 - 1.0 - h = THREE.Math.euclideanModulo( h, 1 ); - s = THREE.Math.clamp( s, 0, 1 ); - l = THREE.Math.clamp( l, 0, 1 ); + h = _Math.euclideanModulo( h, 1 ); + s = _Math.clamp( s, 0, 1 ); + l = _Math.clamp( l, 0, 1 ); if ( s === 0 ) { @@ -222,7 +227,7 @@ THREE.Color.prototype = { if ( style && style.length > 0 ) { // color keywords - var hex = THREE.ColorKeywords[ style ]; + var hex = ColorKeywords[ style ]; if ( hex !== undefined ) { @@ -484,7 +489,7 @@ THREE.Color.prototype = { }; -THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, +ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, @@ -508,3 +513,6 @@ THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; + + +export { ColorKeywords, Color }; \ No newline at end of file diff --git a/src/math/Euler.js b/src/math/Euler.js index 2cf60f844416d0..73bfd63be081d8 100644 --- a/src/math/Euler.js +++ b/src/math/Euler.js @@ -1,25 +1,31 @@ +import { Quaternion } from './Quaternion'; +import { Vector3 } from './Vector3'; +import { Matrix4 } from './Matrix4'; +import { _Math } from './Math'; + /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley * @author bhouston / http://clara.io */ -THREE.Euler = function ( x, y, z, order ) { +function Euler ( x, y, z, order ) { + this.isEuler = true; this._x = x || 0; this._y = y || 0; this._z = z || 0; - this._order = order || THREE.Euler.DefaultOrder; + this._order = order || Euler.DefaultOrder; }; -THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; +Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; -THREE.Euler.DefaultOrder = 'XYZ'; +Euler.DefaultOrder = 'XYZ'; -THREE.Euler.prototype = { +Euler.prototype = { - constructor: THREE.Euler, + constructor: Euler, get x () { @@ -107,7 +113,7 @@ THREE.Euler.prototype = { setFromRotationMatrix: function ( m, order, update ) { - var clamp = THREE.Math.clamp; + var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) @@ -234,7 +240,7 @@ THREE.Euler.prototype = { return function setFromQuaternion( q, order, update ) { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + if ( matrix === undefined ) matrix = new Matrix4(); matrix.makeRotationFromQuaternion( q ); @@ -254,7 +260,7 @@ THREE.Euler.prototype = { // WARNING: this discards revolution information -bhouston - var q = new THREE.Quaternion(); + var q = new Quaternion(); return function reorder( newOrder ) { @@ -307,7 +313,7 @@ THREE.Euler.prototype = { } else { - return new THREE.Vector3( this._x, this._y, this._z ); + return new Vector3( this._x, this._y, this._z ); } @@ -324,3 +330,6 @@ THREE.Euler.prototype = { onChangeCallback: function () {} }; + + +export { Euler }; \ No newline at end of file diff --git a/src/math/Frustum.js b/src/math/Frustum.js index 227cdb3823cc83..3b1911054be063 100644 --- a/src/math/Frustum.js +++ b/src/math/Frustum.js @@ -1,27 +1,32 @@ +import { Vector3 } from './Vector3'; +import { Sphere } from './Sphere'; +import { Plane } from './Plane'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author bhouston / http://clara.io */ -THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) { +function Frustum ( p0, p1, p2, p3, p4, p5 ) { + this.isFrustum = true; this.planes = [ - ( p0 !== undefined ) ? p0 : new THREE.Plane(), - ( p1 !== undefined ) ? p1 : new THREE.Plane(), - ( p2 !== undefined ) ? p2 : new THREE.Plane(), - ( p3 !== undefined ) ? p3 : new THREE.Plane(), - ( p4 !== undefined ) ? p4 : new THREE.Plane(), - ( p5 !== undefined ) ? p5 : new THREE.Plane() + ( p0 !== undefined ) ? p0 : new Plane(), + ( p1 !== undefined ) ? p1 : new Plane(), + ( p2 !== undefined ) ? p2 : new Plane(), + ( p3 !== undefined ) ? p3 : new Plane(), + ( p4 !== undefined ) ? p4 : new Plane(), + ( p5 !== undefined ) ? p5 : new Plane() ]; }; -THREE.Frustum.prototype = { +Frustum.prototype = { - constructor: THREE.Frustum, + constructor: Frustum, set: function ( p0, p1, p2, p3, p4, p5 ) { @@ -80,7 +85,7 @@ THREE.Frustum.prototype = { intersectsObject: function () { - var sphere = new THREE.Sphere(); + var sphere = new Sphere(); return function intersectsObject( object ) { @@ -100,7 +105,7 @@ THREE.Frustum.prototype = { intersectsSprite: function () { - var sphere = new THREE.Sphere(); + var sphere = new Sphere(); return function intersectsSprite( sprite ) { @@ -138,8 +143,8 @@ THREE.Frustum.prototype = { intersectsBox: function () { - var p1 = new THREE.Vector3(), - p2 = new THREE.Vector3(); + var p1 = new Vector3(), + p2 = new Vector3(); return function intersectsBox( box ) { @@ -195,3 +200,6 @@ THREE.Frustum.prototype = { } }; + + +export { Frustum }; \ No newline at end of file diff --git a/src/math/Interpolant.js b/src/math/Interpolant.js index c86df556e83952..09afb8fa138c82 100644 --- a/src/math/Interpolant.js +++ b/src/math/Interpolant.js @@ -20,8 +20,9 @@ * @author tschw */ -THREE.Interpolant = function( +function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isInterpolant = true; this.parameterPositions = parameterPositions; this._cachedIndex = 0; @@ -33,9 +34,9 @@ THREE.Interpolant = function( }; -THREE.Interpolant.prototype = { +Interpolant.prototype = { - constructor: THREE.Interpolant, + constructor: Interpolant, evaluate: function( t ) { @@ -246,12 +247,15 @@ THREE.Interpolant.prototype = { }; -Object.assign( THREE.Interpolant.prototype, { +Object.assign( Interpolant.prototype, { beforeStart_: //( 0, t, t0 ), returns this.resultBuffer - THREE.Interpolant.prototype.copySampleValue_, + Interpolant.prototype.copySampleValue_, afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer - THREE.Interpolant.prototype.copySampleValue_ + Interpolant.prototype.copySampleValue_ } ); + + +export { Interpolant }; \ No newline at end of file diff --git a/src/math/Line3.js b/src/math/Line3.js index 2ae1f482cb3614..ef1983ef11e40d 100644 --- a/src/math/Line3.js +++ b/src/math/Line3.js @@ -1,17 +1,21 @@ +import { Vector3 } from './Vector3'; +import { _Math } from './Math'; + /** * @author bhouston / http://clara.io */ -THREE.Line3 = function ( start, end ) { +function Line3 ( start, end ) { + this.isLine3 = true; - this.start = ( start !== undefined ) ? start : new THREE.Vector3(); - this.end = ( end !== undefined ) ? end : new THREE.Vector3(); + this.start = ( start !== undefined ) ? start : new Vector3(); + this.end = ( end !== undefined ) ? end : new Vector3(); }; -THREE.Line3.prototype = { +Line3.prototype = { - constructor: THREE.Line3, + constructor: Line3, set: function ( start, end ) { @@ -39,14 +43,14 @@ THREE.Line3.prototype = { center: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); }, delta: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.subVectors( this.end, this.start ); }, @@ -65,7 +69,7 @@ THREE.Line3.prototype = { at: function ( t, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return this.delta( result ).multiplyScalar( t ).add( this.start ); @@ -73,8 +77,8 @@ THREE.Line3.prototype = { closestPointToPointParameter: function () { - var startP = new THREE.Vector3(); - var startEnd = new THREE.Vector3(); + var startP = new Vector3(); + var startEnd = new Vector3(); return function closestPointToPointParameter( point, clampToLine ) { @@ -88,7 +92,7 @@ THREE.Line3.prototype = { if ( clampToLine ) { - t = THREE.Math.clamp( t, 0, 1 ); + t = _Math.clamp( t, 0, 1 ); } @@ -102,7 +106,7 @@ THREE.Line3.prototype = { var t = this.closestPointToPointParameter( point, clampToLine ); - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return this.delta( result ).multiplyScalar( t ).add( this.start ); @@ -124,3 +128,6 @@ THREE.Line3.prototype = { } }; + + +export { Line3 }; \ No newline at end of file diff --git a/src/math/Math.js b/src/math/Math.js index 59a4ca344734db..f27114c1532dcf 100644 --- a/src/math/Math.js +++ b/src/math/Math.js @@ -1,9 +1,11 @@ +var _Math; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.Math = { +_Math = { DEG2RAD: Math.PI / 180, RAD2DEG: 180 / Math.PI, @@ -125,13 +127,13 @@ THREE.Math = { degToRad: function ( degrees ) { - return degrees * THREE.Math.DEG2RAD; + return degrees * _Math.DEG2RAD; }, radToDeg: function ( radians ) { - return radians * THREE.Math.RAD2DEG; + return radians * _Math.RAD2DEG; }, @@ -162,3 +164,6 @@ THREE.Math = { } }; + + +export { _Math }; \ No newline at end of file diff --git a/src/math/Matrix3.js b/src/math/Matrix3.js index 81067ad3bab313..59ccb36c0b3309 100644 --- a/src/math/Matrix3.js +++ b/src/math/Matrix3.js @@ -1,3 +1,5 @@ +import { Vector3 } from './Vector3'; + /** * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley @@ -5,7 +7,8 @@ * @author tschw */ -THREE.Matrix3 = function () { +function Matrix3 () { + this.isMatrix3 = true; this.elements = new Float32Array( [ @@ -23,9 +26,9 @@ THREE.Matrix3 = function () { }; -THREE.Matrix3.prototype = { +Matrix3.prototype = { - constructor: THREE.Matrix3, + constructor: Matrix3, set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { @@ -97,7 +100,7 @@ THREE.Matrix3.prototype = { return function applyToVector3Array( array, offset, length ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); if ( offset === undefined ) offset = 0; if ( length === undefined ) length = array.length; @@ -121,7 +124,7 @@ THREE.Matrix3.prototype = { return function applyToBuffer( buffer, offset, length ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); if ( offset === undefined ) offset = 0; if ( length === undefined ) length = buffer.length / buffer.itemSize; @@ -169,7 +172,7 @@ THREE.Matrix3.prototype = { getInverse: function ( matrix, throwOnDegenerate ) { - if ( matrix instanceof THREE.Matrix4 ) { + if ( (matrix && matrix.isMatrix4) ) { console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); @@ -300,3 +303,6 @@ THREE.Matrix3.prototype = { } }; + + +export { Matrix3 }; \ No newline at end of file diff --git a/src/math/Matrix4.js b/src/math/Matrix4.js index ae705d97ea5c45..43c38c624fbb60 100644 --- a/src/math/Matrix4.js +++ b/src/math/Matrix4.js @@ -1,3 +1,6 @@ +import { _Math } from './Math'; +import { Vector3 } from './Vector3'; + /** * @author mrdoob / http://mrdoob.com/ * @author supereggbert / http://www.paulbrunt.co.uk/ @@ -11,7 +14,8 @@ * @author WestLangley / http://github.com/WestLangley */ -THREE.Matrix4 = function () { +function Matrix4 () { + this.isMatrix4 = true; this.elements = new Float32Array( [ @@ -30,9 +34,9 @@ THREE.Matrix4 = function () { }; -THREE.Matrix4.prototype = { +Matrix4.prototype = { - constructor: THREE.Matrix4, + constructor: Matrix4, set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { @@ -64,7 +68,7 @@ THREE.Matrix4.prototype = { clone: function () { - return new THREE.Matrix4().fromArray( this.elements ); + return new Matrix4().fromArray( this.elements ); }, @@ -118,7 +122,7 @@ THREE.Matrix4.prototype = { return function extractRotation( m ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); var te = this.elements; var me = m.elements; @@ -147,7 +151,7 @@ THREE.Matrix4.prototype = { makeRotationFromEuler: function ( euler ) { - if ( euler instanceof THREE.Euler === false ) { + if ( (euler && euler.isEuler) === false ) { console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); @@ -318,9 +322,9 @@ THREE.Matrix4.prototype = { if ( x === undefined ) { - x = new THREE.Vector3(); - y = new THREE.Vector3(); - z = new THREE.Vector3(); + x = new Vector3(); + y = new Vector3(); + z = new Vector3(); } @@ -449,7 +453,7 @@ THREE.Matrix4.prototype = { return function applyToVector3Array( array, offset, length ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); if ( offset === undefined ) offset = 0; if ( length === undefined ) length = array.length; @@ -473,7 +477,7 @@ THREE.Matrix4.prototype = { return function applyToBuffer( buffer, offset, length ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); if ( offset === undefined ) offset = 0; if ( length === undefined ) length = buffer.length / buffer.itemSize; @@ -577,7 +581,7 @@ THREE.Matrix4.prototype = { return function getPosition() { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); return v1.setFromMatrixColumn( this, 3 ); @@ -808,8 +812,8 @@ THREE.Matrix4.prototype = { if ( vector === undefined ) { - vector = new THREE.Vector3(); - matrix = new THREE.Matrix4(); + vector = new Vector3(); + matrix = new Matrix4(); } @@ -885,7 +889,7 @@ THREE.Matrix4.prototype = { makePerspective: function ( fov, aspect, near, far ) { - var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 ); + var ymax = near * Math.tan( _Math.DEG2RAD * fov * 0.5 ); var ymin = - ymax; var xmin = ymin * aspect; var xmax = ymax * aspect; @@ -969,3 +973,6 @@ THREE.Matrix4.prototype = { } }; + + +export { Matrix4 }; \ No newline at end of file diff --git a/src/math/Plane.js b/src/math/Plane.js index a77ea851b70285..4b37edb78b707a 100644 --- a/src/math/Plane.js +++ b/src/math/Plane.js @@ -1,17 +1,21 @@ +import { Matrix3 } from './Matrix3'; +import { Vector3 } from './Vector3'; + /** * @author bhouston / http://clara.io */ -THREE.Plane = function ( normal, constant ) { +function Plane ( normal, constant ) { + this.isPlane = true; - this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 ); + this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); this.constant = ( constant !== undefined ) ? constant : 0; }; -THREE.Plane.prototype = { +Plane.prototype = { - constructor: THREE.Plane, + constructor: Plane, set: function ( normal, constant ) { @@ -42,8 +46,8 @@ THREE.Plane.prototype = { setFromCoplanarPoints: function () { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); return function setFromCoplanarPoints( a, b, c ) { @@ -117,18 +121,18 @@ THREE.Plane.prototype = { var perpendicularMagnitude = this.distanceToPoint( point ); - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); }, intersectLine: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function intersectLine( line, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); var direction = line.delta( v1 ); @@ -187,15 +191,15 @@ THREE.Plane.prototype = { coplanarPoint: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.copy( this.normal ).multiplyScalar( - this.constant ); }, applyMatrix4: function () { - var v1 = new THREE.Vector3(); - var m1 = new THREE.Matrix3(); + var v1 = new Vector3(); + var m1 = new Matrix3(); return function applyMatrix4( matrix, optionalNormalMatrix ) { @@ -230,3 +234,6 @@ THREE.Plane.prototype = { } }; + + +export { Plane }; \ No newline at end of file diff --git a/src/math/Quaternion.js b/src/math/Quaternion.js index 3743c7dc00e457..98a481d590bcfc 100644 --- a/src/math/Quaternion.js +++ b/src/math/Quaternion.js @@ -1,3 +1,5 @@ +import { Vector3 } from './Vector3'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ @@ -5,7 +7,8 @@ * @author bhouston / http://clara.io */ -THREE.Quaternion = function ( x, y, z, w ) { +function Quaternion ( x, y, z, w ) { + this.isQuaternion = true; this._x = x || 0; this._y = y || 0; @@ -14,9 +17,9 @@ THREE.Quaternion = function ( x, y, z, w ) { }; -THREE.Quaternion.prototype = { +Quaternion.prototype = { - constructor: THREE.Quaternion, + constructor: Quaternion, get x () { @@ -104,7 +107,7 @@ THREE.Quaternion.prototype = { setFromEuler: function ( euler, update ) { - if ( euler instanceof THREE.Euler === false ) { + if ( (euler && euler.isEuler) === false ) { throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); @@ -263,7 +266,7 @@ THREE.Quaternion.prototype = { return function setFromUnitVectors( vFrom, vTo ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); r = vFrom.dot( vTo ) + 1; @@ -511,7 +514,7 @@ THREE.Quaternion.prototype = { }; -Object.assign( THREE.Quaternion, { +Object.assign( Quaternion, { slerp: function( qa, qb, qm, t ) { @@ -583,3 +586,6 @@ Object.assign( THREE.Quaternion, { } } ); + + +export { Quaternion }; \ No newline at end of file diff --git a/src/math/Ray.js b/src/math/Ray.js index 540a6cb292d7e0..25b6287f5db968 100644 --- a/src/math/Ray.js +++ b/src/math/Ray.js @@ -1,17 +1,20 @@ +import { Vector3 } from './Vector3'; + /** * @author bhouston / http://clara.io */ -THREE.Ray = function ( origin, direction ) { +function Ray ( origin, direction ) { + this.isRay = true; - this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3(); - this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3(); + this.origin = ( origin !== undefined ) ? origin : new Vector3(); + this.direction = ( direction !== undefined ) ? direction : new Vector3(); }; -THREE.Ray.prototype = { +Ray.prototype = { - constructor: THREE.Ray, + constructor: Ray, set: function ( origin, direction ) { @@ -39,7 +42,7 @@ THREE.Ray.prototype = { at: function ( t, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); @@ -55,7 +58,7 @@ THREE.Ray.prototype = { recast: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function recast( t ) { @@ -69,7 +72,7 @@ THREE.Ray.prototype = { closestPointToPoint: function ( point, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); result.subVectors( point, this.origin ); var directionDistance = result.dot( this.direction ); @@ -91,7 +94,7 @@ THREE.Ray.prototype = { distanceSqToPoint: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function distanceSqToPoint( point ) { @@ -115,9 +118,9 @@ THREE.Ray.prototype = { distanceSqToSegment: function () { - var segCenter = new THREE.Vector3(); - var segDir = new THREE.Vector3(); - var diff = new THREE.Vector3(); + var segCenter = new Vector3(); + var segDir = new Vector3(); + var diff = new Vector3(); return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { @@ -242,7 +245,7 @@ THREE.Ray.prototype = { intersectSphere: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function intersectSphere( sphere, optionalTarget ) { @@ -422,7 +425,7 @@ THREE.Ray.prototype = { intersectsBox: ( function () { - var v = new THREE.Vector3(); + var v = new Vector3(); return function intersectsBox( box ) { @@ -435,10 +438,10 @@ THREE.Ray.prototype = { intersectTriangle: function () { // Compute the offset origin, edges, and normal. - var diff = new THREE.Vector3(); - var edge1 = new THREE.Vector3(); - var edge2 = new THREE.Vector3(); - var normal = new THREE.Vector3(); + var diff = new Vector3(); + var edge1 = new Vector3(); + var edge2 = new Vector3(); + var normal = new Vector3(); return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { @@ -533,3 +536,6 @@ THREE.Ray.prototype = { } }; + + +export { Ray }; \ No newline at end of file diff --git a/src/math/Sphere.js b/src/math/Sphere.js index 99ccd79af00799..d910b3e3b6aceb 100644 --- a/src/math/Sphere.js +++ b/src/math/Sphere.js @@ -1,18 +1,22 @@ +import { Box3 } from './Box3'; +import { Vector3 } from './Vector3'; + /** * @author bhouston / http://clara.io * @author mrdoob / http://mrdoob.com/ */ -THREE.Sphere = function ( center, radius ) { +function Sphere ( center, radius ) { + this.isSphere = true; - this.center = ( center !== undefined ) ? center : new THREE.Vector3(); + this.center = ( center !== undefined ) ? center : new Vector3(); this.radius = ( radius !== undefined ) ? radius : 0; }; -THREE.Sphere.prototype = { +Sphere.prototype = { - constructor: THREE.Sphere, + constructor: Sphere, set: function ( center, radius ) { @@ -25,7 +29,7 @@ THREE.Sphere.prototype = { setFromPoints: function () { - var box = new THREE.Box3(); + var box = new Box3(); return function setFromPoints( points, optionalCenter ) { @@ -122,7 +126,7 @@ THREE.Sphere.prototype = { var deltaLengthSq = this.center.distanceToSquared( point ); - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); result.copy( point ); @@ -139,7 +143,7 @@ THREE.Sphere.prototype = { getBoundingBox: function ( optionalTarget ) { - var box = optionalTarget || new THREE.Box3(); + var box = optionalTarget || new Box3(); box.set( this.center, this.center ); box.expandByScalar( this.radius ); @@ -172,3 +176,6 @@ THREE.Sphere.prototype = { } }; + + +export { Sphere }; \ No newline at end of file diff --git a/src/math/Spherical.js b/src/math/Spherical.js index f3870be9a57cac..1d7d96491a00d3 100644 --- a/src/math/Spherical.js +++ b/src/math/Spherical.js @@ -1,3 +1,5 @@ +import { _Math } from './Math'; + /** * @author bhouston / http://clara.io * @author WestLangley / http://github.com/WestLangley @@ -8,7 +10,8 @@ * The equator starts at positive z. */ -THREE.Spherical = function ( radius, phi, theta ) { +function Spherical ( radius, phi, theta ) { + this.isSpherical = true; this.radius = ( radius !== undefined ) ? radius : 1.0; this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole @@ -18,9 +21,9 @@ THREE.Spherical = function ( radius, phi, theta ) { }; -THREE.Spherical.prototype = { +Spherical.prototype = { - constructor: THREE.Spherical, + constructor: Spherical, set: function ( radius, phi, theta ) { @@ -70,7 +73,7 @@ THREE.Spherical.prototype = { } else { this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis - this.phi = Math.acos( THREE.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle + this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle } @@ -79,3 +82,6 @@ THREE.Spherical.prototype = { }, }; + + +export { Spherical }; \ No newline at end of file diff --git a/src/math/Spline.js b/src/math/Spline.js index 8d04fdb6711fb5..4bad0df3dc1d51 100644 --- a/src/math/Spline.js +++ b/src/math/Spline.js @@ -1,3 +1,5 @@ +import { Vector3 } from './Vector3'; + /** * Spline from Tween.js, slightly optimized (and trashed) * http://sole.github.com/tween.js/examples/05_spline.html @@ -6,7 +8,8 @@ * @author alteredq / http://alteredqualia.com/ */ -THREE.Spline = function ( points ) { +function Spline ( points ) { + this.isSpline = true; this.points = points; @@ -75,8 +78,8 @@ THREE.Spline = function ( points ) { var i, index, nSamples, position, point = 0, intPoint = 0, oldIntPoint = 0, - oldPosition = new THREE.Vector3(), - tmpVec = new THREE.Vector3(), + oldPosition = new Vector3(), + tmpVec = new Vector3(), chunkLengths = [], totalLength = 0; @@ -128,7 +131,7 @@ THREE.Spline = function ( points ) { realDistance, sampling, position, newpoints = [], - tmpVec = new THREE.Vector3(), + tmpVec = new Vector3(), sl = this.getLength(); newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); @@ -174,3 +177,6 @@ THREE.Spline = function ( points ) { } }; + + +export { Spline }; \ No newline at end of file diff --git a/src/math/Triangle.js b/src/math/Triangle.js index 3912687e5c576b..d9193d4ddae1cb 100644 --- a/src/math/Triangle.js +++ b/src/math/Triangle.js @@ -1,23 +1,28 @@ +import { Vector3 } from './Vector3'; +import { Line3 } from './Line3'; +import { Plane } from './Plane'; + /** * @author bhouston / http://clara.io * @author mrdoob / http://mrdoob.com/ */ -THREE.Triangle = function ( a, b, c ) { +function Triangle ( a, b, c ) { + this.isTriangle = true; - this.a = ( a !== undefined ) ? a : new THREE.Vector3(); - this.b = ( b !== undefined ) ? b : new THREE.Vector3(); - this.c = ( c !== undefined ) ? c : new THREE.Vector3(); + this.a = ( a !== undefined ) ? a : new Vector3(); + this.b = ( b !== undefined ) ? b : new Vector3(); + this.c = ( c !== undefined ) ? c : new Vector3(); }; -THREE.Triangle.normal = function () { +Triangle.normal = function () { - var v0 = new THREE.Vector3(); + var v0 = new Vector3(); return function normal( a, b, c, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); result.subVectors( c, b ); v0.subVectors( a, b ); @@ -38,11 +43,11 @@ THREE.Triangle.normal = function () { // static/instance method to calculate barycentric coordinates // based on: http://www.blackpawn.com/texts/pointinpoly/default.html -THREE.Triangle.barycoordFromPoint = function () { +Triangle.barycoordFromPoint = function () { - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + var v0 = new Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); return function barycoordFromPoint( point, a, b, c, optionalTarget ) { @@ -58,7 +63,7 @@ THREE.Triangle.barycoordFromPoint = function () { var denom = ( dot00 * dot11 - dot01 * dot01 ); - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); // collinear or singular triangle if ( denom === 0 ) { @@ -80,13 +85,13 @@ THREE.Triangle.barycoordFromPoint = function () { }(); -THREE.Triangle.containsPoint = function () { +Triangle.containsPoint = function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function containsPoint( point, a, b, c ) { - var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 ); + var result = Triangle.barycoordFromPoint( point, a, b, c, v1 ); return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); @@ -94,9 +99,9 @@ THREE.Triangle.containsPoint = function () { }(); -THREE.Triangle.prototype = { +Triangle.prototype = { - constructor: THREE.Triangle, + constructor: Triangle, set: function ( a, b, c ) { @@ -136,8 +141,8 @@ THREE.Triangle.prototype = { area: function () { - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); + var v0 = new Vector3(); + var v1 = new Vector3(); return function area() { @@ -152,20 +157,20 @@ THREE.Triangle.prototype = { midpoint: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); }, normal: function ( optionalTarget ) { - return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget ); + return Triangle.normal( this.a, this.b, this.c, optionalTarget ); }, plane: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Plane(); + var result = optionalTarget || new Plane(); return result.setFromCoplanarPoints( this.a, this.b, this.c ); @@ -173,13 +178,13 @@ THREE.Triangle.prototype = { barycoordFromPoint: function ( point, optionalTarget ) { - return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); + return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); }, containsPoint: function ( point ) { - return THREE.Triangle.containsPoint( point, this.a, this.b, this.c ); + return Triangle.containsPoint( point, this.a, this.b, this.c ); }, @@ -191,14 +196,14 @@ THREE.Triangle.prototype = { if ( plane === undefined ) { - plane = new THREE.Plane(); - edgeList = [ new THREE.Line3(), new THREE.Line3(), new THREE.Line3() ]; - projectedPoint = new THREE.Vector3(); - closestPoint = new THREE.Vector3(); + plane = new Plane(); + edgeList = [ new Line3(), new Line3(), new Line3() ]; + projectedPoint = new Vector3(); + closestPoint = new Vector3(); } - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); var minDistance = Infinity; // project the point onto the plane of the triangle @@ -253,3 +258,6 @@ THREE.Triangle.prototype = { } }; + + +export { Triangle }; \ No newline at end of file diff --git a/src/math/Vector2.js b/src/math/Vector2.js index fb5b27c2bc3473..2338eed42c2571 100644 --- a/src/math/Vector2.js +++ b/src/math/Vector2.js @@ -5,16 +5,17 @@ * @author zz85 / http://www.lab4games.net/zz85/blog */ -THREE.Vector2 = function ( x, y ) { +function Vector2 ( x, y ) { + this.isVector2 = true; this.x = x || 0; this.y = y || 0; }; -THREE.Vector2.prototype = { +Vector2.prototype = { - constructor: THREE.Vector2, + constructor: Vector2, get width() { @@ -271,8 +272,8 @@ THREE.Vector2.prototype = { if ( min === undefined ) { - min = new THREE.Vector2(); - max = new THREE.Vector2(); + min = new Vector2(); + max = new Vector2(); } @@ -477,3 +478,6 @@ THREE.Vector2.prototype = { } }; + + +export { Vector2 }; \ No newline at end of file diff --git a/src/math/Vector3.js b/src/math/Vector3.js index 25acd8421f4412..a5871c2f374fef 100644 --- a/src/math/Vector3.js +++ b/src/math/Vector3.js @@ -1,3 +1,7 @@ +import { _Math } from './Math'; +import { Matrix4 } from './Matrix4'; +import { Quaternion } from './Quaternion'; + /** * @author mrdoob / http://mrdoob.com/ * @author *kile / http://kile.stravaganza.org/ @@ -7,7 +11,8 @@ * @author WestLangley / http://github.com/WestLangley */ -THREE.Vector3 = function ( x, y, z ) { +function Vector3 ( x, y, z ) { + this.isVector3 = true; this.x = x || 0; this.y = y || 0; @@ -15,9 +20,9 @@ THREE.Vector3 = function ( x, y, z ) { }; -THREE.Vector3.prototype = { +Vector3.prototype = { - constructor: THREE.Vector3, + constructor: Vector3, set: function ( x, y, z ) { @@ -242,13 +247,13 @@ THREE.Vector3.prototype = { return function applyEuler( euler ) { - if ( euler instanceof THREE.Euler === false ) { + if ( (euler && euler.isEuler) === false ) { console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); } - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + if ( quaternion === undefined ) quaternion = new Quaternion(); return this.applyQuaternion( quaternion.setFromEuler( euler ) ); @@ -262,7 +267,7 @@ THREE.Vector3.prototype = { return function applyAxisAngle( axis, angle ) { - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + if ( quaternion === undefined ) quaternion = new Quaternion(); return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); @@ -342,7 +347,7 @@ THREE.Vector3.prototype = { return function project( camera ) { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + if ( matrix === undefined ) matrix = new Matrix4(); matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); return this.applyProjection( matrix ); @@ -357,7 +362,7 @@ THREE.Vector3.prototype = { return function unproject( camera ) { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + if ( matrix === undefined ) matrix = new Matrix4(); matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); return this.applyProjection( matrix ); @@ -438,8 +443,8 @@ THREE.Vector3.prototype = { if ( min === undefined ) { - min = new THREE.Vector3(); - max = new THREE.Vector3(); + min = new Vector3(); + max = new Vector3(); } @@ -608,7 +613,7 @@ THREE.Vector3.prototype = { return function projectOnPlane( planeNormal ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); v1.copy( this ).projectOnVector( planeNormal ); @@ -627,7 +632,7 @@ THREE.Vector3.prototype = { return function reflect( normal ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); @@ -641,7 +646,7 @@ THREE.Vector3.prototype = { // clamp, to handle numerical problems - return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); + return Math.acos( _Math.clamp( theta, - 1, 1 ) ); }, @@ -758,3 +763,6 @@ THREE.Vector3.prototype = { } }; + + +export { Vector3 }; \ No newline at end of file diff --git a/src/math/Vector4.js b/src/math/Vector4.js index ad4dcd143423fc..1bc3c14f9b6a4d 100644 --- a/src/math/Vector4.js +++ b/src/math/Vector4.js @@ -6,7 +6,8 @@ * @author WestLangley / http://github.com/WestLangley */ -THREE.Vector4 = function ( x, y, z, w ) { +function Vector4 ( x, y, z, w ) { + this.isVector4 = true; this.x = x || 0; this.y = y || 0; @@ -15,9 +16,9 @@ THREE.Vector4 = function ( x, y, z, w ) { }; -THREE.Vector4.prototype = { +Vector4.prototype = { - constructor: THREE.Vector4, + constructor: Vector4, set: function ( x, y, z, w ) { @@ -452,8 +453,8 @@ THREE.Vector4.prototype = { if ( min === undefined ) { - min = new THREE.Vector4(); - max = new THREE.Vector4(); + min = new Vector4(); + max = new Vector4(); } @@ -623,3 +624,6 @@ THREE.Vector4.prototype = { } }; + + +export { Vector4 }; \ No newline at end of file diff --git a/src/math/interpolants/CubicInterpolant.js b/src/math/interpolants/CubicInterpolant.js index 9498ba39f2bb4d..bce70c8e421737 100644 --- a/src/math/interpolants/CubicInterpolant.js +++ b/src/math/interpolants/CubicInterpolant.js @@ -1,3 +1,7 @@ +import { ZeroCurvatureEnding } from '../../constants'; +import { Interpolant } from '../Interpolant'; +import { WrapAroundEnding, ZeroSlopeEnding } from '../../constants'; + /** * Fast and simple cubic spline interpolant. * @@ -8,10 +12,11 @@ * @author tschw */ -THREE.CubicInterpolant = function( +function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isCubicInterpolant = true; - THREE.Interpolant.call( + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); this._weightPrev = -0; @@ -21,15 +26,15 @@ THREE.CubicInterpolant = function( }; -THREE.CubicInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { +CubicInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - constructor: THREE.CubicInterpolant, + constructor: CubicInterpolant, DefaultSettings_: { - endingStart: THREE.ZeroCurvatureEnding, - endingEnd: THREE.ZeroCurvatureEnding + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding }, @@ -46,7 +51,7 @@ THREE.CubicInterpolant.prototype = switch ( this.getSettings_().endingStart ) { - case THREE.ZeroSlopeEnding: + case ZeroSlopeEnding: // f'(t0) = 0 iPrev = i1; @@ -54,7 +59,7 @@ THREE.CubicInterpolant.prototype = break; - case THREE.WrapAroundEnding: + case WrapAroundEnding: // use the other end of the curve iPrev = pp.length - 2; @@ -76,7 +81,7 @@ THREE.CubicInterpolant.prototype = switch ( this.getSettings_().endingEnd ) { - case THREE.ZeroSlopeEnding: + case ZeroSlopeEnding: // f'(tN) = 0 iNext = i1; @@ -84,7 +89,7 @@ THREE.CubicInterpolant.prototype = break; - case THREE.WrapAroundEnding: + case WrapAroundEnding: // use the other end of the curve iNext = 1; @@ -150,3 +155,6 @@ THREE.CubicInterpolant.prototype = } } ); + + +export { CubicInterpolant }; \ No newline at end of file diff --git a/src/math/interpolants/DiscreteInterpolant.js b/src/math/interpolants/DiscreteInterpolant.js index e8792aa5cdf60e..cd8eb03259814c 100644 --- a/src/math/interpolants/DiscreteInterpolant.js +++ b/src/math/interpolants/DiscreteInterpolant.js @@ -1,3 +1,5 @@ +import { Interpolant } from '../Interpolant'; + /** * * Interpolant that evaluates to the sample value at the position preceeding @@ -6,18 +8,19 @@ * @author tschw */ -THREE.DiscreteInterpolant = function( +function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isDiscreteInterpolant = true; - THREE.Interpolant.call( + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); }; -THREE.DiscreteInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { +DiscreteInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - constructor: THREE.DiscreteInterpolant, + constructor: DiscreteInterpolant, interpolate_: function( i1, t0, t, t1 ) { @@ -26,3 +29,6 @@ THREE.DiscreteInterpolant.prototype = } } ); + + +export { DiscreteInterpolant }; \ No newline at end of file diff --git a/src/math/interpolants/LinearInterpolant.js b/src/math/interpolants/LinearInterpolant.js index 785d715c01db11..0b8c1b8b805067 100644 --- a/src/math/interpolants/LinearInterpolant.js +++ b/src/math/interpolants/LinearInterpolant.js @@ -1,19 +1,22 @@ +import { Interpolant } from '../Interpolant'; + /** * @author tschw */ -THREE.LinearInterpolant = function( +function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isLinearInterpolant = true; - THREE.Interpolant.call( + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); }; -THREE.LinearInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { +LinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - constructor: THREE.LinearInterpolant, + constructor: LinearInterpolant, interpolate_: function( i1, t0, t, t1 ) { @@ -40,3 +43,6 @@ THREE.LinearInterpolant.prototype = } } ); + + +export { LinearInterpolant }; \ No newline at end of file diff --git a/src/math/interpolants/QuaternionLinearInterpolant.js b/src/math/interpolants/QuaternionLinearInterpolant.js index 0cdbb7f3586d83..4998924afc59b6 100644 --- a/src/math/interpolants/QuaternionLinearInterpolant.js +++ b/src/math/interpolants/QuaternionLinearInterpolant.js @@ -1,21 +1,25 @@ +import { Interpolant } from '../Interpolant'; +import { Quaternion } from '../Quaternion'; + /** * Spherical linear unit quaternion interpolant. * * @author tschw */ -THREE.QuaternionLinearInterpolant = function( +function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isQuaternionLinearInterpolant = true; - THREE.Interpolant.call( + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); }; -THREE.QuaternionLinearInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { +QuaternionLinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - constructor: THREE.QuaternionLinearInterpolant, + constructor: QuaternionLinearInterpolant, interpolate_: function( i1, t0, t, t1 ) { @@ -29,7 +33,7 @@ THREE.QuaternionLinearInterpolant.prototype = for ( var end = offset + stride; offset !== end; offset += 4 ) { - THREE.Quaternion.slerpFlat( result, 0, + Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); } @@ -39,3 +43,6 @@ THREE.QuaternionLinearInterpolant.prototype = } } ); + + +export { QuaternionLinearInterpolant }; \ No newline at end of file diff --git a/src/objects/Bone.js b/src/objects/Bone.js index ff12a01e89347f..cacbe25de44c1d 100644 --- a/src/objects/Bone.js +++ b/src/objects/Bone.js @@ -1,12 +1,15 @@ +import { Object3D } from '../core/Object3D'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author ikerr / http://verold.com */ -THREE.Bone = function ( skin ) { +function Bone ( skin ) { + this.isBone = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Bone'; @@ -14,13 +17,13 @@ THREE.Bone = function ( skin ) { }; -THREE.Bone.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Bone, + constructor: Bone, copy: function ( source ) { - THREE.Object3D.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source ); this.skin = source.skin; @@ -29,3 +32,6 @@ THREE.Bone.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } } ); + + +export { Bone }; \ No newline at end of file diff --git a/src/objects/Group.js b/src/objects/Group.js index 509731d36d6582..5e5094e171e768 100644 --- a/src/objects/Group.js +++ b/src/objects/Group.js @@ -1,17 +1,23 @@ +import { Object3D } from '../core/Object3D'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Group = function () { +function Group () { + this.isGroup = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Group'; }; -THREE.Group.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Group.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Group + constructor: Group } ); + + +export { Group }; \ No newline at end of file diff --git a/src/objects/LOD.js b/src/objects/LOD.js index bb47fedeab55d6..9f0276298e70ca 100644 --- a/src/objects/LOD.js +++ b/src/objects/LOD.js @@ -1,12 +1,16 @@ +import { Vector3 } from '../math/Vector3'; +import { Object3D } from '../core/Object3D'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.LOD = function () { +function LOD () { + this.isLOD = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'LOD'; @@ -20,13 +24,13 @@ THREE.LOD = function () { }; -THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.LOD, + constructor: LOD, copy: function ( source ) { - THREE.Object3D.prototype.copy.call( this, source, false ); + Object3D.prototype.copy.call( this, source, false ); var levels = source.levels; @@ -86,7 +90,7 @@ THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), raycast: ( function () { - var matrixPosition = new THREE.Vector3(); + var matrixPosition = new Vector3(); return function raycast( raycaster, intersects ) { @@ -102,8 +106,8 @@ THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), update: function () { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); return function update( camera ) { @@ -147,7 +151,7 @@ THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), toJSON: function ( meta ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var data = Object3D.prototype.toJSON.call( this, meta ); data.object.levels = []; @@ -169,3 +173,6 @@ THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } } ); + + +export { LOD }; \ No newline at end of file diff --git a/src/objects/LensFlare.js b/src/objects/LensFlare.js index 81c6dac73974a1..f4b732ac91e8ba 100644 --- a/src/objects/LensFlare.js +++ b/src/objects/LensFlare.js @@ -1,15 +1,21 @@ +import { Object3D } from '../core/Object3D'; +import { NormalBlending } from '../constants'; +import { Color } from '../math/Color'; +import { Vector3 } from '../math/Vector3'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ */ -THREE.LensFlare = function ( texture, size, distance, blending, color ) { +function LensFlare ( texture, size, distance, blending, color ) { + this.isLensFlare = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.lensFlares = []; - this.positionScreen = new THREE.Vector3(); + this.positionScreen = new Vector3(); this.customUpdateCallback = undefined; if ( texture !== undefined ) { @@ -20,13 +26,13 @@ THREE.LensFlare = function ( texture, size, distance, blending, color ) { }; -THREE.LensFlare.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.LensFlare, + constructor: LensFlare, copy: function ( source ) { - THREE.Object3D.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source ); this.positionScreen.copy( source.positionScreen ); this.customUpdateCallback = source.customUpdateCallback; @@ -46,8 +52,8 @@ THREE.LensFlare.prototype = Object.assign( Object.create( THREE.Object3D.prototy if ( size === undefined ) size = - 1; if ( distance === undefined ) distance = 0; if ( opacity === undefined ) opacity = 1; - if ( color === undefined ) color = new THREE.Color( 0xffffff ); - if ( blending === undefined ) blending = THREE.NormalBlending; + if ( color === undefined ) color = new Color( 0xffffff ); + if ( blending === undefined ) blending = NormalBlending; distance = Math.min( distance, Math.max( 0, distance ) ); @@ -92,3 +98,6 @@ THREE.LensFlare.prototype = Object.assign( Object.create( THREE.Object3D.prototy } } ); + + +export { LensFlare }; \ No newline at end of file diff --git a/src/objects/Line.js b/src/objects/Line.js index 3ac2a013de65dd..1d8d922afa2806 100644 --- a/src/objects/Line.js +++ b/src/objects/Line.js @@ -1,34 +1,44 @@ +import { Sphere } from '../math/Sphere'; +import { Ray } from '../math/Ray'; +import { Matrix4 } from '../math/Matrix4'; +import { Object3D } from '../core/Object3D'; +import { Vector3 } from '../math/Vector3'; +import { LineBasicMaterial } from '../materials/LineBasicMaterial'; +import { BufferGeometry } from '../core/BufferGeometry'; +import { LineSegments } from './LineSegments'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Line = function ( geometry, material, mode ) { +function Line ( geometry, material, mode ) { + this.isLine = true; if ( mode === 1 ) { console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); - return new THREE.LineSegments( geometry, material ); + return new LineSegments( geometry, material ); } - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Line'; - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } ); + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); }; -THREE.Line.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Line.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Line, + constructor: Line, raycast: ( function () { - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); return function raycast( raycaster, intersects ) { @@ -52,13 +62,13 @@ THREE.Line.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), inverseMatrix.getInverse( matrixWorld ); ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - var vStart = new THREE.Vector3(); - var vEnd = new THREE.Vector3(); - var interSegment = new THREE.Vector3(); - var interRay = new THREE.Vector3(); - var step = this instanceof THREE.LineSegments ? 2 : 1; + var vStart = new Vector3(); + var vEnd = new Vector3(); + var interSegment = new Vector3(); + var interRay = new Vector3(); + var step = (this && this.isLineSegments) ? 2 : 1; - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { var index = geometry.index; var attributes = geometry.attributes; @@ -135,7 +145,7 @@ THREE.Line.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } - } else if ( geometry instanceof THREE.Geometry ) { + } else if ( (geometry && geometry.isGeometry) ) { var vertices = geometry.vertices; var nbVertices = vertices.length; @@ -180,3 +190,6 @@ THREE.Line.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } } ); + + +export { Line }; \ No newline at end of file diff --git a/src/objects/LineSegments.js b/src/objects/LineSegments.js index 60dde8671cf491..3ef59aa1596b1e 100644 --- a/src/objects/LineSegments.js +++ b/src/objects/LineSegments.js @@ -1,17 +1,23 @@ +import { Line } from './Line'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.LineSegments = function ( geometry, material ) { +function LineSegments ( geometry, material ) { + this.isLineSegments = true; - THREE.Line.call( this, geometry, material ); + Line.call( this, geometry, material ); this.type = 'LineSegments'; }; -THREE.LineSegments.prototype = Object.assign( Object.create( THREE.Line.prototype ), { +LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { - constructor: THREE.LineSegments + constructor: LineSegments } ); + + +export { LineSegments }; \ No newline at end of file diff --git a/src/objects/Mesh.js b/src/objects/Mesh.js index 7fb17a69a998a4..7a1ca46ee424cb 100644 --- a/src/objects/Mesh.js +++ b/src/objects/Mesh.js @@ -1,3 +1,15 @@ +import { Vector3 } from '../math/Vector3'; +import { Vector2 } from '../math/Vector2'; +import { Sphere } from '../math/Sphere'; +import { Ray } from '../math/Ray'; +import { Matrix4 } from '../math/Matrix4'; +import { Object3D } from '../core/Object3D'; +import { Triangle } from '../math/Triangle'; +import { Face3 } from '../core/Face3'; +import { DoubleSide, BackSide, TrianglesDrawMode } from '../constants'; +import { MeshBasicMaterial } from '../materials/MeshBasicMaterial'; +import { BufferGeometry } from '../core/BufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -5,24 +17,25 @@ * @author jonobr1 / http://jonobr1.com/ */ -THREE.Mesh = function ( geometry, material ) { +function Mesh ( geometry, material ) { + this.isMesh = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Mesh'; - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ); + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); - this.drawMode = THREE.TrianglesDrawMode; + this.drawMode = TrianglesDrawMode; this.updateMorphTargets(); }; -THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Mesh, + constructor: Mesh, setDrawMode: function ( value ) { @@ -32,7 +45,7 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), copy: function ( source ) { - THREE.Object3D.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source ); this.drawMode = source.drawMode; @@ -75,30 +88,30 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), raycast: ( function () { - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - var vA = new THREE.Vector3(); - var vB = new THREE.Vector3(); - var vC = new THREE.Vector3(); + var vA = new Vector3(); + var vB = new Vector3(); + var vC = new Vector3(); - var tempA = new THREE.Vector3(); - var tempB = new THREE.Vector3(); - var tempC = new THREE.Vector3(); + var tempA = new Vector3(); + var tempB = new Vector3(); + var tempC = new Vector3(); - var uvA = new THREE.Vector2(); - var uvB = new THREE.Vector2(); - var uvC = new THREE.Vector2(); + var uvA = new Vector2(); + var uvB = new Vector2(); + var uvC = new Vector2(); - var barycoord = new THREE.Vector3(); + var barycoord = new Vector3(); - var intersectionPoint = new THREE.Vector3(); - var intersectionPointWorld = new THREE.Vector3(); + var intersectionPoint = new Vector3(); + var intersectionPointWorld = new Vector3(); function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { - THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); + Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); uv1.multiplyScalar( barycoord.x ); uv2.multiplyScalar( barycoord.y ); @@ -115,13 +128,13 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), var intersect; var material = object.material; - if ( material.side === THREE.BackSide ) { + if ( material.side === BackSide ) { intersect = ray.intersectTriangle( pC, pB, pA, true, point ); } else { - intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point ); + intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); } @@ -162,7 +175,7 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } - intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ); + intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); intersection.faceIndex = a; } @@ -203,7 +216,7 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), var uvs, intersection; - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { var a, b, c; var index = geometry.index; @@ -259,10 +272,10 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } - } else if ( geometry instanceof THREE.Geometry ) { + } else if ( (geometry && geometry.isGeometry) ) { var fvA, fvB, fvC; - var isFaceMaterial = material instanceof THREE.MultiMaterial; + var isFaceMaterial = (material && material.isMultiMaterial); var materials = isFaceMaterial === true ? material.materials : null; var vertices = geometry.vertices; @@ -350,3 +363,6 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } } ); + + +export { Mesh }; \ No newline at end of file diff --git a/src/objects/Points.js b/src/objects/Points.js index 35af105e4dbf6e..411dab45587b20 100644 --- a/src/objects/Points.js +++ b/src/objects/Points.js @@ -1,27 +1,36 @@ +import { Sphere } from '../math/Sphere'; +import { Ray } from '../math/Ray'; +import { Matrix4 } from '../math/Matrix4'; +import { Object3D } from '../core/Object3D'; +import { Vector3 } from '../math/Vector3'; +import { PointsMaterial } from '../materials/PointsMaterial'; +import { BufferGeometry } from '../core/BufferGeometry'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.Points = function ( geometry, material ) { +function Points ( geometry, material ) { + this.isPoints = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Points'; - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } ); + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); }; -THREE.Points.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Points.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Points, + constructor: Points, raycast: ( function () { - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); return function raycast( raycaster, intersects ) { @@ -46,7 +55,7 @@ THREE.Points.prototype = Object.assign( Object.create( THREE.Object3D.prototype var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); var localThresholdSq = localThreshold * localThreshold; - var position = new THREE.Vector3(); + var position = new Vector3(); function testPoint( point, index ) { @@ -76,7 +85,7 @@ THREE.Points.prototype = Object.assign( Object.create( THREE.Object3D.prototype } - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { var index = geometry.index; var attributes = geometry.attributes; @@ -131,3 +140,6 @@ THREE.Points.prototype = Object.assign( Object.create( THREE.Object3D.prototype } } ); + + +export { Points }; \ No newline at end of file diff --git a/src/objects/Skeleton.js b/src/objects/Skeleton.js index c5f2c97eee34e7..ba25f13712d71c 100644 --- a/src/objects/Skeleton.js +++ b/src/objects/Skeleton.js @@ -1,3 +1,8 @@ +import { Matrix4 } from '../math/Matrix4'; +import { FloatType, RGBAFormat } from '../constants'; +import { DataTexture } from '../textures/DataTexture'; +import { _Math } from '../math/Math'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ @@ -5,11 +10,12 @@ * @author ikerr / http://verold.com */ -THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { +function Skeleton ( bones, boneInverses, useVertexTexture ) { + this.isSkeleton = true; this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; - this.identityMatrix = new THREE.Matrix4(); + this.identityMatrix = new Matrix4(); // copy the bone array @@ -30,14 +36,14 @@ THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix - size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) ); + size = _Math.nextPowerOfTwo( Math.ceil( size ) ); size = Math.max( size, 4 ); this.boneTextureWidth = size; this.boneTextureHeight = size; this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel - this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType ); + this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType ); } else { @@ -65,7 +71,7 @@ THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - this.boneInverses.push( new THREE.Matrix4() ); + this.boneInverses.push( new Matrix4() ); } @@ -75,7 +81,7 @@ THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { }; -Object.assign( THREE.Skeleton.prototype, { +Object.assign( Skeleton.prototype, { calculateInverses: function () { @@ -83,7 +89,7 @@ Object.assign( THREE.Skeleton.prototype, { for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - var inverse = new THREE.Matrix4(); + var inverse = new Matrix4(); if ( this.bones[ b ] ) { @@ -123,7 +129,7 @@ Object.assign( THREE.Skeleton.prototype, { if ( bone ) { - if ( bone.parent instanceof THREE.Bone ) { + if ( (bone.parent && bone.parent.isBone) ) { bone.matrix.getInverse( bone.parent.matrixWorld ); bone.matrix.multiply( bone.matrixWorld ); @@ -144,7 +150,7 @@ Object.assign( THREE.Skeleton.prototype, { update: ( function () { - var offsetMatrix = new THREE.Matrix4(); + var offsetMatrix = new Matrix4(); return function update() { @@ -173,8 +179,11 @@ Object.assign( THREE.Skeleton.prototype, { clone: function () { - return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); + return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); } } ); + + +export { Skeleton }; \ No newline at end of file diff --git a/src/objects/SkinnedMesh.js b/src/objects/SkinnedMesh.js index 8767cf16fa931b..c7d66de6772c33 100644 --- a/src/objects/SkinnedMesh.js +++ b/src/objects/SkinnedMesh.js @@ -1,18 +1,25 @@ +import { Mesh } from './Mesh'; +import { Vector4 } from '../math/Vector4'; +import { Skeleton } from './Skeleton'; +import { Bone } from './Bone'; +import { Matrix4 } from '../math/Matrix4'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author ikerr / http://verold.com */ -THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { +function SkinnedMesh ( geometry, material, useVertexTexture ) { + this.isSkinnedMesh = true; - THREE.Mesh.call( this, geometry, material ); + Mesh.call( this, geometry, material ); this.type = 'SkinnedMesh'; this.bindMode = "attached"; - this.bindMatrix = new THREE.Matrix4(); - this.bindMatrixInverse = new THREE.Matrix4(); + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); // init bones @@ -29,7 +36,7 @@ THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { gbone = this.geometry.bones[ b ]; - bone = new THREE.Bone( this ); + bone = new Bone( this ); bones.push( bone ); bone.name = gbone.name; @@ -61,14 +68,14 @@ THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { this.normalizeSkinWeights(); this.updateMatrixWorld( true ); - this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); + this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); }; -THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype ), { +SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { - constructor: THREE.SkinnedMesh, + constructor: SkinnedMesh, bind: function( skeleton, bindMatrix ) { @@ -97,7 +104,7 @@ THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype normalizeSkinWeights: function () { - if ( this.geometry instanceof THREE.Geometry ) { + if ( (this.geometry && this.geometry.isGeometry) ) { for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) { @@ -117,9 +124,9 @@ THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype } - } else if ( this.geometry instanceof THREE.BufferGeometry ) { + } else if ( (this.geometry && this.geometry.isBufferGeometry) ) { - var vec = new THREE.Vector4(); + var vec = new Vector4(); var skinWeight = this.geometry.attributes.skinWeight; @@ -152,7 +159,7 @@ THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype updateMatrixWorld: function( force ) { - THREE.Mesh.prototype.updateMatrixWorld.call( this, true ); + Mesh.prototype.updateMatrixWorld.call( this, true ); if ( this.bindMode === "attached" ) { @@ -177,3 +184,6 @@ THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype } } ); + + +export { SkinnedMesh }; \ No newline at end of file diff --git a/src/objects/Sprite.js b/src/objects/Sprite.js index 082cf9be3e3106..b056655ed0485b 100644 --- a/src/objects/Sprite.js +++ b/src/objects/Sprite.js @@ -1,25 +1,30 @@ +import { Vector3 } from '../math/Vector3'; +import { Object3D } from '../core/Object3D'; +import { SpriteMaterial } from '../materials/SpriteMaterial'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Sprite = function ( material ) { +function Sprite ( material ) { + this.isSprite = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Sprite'; - this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial(); + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); }; -THREE.Sprite.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Sprite, + constructor: Sprite, raycast: ( function () { - var matrixPosition = new THREE.Vector3(); + var matrixPosition = new Vector3(); return function raycast( raycaster, intersects ) { @@ -54,3 +59,6 @@ THREE.Sprite.prototype = Object.assign( Object.create( THREE.Object3D.prototype } } ); + + +export { Sprite }; \ No newline at end of file diff --git a/src/renderers/WebGLRenderTarget.js b/src/renderers/WebGLRenderTarget.js index 295ed6818c9e48..28528189fb6da7 100644 --- a/src/renderers/WebGLRenderTarget.js +++ b/src/renderers/WebGLRenderTarget.js @@ -1,3 +1,9 @@ +import { EventDispatcher } from '../core/EventDispatcher'; +import { Texture } from '../textures/Texture'; +import { LinearFilter } from '../constants'; +import { Vector4 } from '../math/Vector4'; +import { _Math } from '../math/Math'; + /** * @author szimek / https://github.com/szimek/ * @author alteredq / http://alteredqualia.com/ @@ -9,23 +15,24 @@ * Texture parameters for an auto-generated target texture * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers */ -THREE.WebGLRenderTarget = function ( width, height, options ) { +function WebGLRenderTarget ( width, height, options ) { + this.isWebGLRenderTarget = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.width = width; this.height = height; - this.scissor = new THREE.Vector4( 0, 0, width, height ); + this.scissor = new Vector4( 0, 0, width, height ); this.scissorTest = false; - this.viewport = new THREE.Vector4( 0, 0, width, height ); + this.viewport = new Vector4( 0, 0, width, height ); options = options || {}; - if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter; + if ( options.minFilter === undefined ) options.minFilter = LinearFilter; - this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; @@ -33,7 +40,7 @@ THREE.WebGLRenderTarget = function ( width, height, options ) { }; -Object.assign( THREE.WebGLRenderTarget.prototype, THREE.EventDispatcher.prototype, { +Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, { setSize: function ( width, height ) { @@ -81,3 +88,6 @@ Object.assign( THREE.WebGLRenderTarget.prototype, THREE.EventDispatcher.prototyp } } ); + + +export { WebGLRenderTarget }; \ No newline at end of file diff --git a/src/renderers/WebGLRenderTargetCube.js b/src/renderers/WebGLRenderTargetCube.js index b64bb135b70c3e..b84faa384242ee 100644 --- a/src/renderers/WebGLRenderTargetCube.js +++ b/src/renderers/WebGLRenderTargetCube.js @@ -1,15 +1,21 @@ +import { WebGLRenderTarget } from './WebGLRenderTarget'; + /** * @author alteredq / http://alteredqualia.com */ -THREE.WebGLRenderTargetCube = function ( width, height, options ) { +function WebGLRenderTargetCube ( width, height, options ) { + this.isWebGLRenderTargetCube = this.isWebGLRenderTarget = true; - THREE.WebGLRenderTarget.call( this, width, height, options ); + WebGLRenderTarget.call( this, width, height, options ); this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 this.activeMipMapLevel = 0; }; -THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype ); -THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube; +WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); +WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; + + +export { WebGLRenderTargetCube }; \ No newline at end of file diff --git a/src/renderers/WebGLRenderer.js b/src/renderers/WebGLRenderer.js index 92f2c4454ceb74..116593c36684ed 100644 --- a/src/renderers/WebGLRenderer.js +++ b/src/renderers/WebGLRenderer.js @@ -1,3 +1,36 @@ +import { MaxEquation, MinEquation, RGB_ETC1_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT5_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT1_Format, RGB_S3TC_DXT1_Format, SrcAlphaSaturateFactor, OneMinusDstColorFactor, DstColorFactor, OneMinusDstAlphaFactor, DstAlphaFactor, OneMinusSrcAlphaFactor, SrcAlphaFactor, OneMinusSrcColorFactor, SrcColorFactor, OneFactor, ZeroFactor, ReverseSubtractEquation, SubtractEquation, AddEquation, DepthFormat, LuminanceAlphaFormat, LuminanceFormat, RGBAFormat, RGBFormat, AlphaFormat, HalfFloatType, FloatType, UnsignedIntType, IntType, UnsignedShortType, ShortType, ByteType, UnsignedShort565Type, UnsignedShort5551Type, UnsignedShort4444Type, UnsignedByteType, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestFilter, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, FrontFaceDirectionCW, NoBlending, BackSide, DoubleSide, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, NoColors, FlatShading, LinearToneMapping } from '../constants'; +import { Matrix4 } from '../math/Matrix4'; +import { WebGLUniforms } from './webgl/WebGLUniforms'; +import { UniformsUtils } from './shaders/UniformsUtils'; +import { ShaderLib } from './shaders/ShaderLib'; +import { LensFlarePlugin } from './webgl/plugins/LensFlarePlugin'; +import { SpritePlugin } from './webgl/plugins/SpritePlugin'; +import { WebGLShadowMap } from './webgl/WebGLShadowMap'; +import { ShaderMaterial } from '../materials/ShaderMaterial'; +import { BoxBufferGeometry } from '../extras/geometries/BoxBufferGeometry'; +import { Mesh } from '../objects/Mesh'; +import { MeshBasicMaterial } from '../materials/MeshBasicMaterial'; +import { PlaneBufferGeometry } from '../extras/geometries/PlaneBufferGeometry'; +import { PerspectiveCamera } from '../cameras/PerspectiveCamera'; +import { OrthographicCamera } from '../cameras/OrthographicCamera'; +import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer'; +import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer'; +import { WebGLLights } from './webgl/WebGLLights'; +import { WebGLPrograms } from './webgl/WebGLPrograms'; +import { WebGLObjects } from './webgl/WebGLObjects'; +import { WebGLTextures } from './webgl/WebGLTextures'; +import { WebGLProperties } from './webgl/WebGLProperties'; +import { WebGLState } from './webgl/WebGLState'; +import { WebGLCapabilities } from './webgl/WebGLCapabilities'; +import { BufferGeometry } from '../core/BufferGeometry'; +import { WebGLExtensions } from './webgl/WebGLExtensions'; +import { Vector3 } from '../math/Vector3'; +import { Sphere } from '../math/Sphere'; +import { WebGLClipping } from './webgl/WebGLClipping'; +import { Frustum } from '../math/Frustum'; +import { Vector4 } from '../math/Vector4'; +import { Color } from '../math/Color'; + /** * @author supereggbert / http://www.paulbrunt.co.uk/ * @author mrdoob / http://mrdoob.com/ @@ -6,9 +39,10 @@ * @author tschw */ -THREE.WebGLRenderer = function ( parameters ) { +function WebGLRenderer ( parameters ) { + this.isWebGLRenderer = true; - console.log( 'THREE.WebGLRenderer', THREE.REVISION ); + console.log( 'THREE.WebGLRenderer', "79dev" ); parameters = parameters || {}; @@ -67,7 +101,7 @@ THREE.WebGLRenderer = function ( parameters ) { // tone mapping - this.toneMapping = THREE.LinearToneMapping; + this.toneMapping = LinearToneMapping; this.toneMappingExposure = 1.0; this.toneMappingWhitePoint = 1.0; @@ -89,10 +123,10 @@ THREE.WebGLRenderer = function ( parameters ) { _currentGeometryProgram = '', _currentCamera = null, - _currentScissor = new THREE.Vector4(), + _currentScissor = new Vector4(), _currentScissorTest = null, - _currentViewport = new THREE.Vector4(), + _currentViewport = new Vector4(), // @@ -100,7 +134,7 @@ THREE.WebGLRenderer = function ( parameters ) { // - _clearColor = new THREE.Color( 0x000000 ), + _clearColor = new Color( 0x000000 ), _clearAlpha = 0, _width = _canvas.width, @@ -108,28 +142,28 @@ THREE.WebGLRenderer = function ( parameters ) { _pixelRatio = 1, - _scissor = new THREE.Vector4( 0, 0, _width, _height ), + _scissor = new Vector4( 0, 0, _width, _height ), _scissorTest = false, - _viewport = new THREE.Vector4( 0, 0, _width, _height ), + _viewport = new Vector4( 0, 0, _width, _height ), // frustum - _frustum = new THREE.Frustum(), + _frustum = new Frustum(), // clipping - _clipping = new THREE.WebGLClipping(), + _clipping = new WebGLClipping(), _clippingEnabled = false, _localClippingEnabled = false, - _sphere = new THREE.Sphere(), + _sphere = new Sphere(), // camera matrices cache - _projScreenMatrix = new THREE.Matrix4(), + _projScreenMatrix = new Matrix4(), - _vector3 = new THREE.Vector3(), + _vector3 = new Vector3(), // light arrays cache @@ -229,7 +263,7 @@ THREE.WebGLRenderer = function ( parameters ) { } - var extensions = new THREE.WebGLExtensions( _gl ); + var extensions = new WebGLExtensions( _gl ); extensions.get( 'WEBGL_depth_texture' ); extensions.get( 'OES_texture_float' ); @@ -241,40 +275,40 @@ THREE.WebGLRenderer = function ( parameters ) { if ( extensions.get( 'OES_element_index_uint' ) ) { - THREE.BufferGeometry.MaxIndex = 4294967296; + BufferGeometry.MaxIndex = 4294967296; } - var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters ); + var capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL ); - var properties = new THREE.WebGLProperties(); - var textures = new THREE.WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info ); - var objects = new THREE.WebGLObjects( _gl, properties, this.info ); - var programCache = new THREE.WebGLPrograms( this, capabilities ); - var lightCache = new THREE.WebGLLights(); + var state = new WebGLState( _gl, extensions, paramThreeToGL ); + var properties = new WebGLProperties(); + var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info ); + var objects = new WebGLObjects( _gl, properties, this.info ); + var programCache = new WebGLPrograms( this, capabilities ); + var lightCache = new WebGLLights(); this.info.programs = programCache.programs; - var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender ); - var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); + var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender ); + var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); // - var backgroundCamera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); - var backgroundCamera2 = new THREE.PerspectiveCamera(); - var backgroundPlaneMesh = new THREE.Mesh( - new THREE.PlaneBufferGeometry( 2, 2 ), - new THREE.MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) + var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + var backgroundCamera2 = new PerspectiveCamera(); + var backgroundPlaneMesh = new Mesh( + new PlaneBufferGeometry( 2, 2 ), + new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) ); - var backgroundBoxShader = THREE.ShaderLib[ 'cube' ]; - var backgroundBoxMesh = new THREE.Mesh( - new THREE.BoxBufferGeometry( 5, 5, 5 ), - new THREE.ShaderMaterial( { + var backgroundBoxShader = ShaderLib[ 'cube' ]; + var backgroundBoxMesh = new Mesh( + new BoxBufferGeometry( 5, 5, 5 ), + new ShaderMaterial( { uniforms: backgroundBoxShader.uniforms, vertexShader: backgroundBoxShader.vertexShader, fragmentShader: backgroundBoxShader.fragmentShader, - side: THREE.BackSide, + side: BackSide, depthTest: false, depthWrite: false, fog: false @@ -334,15 +368,15 @@ THREE.WebGLRenderer = function ( parameters ) { // shadow map - var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects, capabilities ); + var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities ); this.shadowMap = shadowMap; // Plugins - var spritePlugin = new THREE.SpritePlugin( this, sprites ); - var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares ); + var spritePlugin = new SpritePlugin( this, sprites ); + var lensFlarePlugin = new LensFlarePlugin( this, lensFlares ); // API @@ -599,7 +633,7 @@ THREE.WebGLRenderer = function ( parameters ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); - if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) { + if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === FlatShading ) { for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { @@ -644,7 +678,7 @@ THREE.WebGLRenderer = function ( parameters ) { } - if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { + if ( object.hasColors && material.vertexColors !== NoColors ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); @@ -796,7 +830,7 @@ THREE.WebGLRenderer = function ( parameters ) { // - if ( object instanceof THREE.Mesh ) { + if ( (object && object.isMesh) ) { if ( material.wireframe === true ) { @@ -807,15 +841,15 @@ THREE.WebGLRenderer = function ( parameters ) { switch ( object.drawMode ) { - case THREE.TrianglesDrawMode: + case TrianglesDrawMode: renderer.setMode( _gl.TRIANGLES ); break; - case THREE.TriangleStripDrawMode: + case TriangleStripDrawMode: renderer.setMode( _gl.TRIANGLE_STRIP ); break; - case THREE.TriangleFanDrawMode: + case TriangleFanDrawMode: renderer.setMode( _gl.TRIANGLE_FAN ); break; @@ -824,7 +858,7 @@ THREE.WebGLRenderer = function ( parameters ) { } - } else if ( object instanceof THREE.Line ) { + } else if ( (object && object.isLine) ) { var lineWidth = material.linewidth; @@ -832,7 +866,7 @@ THREE.WebGLRenderer = function ( parameters ) { state.setLineWidth( lineWidth * getTargetPixelRatio() ); - if ( object instanceof THREE.LineSegments ) { + if ( (object && object.isLineSegments) ) { renderer.setMode( _gl.LINES ); @@ -842,13 +876,13 @@ THREE.WebGLRenderer = function ( parameters ) { } - } else if ( object instanceof THREE.Points ) { + } else if ( (object && object.isPoints) ) { renderer.setMode( _gl.POINTS ); } - if ( geometry instanceof THREE.InstancedBufferGeometry ) { + if ( (geometry && geometry.isInstancedBufferGeometry) ) { if ( geometry.maxInstancedCount > 0 ) { @@ -868,7 +902,7 @@ THREE.WebGLRenderer = function ( parameters ) { var extension; - if ( geometry instanceof THREE.InstancedBufferGeometry ) { + if ( (geometry && geometry.isInstancedBufferGeometry) ) { extension = extensions.get( 'ANGLE_instanced_arrays' ); @@ -942,13 +976,13 @@ THREE.WebGLRenderer = function ( parameters ) { var size = geometryAttribute.itemSize; var buffer = objects.getAttributeBuffer( geometryAttribute ); - if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) { + if ( (geometryAttribute && geometryAttribute.isInterleavedBufferAttribute) ) { var data = geometryAttribute.data; var stride = data.stride; var offset = geometryAttribute.offset; - if ( data instanceof THREE.InstancedInterleavedBuffer ) { + if ( (data && data.isInstancedInterleavedBuffer) ) { state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); @@ -969,7 +1003,7 @@ THREE.WebGLRenderer = function ( parameters ) { } else { - if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) { + if ( (geometryAttribute && geometryAttribute.isInstancedBufferAttribute) ) { state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); @@ -1083,7 +1117,7 @@ THREE.WebGLRenderer = function ( parameters ) { this.render = function ( scene, camera, renderTarget, forceClear ) { - if ( camera instanceof THREE.Camera === false ) { + if ( (camera && camera.isCamera) === false ) { console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); return; @@ -1169,7 +1203,7 @@ THREE.WebGLRenderer = function ( parameters ) { glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - } else if ( background instanceof THREE.Color ) { + } else if ( (background && background.isColor) ) { glClearColor( background.r, background.g, background.b, 1 ); @@ -1181,7 +1215,7 @@ THREE.WebGLRenderer = function ( parameters ) { } - if ( background instanceof THREE.CubeTexture ) { + if ( (background && background.isCubeTexture) ) { backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); @@ -1195,7 +1229,7 @@ THREE.WebGLRenderer = function ( parameters ) { _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); - } else if ( background instanceof THREE.Texture ) { + } else if ( (background && background.isTexture) ) { backgroundPlaneMesh.material.map = background; @@ -1218,7 +1252,7 @@ THREE.WebGLRenderer = function ( parameters ) { // opaque pass (front-to-back order) - state.setBlending( THREE.NoBlending ); + state.setBlending( NoBlending ); renderObjects( opaqueObjects, camera, fog ); // transparent pass (back-to-front order) @@ -1356,11 +1390,11 @@ THREE.WebGLRenderer = function ( parameters ) { if ( object.layers.test( camera.layers ) ) { - if ( object instanceof THREE.Light ) { + if ( (object && object.isLight) ) { lights.push( object ); - } else if ( object instanceof THREE.Sprite ) { + } else if ( (object && object.isSprite) ) { if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) { @@ -1368,11 +1402,11 @@ THREE.WebGLRenderer = function ( parameters ) { } - } else if ( object instanceof THREE.LensFlare ) { + } else if ( (object && object.isLensFlare) ) { lensFlares.push( object ); - } else if ( object instanceof THREE.ImmediateRenderObject ) { + } else if ( (object && object.isImmediateRenderObject) ) { if ( _this.sortObjects === true ) { @@ -1383,9 +1417,9 @@ THREE.WebGLRenderer = function ( parameters ) { pushRenderItem( object, null, object.material, _vector3.z, null ); - } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) { + } else if ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) { - if ( object instanceof THREE.SkinnedMesh ) { + if ( (object && object.isSkinnedMesh) ) { object.skeleton.update(); @@ -1406,7 +1440,7 @@ THREE.WebGLRenderer = function ( parameters ) { var geometry = objects.update( object ); - if ( material instanceof THREE.MultiMaterial ) { + if ( (material && material.isMultiMaterial) ) { var groups = geometry.groups; var materials = material.materials; @@ -1462,7 +1496,7 @@ THREE.WebGLRenderer = function ( parameters ) { object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); - if ( object instanceof THREE.ImmediateRenderObject ) { + if ( (object && object.isImmediateRenderObject) ) { setMaterial( material ); @@ -1524,11 +1558,11 @@ THREE.WebGLRenderer = function ( parameters ) { if ( parameters.shaderID ) { - var shader = THREE.ShaderLib[ parameters.shaderID ]; + var shader = ShaderLib[ parameters.shaderID ]; materialProperties.__webglShader = { name: material.type, - uniforms: THREE.UniformsUtils.clone( shader.uniforms ), + uniforms: UniformsUtils.clone( shader.uniforms ), vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader }; @@ -1589,8 +1623,8 @@ THREE.WebGLRenderer = function ( parameters ) { var uniforms = materialProperties.__webglShader.uniforms; - if ( ! ( material instanceof THREE.ShaderMaterial ) && - ! ( material instanceof THREE.RawShaderMaterial ) || + if ( ! ( (material && material.isShaderMaterial) ) && + ! ( (material && material.isRawShaderMaterial) ) || material.clipping === true ) { materialProperties.numClippingPlanes = _clipping.numPlanes; @@ -1623,22 +1657,22 @@ THREE.WebGLRenderer = function ( parameters ) { var progUniforms = materialProperties.program.getUniforms(), uniformsList = - THREE.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); materialProperties.uniformsList = uniformsList; materialProperties.dynamicUniforms = - THREE.WebGLUniforms.splitDynamic( uniformsList, uniforms ); + WebGLUniforms.splitDynamic( uniformsList, uniforms ); } function setMaterial( material ) { - if ( material.side !== THREE.DoubleSide ) + if ( material.side !== DoubleSide ) state.enable( _gl.CULL_FACE ); else state.disable( _gl.CULL_FACE ); - state.setFlipSided( material.side === THREE.BackSide ); + state.setFlipSided( material.side === BackSide ); if ( material.transparent === true ) { @@ -1646,7 +1680,7 @@ THREE.WebGLRenderer = function ( parameters ) { } else { - state.setBlending( THREE.NoBlending ); + state.setBlending( NoBlending ); } @@ -1765,9 +1799,9 @@ THREE.WebGLRenderer = function ( parameters ) { // load material specific uniforms // (shader material also gets them for the sake of genericity) - if ( material instanceof THREE.ShaderMaterial || - material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshStandardMaterial || + if ( (material && material.isShaderMaterial) || + (material && material.isMeshPhongMaterial) || + (material && material.isMeshStandardMaterial) || material.envMap ) { var uCamPos = p_uniforms.map.cameraPosition; @@ -1781,11 +1815,11 @@ THREE.WebGLRenderer = function ( parameters ) { } - if ( material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshStandardMaterial || - material instanceof THREE.ShaderMaterial || + if ( (material && material.isMeshPhongMaterial) || + (material && material.isMeshLambertMaterial) || + (material && material.isMeshBasicMaterial) || + (material && material.isMeshStandardMaterial) || + (material && material.isShaderMaterial) || material.skinning ) { p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); @@ -1851,11 +1885,11 @@ THREE.WebGLRenderer = function ( parameters ) { } - if ( material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshStandardMaterial || - material instanceof THREE.MeshDepthMaterial ) { + if ( (material && material.isMeshBasicMaterial) || + (material && material.isMeshLambertMaterial) || + (material && material.isMeshPhongMaterial) || + (material && material.isMeshStandardMaterial) || + (material && material.isMeshDepthMaterial) ) { refreshUniformsCommon( m_uniforms, material ); @@ -1863,36 +1897,36 @@ THREE.WebGLRenderer = function ( parameters ) { // refresh single material specific uniforms - if ( material instanceof THREE.LineBasicMaterial ) { + if ( (material && material.isLineBasicMaterial) ) { refreshUniformsLine( m_uniforms, material ); - } else if ( material instanceof THREE.LineDashedMaterial ) { + } else if ( (material && material.isLineDashedMaterial) ) { refreshUniformsLine( m_uniforms, material ); refreshUniformsDash( m_uniforms, material ); - } else if ( material instanceof THREE.PointsMaterial ) { + } else if ( (material && material.isPointsMaterial) ) { refreshUniformsPoints( m_uniforms, material ); - } else if ( material instanceof THREE.MeshLambertMaterial ) { + } else if ( (material && material.isMeshLambertMaterial) ) { refreshUniformsLambert( m_uniforms, material ); - } else if ( material instanceof THREE.MeshPhongMaterial ) { + } else if ( (material && material.isMeshPhongMaterial) ) { refreshUniformsPhong( m_uniforms, material ); - } else if ( material instanceof THREE.MeshPhysicalMaterial ) { + } else if ( (material && material.isMeshPhysicalMaterial) ) { refreshUniformsPhysical( m_uniforms, material ); - } else if ( material instanceof THREE.MeshStandardMaterial ) { + } else if ( (material && material.isMeshStandardMaterial) ) { refreshUniformsStandard( m_uniforms, material ); - } else if ( material instanceof THREE.MeshDepthMaterial ) { + } else if ( (material && material.isMeshDepthMaterial) ) { if ( material.displacementMap ) { @@ -1902,13 +1936,13 @@ THREE.WebGLRenderer = function ( parameters ) { } - } else if ( material instanceof THREE.MeshNormalMaterial ) { + } else if ( (material && material.isMeshNormalMaterial) ) { m_uniforms.opacity.value = material.opacity; } - THREE.WebGLUniforms.upload( + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this ); } @@ -1927,10 +1961,10 @@ THREE.WebGLRenderer = function ( parameters ) { if ( dynUniforms !== null ) { - THREE.WebGLUniforms.evalDynamic( + WebGLUniforms.evalDynamic( dynUniforms, m_uniforms, object, camera ); - THREE.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); + WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); } @@ -2014,7 +2048,7 @@ THREE.WebGLRenderer = function ( parameters ) { if ( uvScaleMap !== undefined ) { // backwards compatibility - if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) { + if ( (uvScaleMap && uvScaleMap.isWebGLRenderTarget) ) { uvScaleMap = uvScaleMap.texture; @@ -2033,7 +2067,7 @@ THREE.WebGLRenderer = function ( parameters ) { // WebGLRenderTargetCube will be flipped for backwards compatibility // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future - uniforms.flipEnvMap.value = ( ! ( material.envMap instanceof THREE.CubeTexture ) ) ? 1 : - 1; + uniforms.flipEnvMap.value = ( ! ( (material.envMap && material.envMap.isCubeTexture) ) ) ? 1 : - 1; uniforms.reflectivity.value = material.reflectivity; uniforms.refractionRatio.value = material.refractionRatio; @@ -2079,12 +2113,12 @@ THREE.WebGLRenderer = function ( parameters ) { uniforms.fogColor.value = fog.color; - if ( fog instanceof THREE.Fog ) { + if ( (fog && fog.isFog) ) { uniforms.fogNear.value = fog.near; uniforms.fogFar.value = fog.far; - } else if ( fog instanceof THREE.FogExp2 ) { + } else if ( (fog && fog.isFogExp2) ) { uniforms.fogDensity.value = fog.density; @@ -2282,13 +2316,13 @@ THREE.WebGLRenderer = function ( parameters ) { shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; - if ( light instanceof THREE.AmbientLight ) { + if ( (light && light.isAmbientLight) ) { r += color.r * intensity; g += color.g * intensity; b += color.b * intensity; - } else if ( light instanceof THREE.DirectionalLight ) { + } else if ( (light && light.isDirectionalLight) ) { var uniforms = lightCache.get( light ); @@ -2312,7 +2346,7 @@ THREE.WebGLRenderer = function ( parameters ) { _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; _lights.directional[ directionalLength ++ ] = uniforms; - } else if ( light instanceof THREE.SpotLight ) { + } else if ( (light && light.isSpotLight) ) { var uniforms = lightCache.get( light ); @@ -2345,7 +2379,7 @@ THREE.WebGLRenderer = function ( parameters ) { _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; _lights.spot[ spotLength ++ ] = uniforms; - } else if ( light instanceof THREE.PointLight ) { + } else if ( (light && light.isPointLight) ) { var uniforms = lightCache.get( light ); @@ -2370,7 +2404,7 @@ THREE.WebGLRenderer = function ( parameters ) { if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) { - _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4(); + _lights.pointShadowMatrix[ pointLength ] = new Matrix4(); } @@ -2381,7 +2415,7 @@ THREE.WebGLRenderer = function ( parameters ) { _lights.point[ pointLength ++ ] = uniforms; - } else if ( light instanceof THREE.HemisphereLight ) { + } else if ( (light && light.isHemisphereLight) ) { var uniforms = lightCache.get( light ); @@ -2416,7 +2450,7 @@ THREE.WebGLRenderer = function ( parameters ) { this.setFaceCulling = function ( cullFace, frontFaceDirection ) { state.setCullFace( cullFace ); - state.setFlipSided( frontFaceDirection === THREE.FrontFaceDirectionCW ); + state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW ); }; @@ -2448,7 +2482,7 @@ THREE.WebGLRenderer = function ( parameters ) { // backwards compatibility: peel texture.texture return function setTexture2D( texture, slot ) { - if ( texture instanceof THREE.WebGLRenderTarget ) { + if ( (texture && texture.isWebGLRenderTarget) ) { if ( ! warned ) { @@ -2493,7 +2527,7 @@ THREE.WebGLRenderer = function ( parameters ) { return function setTextureCube( texture, slot ) { // backwards compatibility: peel texture.texture - if ( texture instanceof THREE.WebGLRenderTargetCube ) { + if ( (texture && texture.isWebGLRenderTargetCube) ) { if ( ! warned ) { @@ -2508,7 +2542,7 @@ THREE.WebGLRenderer = function ( parameters ) { // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture // TODO: unify these code paths - if ( texture instanceof THREE.CubeTexture || + if ( (texture && texture.isCubeTexture) || ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/ @@ -2544,7 +2578,7 @@ THREE.WebGLRenderer = function ( parameters ) { } - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); var framebuffer; if ( renderTarget ) { @@ -2600,7 +2634,7 @@ THREE.WebGLRenderer = function ( parameters ) { this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { - if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) { + if ( (renderTarget && renderTarget.isWebGLRenderTarget) === false ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); return; @@ -2625,17 +2659,17 @@ THREE.WebGLRenderer = function ( parameters ) { var texture = renderTarget.texture; - if ( texture.format !== THREE.RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + if ( texture.format !== RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); return; } - if ( texture.type !== THREE.UnsignedByteType && + if ( texture.type !== UnsignedByteType && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && - ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) && - ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { + ! ( texture.type === FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) && + ! ( texture.type === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); return; @@ -2678,70 +2712,70 @@ THREE.WebGLRenderer = function ( parameters ) { var extension; - if ( p === THREE.RepeatWrapping ) return _gl.REPEAT; - if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; - if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; + if ( p === RepeatWrapping ) return _gl.REPEAT; + if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; + if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; - if ( p === THREE.NearestFilter ) return _gl.NEAREST; - if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; - if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; + if ( p === NearestFilter ) return _gl.NEAREST; + if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; + if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; - if ( p === THREE.LinearFilter ) return _gl.LINEAR; - if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; - if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; + if ( p === LinearFilter ) return _gl.LINEAR; + if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; + if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; - if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; - if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; - if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; - if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; + if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE; + if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; + if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; - if ( p === THREE.ByteType ) return _gl.BYTE; - if ( p === THREE.ShortType ) return _gl.SHORT; - if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; - if ( p === THREE.IntType ) return _gl.INT; - if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; - if ( p === THREE.FloatType ) return _gl.FLOAT; + if ( p === ByteType ) return _gl.BYTE; + if ( p === ShortType ) return _gl.SHORT; + if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT; + if ( p === IntType ) return _gl.INT; + if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT; + if ( p === FloatType ) return _gl.FLOAT; extension = extensions.get( 'OES_texture_half_float' ); if ( extension !== null ) { - if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES; + if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES; } - if ( p === THREE.AlphaFormat ) return _gl.ALPHA; - if ( p === THREE.RGBFormat ) return _gl.RGB; - if ( p === THREE.RGBAFormat ) return _gl.RGBA; - if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; - if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; - if ( p === THREE.DepthFormat ) return _gl.DEPTH_COMPONENT; + if ( p === AlphaFormat ) return _gl.ALPHA; + if ( p === RGBFormat ) return _gl.RGB; + if ( p === RGBAFormat ) return _gl.RGBA; + if ( p === LuminanceFormat ) return _gl.LUMINANCE; + if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; + if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT; - if ( p === THREE.AddEquation ) return _gl.FUNC_ADD; - if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT; - if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; + if ( p === AddEquation ) return _gl.FUNC_ADD; + if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT; + if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; - if ( p === THREE.ZeroFactor ) return _gl.ZERO; - if ( p === THREE.OneFactor ) return _gl.ONE; - if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR; - if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; - if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA; - if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; - if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA; - if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; + if ( p === ZeroFactor ) return _gl.ZERO; + if ( p === OneFactor ) return _gl.ONE; + if ( p === SrcColorFactor ) return _gl.SRC_COLOR; + if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; + if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA; + if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; + if ( p === DstAlphaFactor ) return _gl.DST_ALPHA; + if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; - if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR; - if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; - if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; + if ( p === DstColorFactor ) return _gl.DST_COLOR; + if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; + if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); if ( extension !== null ) { - if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; - if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; - if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; - if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; } @@ -2749,10 +2783,10 @@ THREE.WebGLRenderer = function ( parameters ) { if ( extension !== null ) { - if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; } @@ -2760,7 +2794,7 @@ THREE.WebGLRenderer = function ( parameters ) { if ( extension !== null ) { - if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; + if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; } @@ -2768,8 +2802,8 @@ THREE.WebGLRenderer = function ( parameters ) { if ( extension !== null ) { - if ( p === THREE.MinEquation ) return extension.MIN_EXT; - if ( p === THREE.MaxEquation ) return extension.MAX_EXT; + if ( p === MinEquation ) return extension.MIN_EXT; + if ( p === MaxEquation ) return extension.MAX_EXT; } @@ -2778,3 +2812,6 @@ THREE.WebGLRenderer = function ( parameters ) { } }; + + +export { WebGLRenderer }; diff --git a/src/renderers/shaders/ShaderChunk.js b/src/renderers/shaders/ShaderChunk.js index 6ffa98166bfa21..396154e1bcec82 100644 --- a/src/renderers/shaders/ShaderChunk.js +++ b/src/renderers/shaders/ShaderChunk.js @@ -1 +1,112 @@ -THREE.ShaderChunk = {}; +var ShaderChunk; + +ShaderChunk = {}; + +ShaderChunk["alphamap_fragment"] = "#ifdef USE_ALPHAMAP\n\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n"; +ShaderChunk["alphamap_pars_fragment"] = "#ifdef USE_ALPHAMAP\n\n\tuniform sampler2D alphaMap;\n\n#endif\n"; +ShaderChunk["alphatest_fragment"] = "#ifdef ALPHATEST\n\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n"; +ShaderChunk["ambient_pars"] = "uniform vec3 ambientLightColor;\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n"; +ShaderChunk["aomap_fragment"] = "#ifdef USE_AOMAP\n\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\n\t#endif\n\n#endif\n"; +ShaderChunk["aomap_pars_fragment"] = "#ifdef USE_AOMAP\n\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n\n#endif"; +ShaderChunk["begin_vertex"] = "\nvec3 transformed = vec3( position );\n"; +ShaderChunk["beginnormal_vertex"] = "\nvec3 objectNormal = vec3( normal );\n"; +ShaderChunk["bsdfs"] = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n\n}\n\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\n\t\tif( decayExponent > 0.0 ) {\n\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\n\t\t\t// based upon Frostbite 3 Moving to Physically-based Rendering\n\t\t\t// page 32, equation 26: E[window1]\n\t\t\t// http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\n\t\t\t// this is intended to be used on spot and point lights who are represented as luminous intensity\n\t\t\t// but who must be converted to luminous irradiance for surface lighting calculation\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n\n#else\n\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\n#endif\n\n\t\t}\n\n\t\treturn 1.0;\n}\n\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\n\treturn RECIPROCAL_PI * diffuseColor;\n\n} // validated\n\n\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\n\t// Original approximation by Christophe Schlick '94\n\t//;float fresnel = pow( 1.0 - dotLH, 5.0 );\n\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n\n} // validated\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (34)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\t// geometry term = G(l)⋅G(v) / 4(n⋅l)(n⋅v)\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\n\treturn 1.0 / ( gl * gv );\n\n} // validated\n\n// from page 12, listing 2 of http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\tfloat a2 = pow2( alpha );\n\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\n\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\n\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n\n}\n\n\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat alpha = pow2( roughness ); // UE4's roughness\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\n\tfloat D = D_GGX( alpha, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\n\tvec4 r = roughness * c0 + c1;\n\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\n\treturn specularColor * AB.x + AB.y;\n\n} // validated\n\n\nfloat G_BlinnPhong_Implicit( /* const in float dotNL, const in float dotNV */ ) {\n\n\t// geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v)\n\treturn 0.25;\n\n}\n\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n\n}\n\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\t//float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\t//float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\n\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; +ShaderChunk["bumpmap_pars_fragment"] = "#ifdef USE_BUMPMAP\n\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\n\t// Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n\t// http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n\t// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n\tvec2 dHdxy_fwd() {\n\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n\t\treturn vec2( dBx, dBy );\n\n\t}\n\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\t\t// normalized\n\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\n\t}\n\n#endif\n"; +ShaderChunk["clipping_planes_fragment"] = "#if NUM_CLIPPING_PLANES > 0\n\n\tfor ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\n\t}\n\n#endif\n"; +ShaderChunk["clipping_planes_pars_fragment"] = "#if NUM_CLIPPING_PLANES > 0\n\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n\n#endif\n"; +ShaderChunk["clipping_planes_pars_vertex"] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; +ShaderChunk["clipping_planes_vertex"] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n\n"; +ShaderChunk["color_fragment"] = "#ifdef USE_COLOR\n\n\tdiffuseColor.rgb *= vColor;\n\n#endif"; +ShaderChunk["color_pars_fragment"] = "#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif\n"; +ShaderChunk["color_pars_vertex"] = "#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif"; +ShaderChunk["color_vertex"] = "#ifdef USE_COLOR\n\n\tvColor.xyz = color.xyz;\n\n#endif"; +ShaderChunk["common"] = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\n\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\n// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range.\n// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\n\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\n\n\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n}\n\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n\n}\n\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\n\treturn - distance * planeNormal + point;\n\n}\n\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n\n}\n\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n\n}\n"; +ShaderChunk["cube_uv_reflection_fragment"] = "#ifdef ENVMAP_TYPE_CUBE_UV\n\n#define cubeUV_textureSize (1024.0)\n\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\n\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\t// Clamp the value to the max mip level counts. hard coded to 6 mips\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\n\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\t// float powScale = exp2(roughnessLevel + mipLevel);\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\t// float scale = 1.0 / exp2(roughnessLevel + 2.0 + mipLevel);\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\t// float mipOffset = 0.75*(1.0 - 1.0/exp2(mipLevel))/exp2(roughnessLevel);\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\n\tfloat rcpPowScale = 1.0 / powScale;\n\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\n\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\n\t// round to nearest mipmap if we are not interpolating.\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\n\t// Tri linear interpolation.\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\n\tvec4 result = mix(color10, color20, t);\n\n\treturn vec4(result.rgb, 1.0);\n}\n\n#endif\n"; +ShaderChunk["defaultnormal_vertex"] = "#ifdef FLIP_SIDED\n\n\tobjectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; +ShaderChunk["displacementmap_pars_vertex"] = "#ifdef USE_DISPLACEMENTMAP\n\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n\n#endif\n"; +ShaderChunk["displacementmap_vertex"] = "#ifdef USE_DISPLACEMENTMAP\n\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n\n#endif\n"; +ShaderChunk["emissivemap_fragment"] = "#ifdef USE_EMISSIVEMAP\n\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n\n#endif\n"; +ShaderChunk["emissivemap_pars_fragment"] = "#ifdef USE_EMISSIVEMAP\n\n\tuniform sampler2D emissiveMap;\n\n#endif\n"; +ShaderChunk["encodings_fragment"] = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; +ShaderChunk["encodings_pars_fragment"] = "// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/\n\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\n\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\n\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\n\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\n\n// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html\n\n// M matrix, for encoding\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\n\n// Inverse M matrix, for decoding\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n"; +ShaderChunk["envmap_fragment"] = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n\t\t// Transforming Normal Vectors with the Inverse Transformation\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#else\n\n\t\tvec3 reflectVec = vReflect;\n\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\n\t#endif\n\n\tenvColor = envMapTexelToLinear( envColor );\n\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n\t#endif\n\n#endif\n"; +ShaderChunk["envmap_pars_fragment"] = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n\n#ifdef USE_ENVMAP\n\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n\n#endif\n"; +ShaderChunk["envmap_pars_vertex"] = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\n\t#else\n\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\n\t#endif\n\n#endif\n"; +ShaderChunk["envmap_vertex"] = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\tvWorldPosition = worldPosition.xyz;\n\n\t#else\n\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#endif\n\n#endif\n"; +ShaderChunk["fog_fragment"] = "#ifdef USE_FOG\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n\t#else\n\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\n\t#endif\n\n\t#ifdef FOG_EXP2\n\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\n\t#else\n\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\n\t#endif\n\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\n#endif\n"; +ShaderChunk["fog_pars_fragment"] = "#ifdef USE_FOG\n\n\tuniform vec3 fogColor;\n\n\t#ifdef FOG_EXP2\n\n\t\tuniform float fogDensity;\n\n\t#else\n\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n\n#endif"; +ShaderChunk["lightmap_fragment"] = "#ifdef USE_LIGHTMAP\n\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\n\n#endif\n"; +ShaderChunk["lightmap_pars_fragment"] = "#ifdef USE_LIGHTMAP\n\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n\n#endif"; +ShaderChunk["lights_lambert_vertex"] = "vec3 diffuse = vec3( 1.0 );\n\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\n\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\n\nvLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\n\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n\n#if NUM_POINT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\n#endif\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\t}\n\n#endif\n\n#if NUM_DIR_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\n#endif\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\n\t\t#endif\n\n\t}\n\n#endif\n"; +ShaderChunk["lights_pars"] = "uniform vec3 ambientLightColor;\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n\n#if NUM_DIR_LIGHTS > 0\n\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\n\t}\n\n#endif\n\n\n#if NUM_POINT_LIGHTS > 0\n\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\n\t}\n\n#endif\n\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\n\t}\n\n#endif\n\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tirradiance *= PI;\n\n\t\t#endif\n\n\t\treturn irradiance;\n\n\t}\n\n#endif\n\n\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\n\tvec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) {\n\n\t\t#include \n\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\n\t\t\t// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\n\t\t\t// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#else\n\n\t\t\t\t// force the bias high to get the last LOD level as it is the most blurred.\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\n\t\t#else\n\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\n\t\t#endif\n\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\n\t}\n\n\t// taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\n\t\t//float envMapWidth = pow( 2.0, maxMIPLevelScalar );\n\t\t//float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\n\t\t// clamp to allowable LOD ranges.\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\n\t}\n\n\tvec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\n\t\t#endif\n\n\t\t#include \n\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\n\t\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#endif\n\n\t\treturn envMapColor.rgb * envMapIntensity;\n\n\t}\n\n#endif\n"; +ShaderChunk["lights_phong_fragment"] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; +ShaderChunk["lights_phong_pars_fragment"] = "varying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n\nstruct BlinnPhongMaterial {\n\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n\n};\n\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n\n}\n\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n\n#define Material_LightProbeLOD( material )\t(0)\n"; +ShaderChunk["lights_physical_fragment"] = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat ); // Burley clearcoat model\n\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; +ShaderChunk["lights_physical_pars_fragment"] = "struct PhysicalMaterial {\n\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n\n};\n\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\n\n// Clear coat directional hemishperical reflectance (this approximation should be improved)\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n\n}\n\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n\t#ifndef STANDARD\n\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\n\t#endif\n\n}\n\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\n\t#ifndef STANDARD\n\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\n\t#endif\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\n\n// ref: http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n\n}\n"; +ShaderChunk["lights_template"] = "//\n// This is a template that can be used to light a material, it uses pluggable RenderEquations (RE)\n// for specific lighting scenarios.\n//\n// Instructions for use:\n// - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined\n// - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ???\n// - Create a material parameter that is to be passed as the third parameter to your lighting functions.\n//\n// TODO:\n// - Add area light support.\n// - Add sphere light support.\n// - Add diffuse light probe (irradiance cubemap) support.\n//\n\nGeometricContext geometry;\n\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n\nIncidentLight directLight;\n\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tPointLight pointLight;\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tSpotLight spotLight;\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tDirectionalLight directionalLight;\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if defined( RE_IndirectDiffuse )\n\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n\t#ifdef USE_LIGHTMAP\n\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tlightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage\n\n\t\t#endif\n\n\t\tirradiance += lightMapIrradiance;\n\n\t#endif\n\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t}\n\n\t#endif\n\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t// TODO, replace 8 with the real maxMIPLevel\n\t \tirradiance += getLightProbeIndirectIrradiance( /*lightProbe,*/ geometry, 8 );\n\n\t#endif\n\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n\n#endif\n\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\n\t// TODO, replace 8 with the real maxMIPLevel\n\tvec3 radiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_BlinnShininessExponent( material ), 8 );\n\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n\n#endif\n"; +ShaderChunk["logdepthbuf_fragment"] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif"; +ShaderChunk["logdepthbuf_pars_fragment"] = "#ifdef USE_LOGDEPTHBUF\n\n\tuniform float logDepthBufFC;\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\n\t#endif\n\n#endif\n"; +ShaderChunk["logdepthbuf_pars_vertex"] = "#ifdef USE_LOGDEPTHBUF\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\n\t#endif\n\n\tuniform float logDepthBufFC;\n\n#endif"; +ShaderChunk["logdepthbuf_vertex"] = "#ifdef USE_LOGDEPTHBUF\n\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\n\t#else\n\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n\t#endif\n\n#endif\n"; +ShaderChunk["map_fragment"] = "#ifdef USE_MAP\n\n\tvec4 texelColor = texture2D( map, vUv );\n\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n\n#endif\n"; +ShaderChunk["map_pars_fragment"] = "#ifdef USE_MAP\n\n\tuniform sampler2D map;\n\n#endif\n"; +ShaderChunk["map_particle_fragment"] = "#ifdef USE_MAP\n\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n\n#endif\n"; +ShaderChunk["map_particle_pars_fragment"] = "#ifdef USE_MAP\n\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n\n#endif\n"; +ShaderChunk["metalnessmap_fragment"] = "float metalnessFactor = metalness;\n\n#ifdef USE_METALNESSMAP\n\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n\n#endif\n"; +ShaderChunk["metalnessmap_pars_fragment"] = "#ifdef USE_METALNESSMAP\n\n\tuniform sampler2D metalnessMap;\n\n#endif"; +ShaderChunk["morphnormal_vertex"] = "#ifdef USE_MORPHNORMALS\n\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n#endif\n"; +ShaderChunk["morphtarget_pars_vertex"] = "#ifdef USE_MORPHTARGETS\n\n\t#ifndef USE_MORPHNORMALS\n\n\tuniform float morphTargetInfluences[ 8 ];\n\n\t#else\n\n\tuniform float morphTargetInfluences[ 4 ];\n\n\t#endif\n\n#endif"; +ShaderChunk["morphtarget_vertex"] = "#ifdef USE_MORPHTARGETS\n\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n\t#ifndef USE_MORPHNORMALS\n\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n\t#endif\n\n#endif\n"; +ShaderChunk["normal_flip"] = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n"; +ShaderChunk["normal_fragment"] = "#ifdef FLAT_SHADED\n\n\t// Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ...\n\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n\n#else\n\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n\n#endif\n\n#ifdef USE_NORMALMAP\n\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n"; +ShaderChunk["normalmap_pars_fragment"] = "#ifdef USE_NORMALMAP\n\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\n\t// Per-Pixel Tangent Space Normal Mapping\n\t// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\n\t}\n\n#endif\n"; +ShaderChunk["packing"] = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\n\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\n\nconst float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1)\nconst float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1)\n\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\n\nconst float ShiftRight8 = 1. / 256.;\n\nvec4 packDepthToRGBA( const in float v ) {\n\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\n\treturn r * PackUpscale;\n\n}\n\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\n\treturn dot( v, UnpackFactors );\n\n}\n\n// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions\n\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\n\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; +ShaderChunk["premultiplied_alpha_fragment"] = "#ifdef PREMULTIPLIED_ALPHA\n\n\t// Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation.\n\tgl_FragColor.rgb *= gl_FragColor.a;\n\n#endif\n"; +ShaderChunk["project_vertex"] = "#ifdef USE_SKINNING\n\n\tvec4 mvPosition = modelViewMatrix * skinned;\n\n#else\n\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n"; +ShaderChunk["roughnessmap_fragment"] = "float roughnessFactor = roughness;\n\n#ifdef USE_ROUGHNESSMAP\n\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n\n#endif\n"; +ShaderChunk["roughnessmap_pars_fragment"] = "#ifdef USE_ROUGHNESSMAP\n\n\tuniform sampler2D roughnessMap;\n\n#endif"; +ShaderChunk["shadowmap_pars_fragment"] = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\n\t#endif\n\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\n\t}\n\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\n\t\tvec2 f = fract( uv * size + 0.5 );\n\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\n\t\treturn c;\n\n\t}\n\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\n\t\t// if ( something && something ) breaks ATI OpenGL shader compiler\n\t\t// if ( all( something, something ) ) using this instead\n\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n\t\tbool frustumTest = all( frustumTestVec );\n\n\t\tif ( frustumTest ) {\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering:\n\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\n\t\t#endif\n\n\t\t}\n\n\t\treturn 1.0;\n\n\t}\n\n\t// cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D\n\t// vector suitable for 2D texture mapping. This code uses the following layout for the\n\t// 2D texture:\n\t//\n\t// xzXZ\n\t// y Y\n\t//\n\t// Y - Positive y direction\n\t// y - Negative y direction\n\t// X - Positive x direction\n\t// x - Negative x direction\n\t// Z - Positive z direction\n\t// z - Negative z direction\n\t//\n\t// Source and test bed:\n\t// https://gist.github.com/tschw/da10c43c467ce8afd0c4\n\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\n\t\t// Number of texels to avoid at the edge of each square\n\n\t\tvec3 absV = abs( v );\n\n\t\t// Intersect unit cube\n\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\n\t\t// Apply scale to avoid seams\n\n\t\t// two texels less per square (one texel will do for NEAREST)\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\n\t\t// Unwrap\n\n\t\t// space: -1 ... 1 range for each square\n\t\t//\n\t\t// #X##\t\tdim := ( 4 , 2 )\n\t\t// # #\t\tcenter := ( 1 , 1 )\n\n\t\tvec2 planar = v.xy;\n\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\n\t\tif ( absV.z >= almostOne ) {\n\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\n\t\t} else if ( absV.x >= almostOne ) {\n\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\n\t\t} else if ( absV.y >= almostOne ) {\n\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\n\t\t}\n\n\t\t// Transform to UV space\n\n\t\t// scale := 0.5 / dim\n\t\t// translate := ( center + 0.5 ) / dim\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\n\t}\n\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\n\t\t// for point lights, the uniform @vShadowCoord is re-purposed to hold\n\t\t// the distance from the light to the world-space position of the fragment.\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\n\t\t// bd3D = base direction 3D\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t// dp = distance from light to fragment position\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering\n\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\n\t\t#endif\n\n\t}\n\n#endif\n"; +ShaderChunk["shadowmap_pars_vertex"] = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\n\t#endif\n\n#endif\n"; +ShaderChunk["shadowmap_vertex"] = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n#endif\n"; +ShaderChunk["shadowmask_pars_fragment"] = "float getShadowMask() {\n\n\tfloat shadow = 1.0;\n\n\t#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\tDirectionalLight directionalLight;\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\tSpotLight spotLight;\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\tPointLight pointLight;\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#endif\n\n\treturn shadow;\n\n}\n"; +ShaderChunk["skinbase_vertex"] = "#ifdef USE_SKINNING\n\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif"; +ShaderChunk["skinning_pars_vertex"] = "#ifdef USE_SKINNING\n\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\n\t#ifdef BONE_TEXTURE\n\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\n\t\t\ty = dy * ( y + 0.5 );\n\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\n\t\t\treturn bone;\n\n\t\t}\n\n\t#else\n\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\n\t\t}\n\n\t#endif\n\n#endif\n"; +ShaderChunk["skinning_vertex"] = "#ifdef USE_SKINNING\n\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n\n#endif\n"; +ShaderChunk["skinnormal_vertex"] = "#ifdef USE_SKINNING\n\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\n#endif\n"; +ShaderChunk["specularmap_fragment"] = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n\n#else\n\n\tspecularStrength = 1.0;\n\n#endif"; +ShaderChunk["specularmap_pars_fragment"] = "#ifdef USE_SPECULARMAP\n\n\tuniform sampler2D specularMap;\n\n#endif"; +ShaderChunk["tonemapping_fragment"] = "#if defined( TONE_MAPPING )\n\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n\n#endif\n"; +ShaderChunk["tonemapping_pars_fragment"] = "#define saturate(a) clamp( a, 0.0, 1.0 )\n\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\n\n// exposure only\nvec3 LinearToneMapping( vec3 color ) {\n\n return toneMappingExposure * color;\n\n}\n\n// source: https://www.cs.utah.edu/~reinhard/cdrom/\nvec3 ReinhardToneMapping( vec3 color ) {\n\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n\n}\n\n// source: http://filmicgames.com/archives/75\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\n // John Hable's filmic operator from Uncharted 2 video game\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n\n}\n\n// source: http://filmicgames.com/archives/75\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n\n}\n"; +ShaderChunk["uv2_pars_fragment"] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvarying vec2 vUv2;\n\n#endif"; +ShaderChunk["uv2_pars_vertex"] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\n#endif"; +ShaderChunk["uv2_vertex"] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvUv2 = uv2;\n\n#endif"; +ShaderChunk["uv_pars_fragment"] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvarying vec2 vUv;\n\n#endif"; +ShaderChunk["uv_pars_vertex"] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n\n#endif\n"; +ShaderChunk["uv_vertex"] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif"; +ShaderChunk["worldpos_vertex"] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n\t#ifdef USE_SKINNING\n\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\n\t#else\n\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\n\t#endif\n\n#endif\n"; +ShaderChunk["cube_frag"] = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\n\nvarying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n\n}\n"; +ShaderChunk["cube_vert"] = "varying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\n\t#include \n\t#include \n\n}\n"; +ShaderChunk["depth_frag"] = "#if DEPTH_PACKING == 3200\n\n\tuniform float opacity;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( 1.0 );\n\n\t#if DEPTH_PACKING == 3200\n\n\t\tdiffuseColor.a = opacity;\n\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\n\t#if DEPTH_PACKING == 3200\n\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\n\t#elif DEPTH_PACKING == 3201\n\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\n\t#endif\n\n}\n"; +ShaderChunk["depth_vert"] = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["distanceRGBA_frag"] = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n\n#include \n#include \n#include \n\nvoid main () {\n\n\t#include \n\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n\n}\n"; +ShaderChunk["distanceRGBA_vert"] = "varying vec4 vWorldPosition;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvWorldPosition = worldPosition;\n\n}\n"; +ShaderChunk["equirect_frag"] = "uniform sampler2D tEquirect;\nuniform float tFlip;\n\nvarying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\t// \tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n}\n"; +ShaderChunk["equirect_vert"] = "varying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\n\t#include \n\t#include \n\n}\n"; +ShaderChunk["linedashed_frag"] = "uniform vec3 diffuse;\nuniform float opacity;\n\nuniform float dashSize;\nuniform float totalSize;\n\nvarying float vLineDistance;\n\n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\n\t\tdiscard;\n\n\t}\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\n\toutgoingLight = diffuseColor.rgb; // simple shader\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["linedashed_vert"] = "uniform float scale;\nattribute float lineDistance;\n\nvarying float vLineDistance;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvLineDistance = scale * lineDistance;\n\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\n\t#include \n\t#include \n\n}\n"; +ShaderChunk["meshbasic_frag"] = "uniform vec3 diffuse;\nuniform float opacity;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n\t#include \n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["meshbasic_vert"] = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#ifdef USE_ENVMAP\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["meshlambert_frag"] = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n\nvarying vec3 vLightFront;\n\n#ifdef DOUBLE_SIDED\n\n\tvarying vec3 vLightBack;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\n\t#include \n\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\n\t#ifdef DOUBLE_SIDED\n\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\n\t#else\n\n\t\treflectedLight.directDiffuse = vLightFront;\n\n\t#endif\n\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\t#include \n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["meshlambert_vert"] = "#define LAMBERT\n\nvarying vec3 vLightFront;\n\n#ifdef DOUBLE_SIDED\n\n\tvarying vec3 vLightBack;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["meshphong_frag"] = "#define PHONG\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["meshphong_vert"] = "#define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["meshphysical_frag"] = "#define PHYSICAL\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\n\nuniform float envMapIntensity; // temporary\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["meshphysical_vert"] = "#define PHYSICAL\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\n}\n"; +ShaderChunk["normal_frag"] = "uniform float opacity;\nvarying vec3 vNormal;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\n\t#include \n\n}\n"; +ShaderChunk["normal_vert"] = "varying vec3 vNormal;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\tvNormal = normalize( normalMatrix * normal );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["points_frag"] = "uniform vec3 diffuse;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\toutgoingLight = diffuseColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["points_vert"] = "uniform float size;\nuniform float scale;\n\n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; +ShaderChunk["shadow_frag"] = "uniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n\n}\n"; +ShaderChunk["shadow_vert"] = "#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + +export { ShaderChunk }; \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl b/src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl deleted file mode 100644 index 1aa712eb3aaa9c..00000000000000 --- a/src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_ALPHAMAP - - diffuseColor.a *= texture2D( alphaMap, vUv ).g; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl deleted file mode 100644 index 4a84b4997f9749..00000000000000 --- a/src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_ALPHAMAP - - uniform sampler2D alphaMap; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl b/src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl deleted file mode 100644 index 448b2bf55661f7..00000000000000 --- a/src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef ALPHATEST - - if ( diffuseColor.a < ALPHATEST ) discard; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/ambient_pars.glsl b/src/renderers/shaders/ShaderChunk/ambient_pars.glsl deleted file mode 100644 index fb77dde559a06d..00000000000000 --- a/src/renderers/shaders/ShaderChunk/ambient_pars.glsl +++ /dev/null @@ -1,15 +0,0 @@ -uniform vec3 ambientLightColor; - -vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { - - vec3 irradiance = ambientLightColor; - - #ifndef PHYSICALLY_CORRECT_LIGHTS - - irradiance *= PI; - - #endif - - return irradiance; - -} diff --git a/src/renderers/shaders/ShaderChunk/aomap_fragment.glsl b/src/renderers/shaders/ShaderChunk/aomap_fragment.glsl deleted file mode 100644 index 0b4488bd6db860..00000000000000 --- a/src/renderers/shaders/ShaderChunk/aomap_fragment.glsl +++ /dev/null @@ -1,15 +0,0 @@ -#ifdef USE_AOMAP - - float ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0; - - reflectedLight.indirectDiffuse *= ambientOcclusion; - - #if defined( USE_ENVMAP ) && defined( PHYSICAL ) - - float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) ); - - reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness ); - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl deleted file mode 100644 index 73277ab4b1eba9..00000000000000 --- a/src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl +++ /dev/null @@ -1,6 +0,0 @@ -#ifdef USE_AOMAP - - uniform sampler2D aoMap; - uniform float aoMapIntensity; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/begin_vertex.glsl b/src/renderers/shaders/ShaderChunk/begin_vertex.glsl deleted file mode 100644 index 9f681c6600faa8..00000000000000 --- a/src/renderers/shaders/ShaderChunk/begin_vertex.glsl +++ /dev/null @@ -1,2 +0,0 @@ - -vec3 transformed = vec3( position ); diff --git a/src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl b/src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl deleted file mode 100644 index f24d6d48030552..00000000000000 --- a/src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl +++ /dev/null @@ -1,2 +0,0 @@ - -vec3 objectNormal = vec3( normal ); diff --git a/src/renderers/shaders/ShaderChunk/bsdfs.glsl b/src/renderers/shaders/ShaderChunk/bsdfs.glsl deleted file mode 100644 index 48b11a900eb85a..00000000000000 --- a/src/renderers/shaders/ShaderChunk/bsdfs.glsl +++ /dev/null @@ -1,179 +0,0 @@ -bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) { - - return any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) ); - -} - -float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { - - if( decayExponent > 0.0 ) { - -#if defined ( PHYSICALLY_CORRECT_LIGHTS ) - - // based upon Frostbite 3 Moving to Physically-based Rendering - // page 32, equation 26: E[window1] - // http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf - // this is intended to be used on spot and point lights who are represented as luminous intensity - // but who must be converted to luminous irradiance for surface lighting calculation - float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); - float maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); - return distanceFalloff * maxDistanceCutoffFactor; - -#else - - return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent ); - -#endif - - } - - return 1.0; -} - -vec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) { - - return RECIPROCAL_PI * diffuseColor; - -} // validated - - -vec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) { - - // Original approximation by Christophe Schlick '94 - //;float fresnel = pow( 1.0 - dotLH, 5.0 ); - - // Optimized variant (presented by Epic at SIGGRAPH '13) - float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH ); - - return ( 1.0 - specularColor ) * fresnel + specularColor; - -} // validated - - -// Microfacet Models for Refraction through Rough Surfaces - equation (34) -// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html -// alpha is "roughness squared" in Disney’s reparameterization -float G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) { - - // geometry term = G(l)⋅G(v) / 4(n⋅l)(n⋅v) - - float a2 = pow2( alpha ); - - float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); - float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); - - return 1.0 / ( gl * gv ); - -} // validated - -// from page 12, listing 2 of http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf -float G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { - - float a2 = pow2( alpha ); - - // dotNL and dotNV are explicitly swapped. This is not a mistake. - float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); - float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); - - return 0.5 / max( gv + gl, EPSILON ); -} - - - -// Microfacet Models for Refraction through Rough Surfaces - equation (33) -// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html -// alpha is "roughness squared" in Disney’s reparameterization -float D_GGX( const in float alpha, const in float dotNH ) { - - float a2 = pow2( alpha ); - - float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1 - - return RECIPROCAL_PI * a2 / pow2( denom ); - -} - - -// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility -vec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) { - - float alpha = pow2( roughness ); // UE4's roughness - - vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir ); - - float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) ); - float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) ); - float dotNH = saturate( dot( geometry.normal, halfDir ) ); - float dotLH = saturate( dot( incidentLight.direction, halfDir ) ); - - vec3 F = F_Schlick( specularColor, dotLH ); - - float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - - float D = D_GGX( alpha, dotNH ); - - return F * ( G * D ); - -} // validated - - -// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile -vec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) { - - float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) ); - - const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); - - const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); - - vec4 r = roughness * c0 + c1; - - float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; - - vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw; - - return specularColor * AB.x + AB.y; - -} // validated - - -float G_BlinnPhong_Implicit( /* const in float dotNL, const in float dotNV */ ) { - - // geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v) - return 0.25; - -} - -float D_BlinnPhong( const in float shininess, const in float dotNH ) { - - return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); - -} - -vec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) { - - vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir ); - - //float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) ); - //float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) ); - float dotNH = saturate( dot( geometry.normal, halfDir ) ); - float dotLH = saturate( dot( incidentLight.direction, halfDir ) ); - - vec3 F = F_Schlick( specularColor, dotLH ); - - float G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ ); - - float D = D_BlinnPhong( shininess, dotNH ); - - return F * ( G * D ); - -} // validated - -// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html -float GGXRoughnessToBlinnExponent( const in float ggxRoughness ) { - return ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 ); -} - -float BlinnExponentToGGXRoughness( const in float blinnExponent ) { - return sqrt( 2.0 / ( blinnExponent + 2.0 ) ); -} diff --git a/src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl deleted file mode 100644 index c901f0b0135cc5..00000000000000 --- a/src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl +++ /dev/null @@ -1,40 +0,0 @@ -#ifdef USE_BUMPMAP - - uniform sampler2D bumpMap; - uniform float bumpScale; - - // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen - // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html - - // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2) - - vec2 dHdxy_fwd() { - - vec2 dSTdx = dFdx( vUv ); - vec2 dSTdy = dFdy( vUv ); - - float Hll = bumpScale * texture2D( bumpMap, vUv ).x; - float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll; - float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll; - - return vec2( dBx, dBy ); - - } - - vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) { - - vec3 vSigmaX = dFdx( surf_pos ); - vec3 vSigmaY = dFdy( surf_pos ); - vec3 vN = surf_norm; // normalized - - vec3 R1 = cross( vSigmaY, vN ); - vec3 R2 = cross( vN, vSigmaX ); - - float fDet = dot( vSigmaX, R1 ); - - vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); - return normalize( abs( fDet ) * surf_norm - vGrad ); - - } - -#endif diff --git a/src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl b/src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl deleted file mode 100644 index cc3008fcbfd6d0..00000000000000 --- a/src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl +++ /dev/null @@ -1,10 +0,0 @@ -#if NUM_CLIPPING_PLANES > 0 - - for ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) { - - vec4 plane = clippingPlanes[ i ]; - if ( dot( vViewPosition, plane.xyz ) > plane.w ) discard; - - } - -#endif diff --git a/src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl deleted file mode 100644 index 3eb44cdadebebb..00000000000000 --- a/src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl +++ /dev/null @@ -1,9 +0,0 @@ -#if NUM_CLIPPING_PLANES > 0 - - #if ! defined( PHYSICAL ) && ! defined( PHONG ) - varying vec3 vViewPosition; - #endif - - uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl deleted file mode 100644 index d83f96d56c1994..00000000000000 --- a/src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl +++ /dev/null @@ -1,3 +0,0 @@ -#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG ) - varying vec3 vViewPosition; -#endif diff --git a/src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl b/src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl deleted file mode 100644 index d3fa83858ea6c4..00000000000000 --- a/src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl +++ /dev/null @@ -1,4 +0,0 @@ -#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG ) - vViewPosition = - mvPosition.xyz; -#endif - diff --git a/src/renderers/shaders/ShaderChunk/color_fragment.glsl b/src/renderers/shaders/ShaderChunk/color_fragment.glsl deleted file mode 100644 index 693fdf061c226f..00000000000000 --- a/src/renderers/shaders/ShaderChunk/color_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_COLOR - - diffuseColor.rgb *= vColor; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl deleted file mode 100644 index 4f59898b6ef7fd..00000000000000 --- a/src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_COLOR - - varying vec3 vColor; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl deleted file mode 100644 index f3862c30b66d43..00000000000000 --- a/src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_COLOR - - varying vec3 vColor; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/color_vertex.glsl b/src/renderers/shaders/ShaderChunk/color_vertex.glsl deleted file mode 100644 index 7bd534d9cf170f..00000000000000 --- a/src/renderers/shaders/ShaderChunk/color_vertex.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_COLOR - - vColor.xyz = color.xyz; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/common.glsl b/src/renderers/shaders/ShaderChunk/common.glsl deleted file mode 100644 index d62dafd587b63c..00000000000000 --- a/src/renderers/shaders/ShaderChunk/common.glsl +++ /dev/null @@ -1,74 +0,0 @@ -#define PI 3.14159265359 -#define PI2 6.28318530718 -#define RECIPROCAL_PI 0.31830988618 -#define RECIPROCAL_PI2 0.15915494 -#define LOG2 1.442695 -#define EPSILON 1e-6 - -#define saturate(a) clamp( a, 0.0, 1.0 ) -#define whiteCompliment(a) ( 1.0 - saturate( a ) ) - -float pow2( const in float x ) { return x*x; } -float pow3( const in float x ) { return x*x*x; } -float pow4( const in float x ) { float x2 = x*x; return x2*x2; } -float average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); } -// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range. -// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/ -highp float rand( const in vec2 uv ) { - const highp float a = 12.9898, b = 78.233, c = 43758.5453; - highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); - return fract(sin(sn) * c); -} - -struct IncidentLight { - vec3 color; - vec3 direction; - bool visible; -}; - -struct ReflectedLight { - vec3 directDiffuse; - vec3 directSpecular; - vec3 indirectDiffuse; - vec3 indirectSpecular; -}; - -struct GeometricContext { - vec3 position; - vec3 normal; - vec3 viewDir; -}; - - -vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); - -} - -// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations -vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { - - return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); - -} - -vec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) { - - float distance = dot( planeNormal, point - pointOnPlane ); - - return - distance * planeNormal + point; - -} - -float sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) { - - return sign( dot( point - pointOnPlane, planeNormal ) ); - -} - -vec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) { - - return lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine; - -} diff --git a/src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl b/src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl deleted file mode 100644 index d23ab4596e13f4..00000000000000 --- a/src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl +++ /dev/null @@ -1,128 +0,0 @@ -#ifdef ENVMAP_TYPE_CUBE_UV - -#define cubeUV_textureSize (1024.0) - -int getFaceFromDirection(vec3 direction) { - vec3 absDirection = abs(direction); - int face = -1; - if( absDirection.x > absDirection.z ) { - if(absDirection.x > absDirection.y ) - face = direction.x > 0.0 ? 0 : 3; - else - face = direction.y > 0.0 ? 1 : 4; - } - else { - if(absDirection.z > absDirection.y ) - face = direction.z > 0.0 ? 2 : 5; - else - face = direction.y > 0.0 ? 1 : 4; - } - return face; -} -#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0) -#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0)) - -vec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) { - float scale = exp2(cubeUV_maxLods1 - roughnessLevel); - float dxRoughness = dFdx(roughness); - float dyRoughness = dFdy(roughness); - vec3 dx = dFdx( vec * scale * dxRoughness ); - vec3 dy = dFdy( vec * scale * dyRoughness ); - float d = max( dot( dx, dx ), dot( dy, dy ) ); - // Clamp the value to the max mip level counts. hard coded to 6 mips - d = clamp(d, 1.0, cubeUV_rangeClamp); - float mipLevel = 0.5 * log2(d); - return vec2(floor(mipLevel), fract(mipLevel)); -} - -#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0) -#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize) - -vec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) { - mipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel; - float a = 16.0 * cubeUV_rcpTextureSize; - - vec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) ); - vec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed; - // float powScale = exp2(roughnessLevel + mipLevel); - float powScale = exp2_packed.x * exp2_packed.y; - // float scale = 1.0 / exp2(roughnessLevel + 2.0 + mipLevel); - float scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25; - // float mipOffset = 0.75*(1.0 - 1.0/exp2(mipLevel))/exp2(roughnessLevel); - float mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x; - - bool bRes = mipLevel == 0.0; - scale = bRes && (scale < a) ? a : scale; - - vec3 r; - vec2 offset; - int face = getFaceFromDirection(direction); - - float rcpPowScale = 1.0 / powScale; - - if( face == 0) { - r = vec3(direction.x, -direction.z, direction.y); - offset = vec2(0.0+mipOffset,0.75 * rcpPowScale); - offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y; - } - else if( face == 1) { - r = vec3(direction.y, direction.x, direction.z); - offset = vec2(scale+mipOffset, 0.75 * rcpPowScale); - offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y; - } - else if( face == 2) { - r = vec3(direction.z, direction.x, direction.y); - offset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale); - offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y; - } - else if( face == 3) { - r = vec3(direction.x, direction.z, direction.y); - offset = vec2(0.0+mipOffset,0.5 * rcpPowScale); - offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y; - } - else if( face == 4) { - r = vec3(direction.y, direction.x, -direction.z); - offset = vec2(scale+mipOffset, 0.5 * rcpPowScale); - offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y; - } - else { - r = vec3(direction.z, -direction.x, direction.y); - offset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale); - offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y; - } - r = normalize(r); - float texelOffset = 0.5 * cubeUV_rcpTextureSize; - vec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5; - vec2 base = offset + vec2( texelOffset ); - return base + s * ( scale - 2.0 * texelOffset ); -} - -#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0) - -vec4 textureCubeUV(vec3 reflectedDirection, float roughness ) { - float roughnessVal = roughness* cubeUV_maxLods3; - float r1 = floor(roughnessVal); - float r2 = r1 + 1.0; - float t = fract(roughnessVal); - vec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness); - float s = mipInfo.y; - float level0 = mipInfo.x; - float level1 = level0 + 1.0; - level1 = level1 > 5.0 ? 5.0 : level1; - - // round to nearest mipmap if we are not interpolating. - level0 += min( floor( s + 0.5 ), 5.0 ); - - // Tri linear interpolation. - vec2 uv_10 = getCubeUV(reflectedDirection, r1, level0); - vec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10)); - - vec2 uv_20 = getCubeUV(reflectedDirection, r2, level0); - vec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20)); - - vec4 result = mix(color10, color20, t); - - return vec4(result.rgb, 1.0); -} - -#endif diff --git a/src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl b/src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl deleted file mode 100644 index d9fb04ee0a892a..00000000000000 --- a/src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl +++ /dev/null @@ -1,7 +0,0 @@ -#ifdef FLIP_SIDED - - objectNormal = -objectNormal; - -#endif - -vec3 transformedNormal = normalMatrix * objectNormal; diff --git a/src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl deleted file mode 100644 index 5e771596b11f94..00000000000000 --- a/src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl +++ /dev/null @@ -1,7 +0,0 @@ -#ifdef USE_DISPLACEMENTMAP - - uniform sampler2D displacementMap; - uniform float displacementScale; - uniform float displacementBias; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl b/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl deleted file mode 100644 index b03c142c68721b..00000000000000 --- a/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_DISPLACEMENTMAP - - transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias ); - -#endif diff --git a/src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl b/src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl deleted file mode 100644 index 1d65996de11701..00000000000000 --- a/src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl +++ /dev/null @@ -1,9 +0,0 @@ -#ifdef USE_EMISSIVEMAP - - vec4 emissiveColor = texture2D( emissiveMap, vUv ); - - emissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb; - - totalEmissiveRadiance *= emissiveColor.rgb; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl deleted file mode 100644 index c05bb7f55180a0..00000000000000 --- a/src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_EMISSIVEMAP - - uniform sampler2D emissiveMap; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/encodings_fragment.glsl b/src/renderers/shaders/ShaderChunk/encodings_fragment.glsl deleted file mode 100644 index 189d735b547723..00000000000000 --- a/src/renderers/shaders/ShaderChunk/encodings_fragment.glsl +++ /dev/null @@ -1 +0,0 @@ - gl_FragColor = linearToOutputTexel( gl_FragColor ); diff --git a/src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl deleted file mode 100644 index 925590e88e11cb..00000000000000 --- a/src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl +++ /dev/null @@ -1,78 +0,0 @@ -// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/ - -vec4 LinearToLinear( in vec4 value ) { - return value; -} - -vec4 GammaToLinear( in vec4 value, in float gammaFactor ) { - return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w ); -} -vec4 LinearToGamma( in vec4 value, in float gammaFactor ) { - return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w ); -} - -vec4 sRGBToLinear( in vec4 value ) { - return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w ); -} -vec4 LinearTosRGB( in vec4 value ) { - return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w ); -} - -vec4 RGBEToLinear( in vec4 value ) { - return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 ); -} -vec4 LinearToRGBE( in vec4 value ) { - float maxComponent = max( max( value.r, value.g ), value.b ); - float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 ); - return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 ); -// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 ); -} - -// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html -vec4 RGBMToLinear( in vec4 value, in float maxRange ) { - return vec4( value.xyz * value.w * maxRange, 1.0 ); -} -vec4 LinearToRGBM( in vec4 value, in float maxRange ) { - float maxRGB = max( value.x, max( value.g, value.b ) ); - float M = clamp( maxRGB / maxRange, 0.0, 1.0 ); - M = ceil( M * 255.0 ) / 255.0; - return vec4( value.rgb / ( M * maxRange ), M ); -} - -// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html -vec4 RGBDToLinear( in vec4 value, in float maxRange ) { - return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 ); -} -vec4 LinearToRGBD( in vec4 value, in float maxRange ) { - float maxRGB = max( value.x, max( value.g, value.b ) ); - float D = max( maxRange / maxRGB, 1.0 ); - D = min( floor( D ) / 255.0, 1.0 ); - return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D ); -} - -// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html - -// M matrix, for encoding -const mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 ); -vec4 LinearToLogLuv( in vec4 value ) { - vec3 Xp_Y_XYZp = value.rgb * cLogLuvM; - Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6)); - vec4 vResult; - vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z; - float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0; - vResult.w = fract(Le); - vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0; - return vResult; -} - -// Inverse M matrix, for decoding -const mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 ); -vec4 LogLuvToLinear( in vec4 value ) { - float Le = value.z * 255.0 + value.w; - vec3 Xp_Y_XYZp; - Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0); - Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y; - Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z; - vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM; - return vec4( max(vRGB, 0.0), 1.0 ); -} diff --git a/src/renderers/shaders/ShaderChunk/envmap_fragment.glsl b/src/renderers/shaders/ShaderChunk/envmap_fragment.glsl deleted file mode 100644 index ccb35fa6bdf724..00000000000000 --- a/src/renderers/shaders/ShaderChunk/envmap_fragment.glsl +++ /dev/null @@ -1,60 +0,0 @@ -#ifdef USE_ENVMAP - - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) - - vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition ); - - // Transforming Normal Vectors with the Inverse Transformation - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - - #ifdef ENVMAP_MODE_REFLECTION - - vec3 reflectVec = reflect( cameraToVertex, worldNormal ); - - #else - - vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio ); - - #endif - - #else - - vec3 reflectVec = vReflect; - - #endif - - #ifdef ENVMAP_TYPE_CUBE - - vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); - - #elif defined( ENVMAP_TYPE_EQUIREC ) - - vec2 sampleUV; - sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 ); - sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5; - vec4 envColor = texture2D( envMap, sampleUV ); - - #elif defined( ENVMAP_TYPE_SPHERE ) - - vec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) ); - vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 ); - - #endif - - envColor = envMapTexelToLinear( envColor ); - - #ifdef ENVMAP_BLENDING_MULTIPLY - - outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); - - #elif defined( ENVMAP_BLENDING_MIX ) - - outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); - - #elif defined( ENVMAP_BLENDING_ADD ) - - outgoingLight += envColor.xyz * specularStrength * reflectivity; - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl deleted file mode 100644 index 575800944abc0e..00000000000000 --- a/src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl +++ /dev/null @@ -1,25 +0,0 @@ -#if defined( USE_ENVMAP ) || defined( PHYSICAL ) - uniform float reflectivity; - uniform float envMapIntenstiy; -#endif - -#ifdef USE_ENVMAP - - #if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) ) - varying vec3 vWorldPosition; - #endif - - #ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; - #else - uniform sampler2D envMap; - #endif - uniform float flipEnvMap; - - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL ) - uniform float refractionRatio; - #else - varying vec3 vReflect; - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl deleted file mode 100644 index 7feab7532e506d..00000000000000 --- a/src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl +++ /dev/null @@ -1,13 +0,0 @@ -#ifdef USE_ENVMAP - - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) - varying vec3 vWorldPosition; - - #else - - varying vec3 vReflect; - uniform float refractionRatio; - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/envmap_vertex.glsl b/src/renderers/shaders/ShaderChunk/envmap_vertex.glsl deleted file mode 100644 index ce32d522895622..00000000000000 --- a/src/renderers/shaders/ShaderChunk/envmap_vertex.glsl +++ /dev/null @@ -1,25 +0,0 @@ -#ifdef USE_ENVMAP - - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) - - vWorldPosition = worldPosition.xyz; - - #else - - vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); - - vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - - #ifdef ENVMAP_MODE_REFLECTION - - vReflect = reflect( cameraToVertex, worldNormal ); - - #else - - vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); - - #endif - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/fog_fragment.glsl b/src/renderers/shaders/ShaderChunk/fog_fragment.glsl deleted file mode 100644 index 38309ad7a28f3e..00000000000000 --- a/src/renderers/shaders/ShaderChunk/fog_fragment.glsl +++ /dev/null @@ -1,25 +0,0 @@ -#ifdef USE_FOG - - #ifdef USE_LOGDEPTHBUF_EXT - - float depth = gl_FragDepthEXT / gl_FragCoord.w; - - #else - - float depth = gl_FragCoord.z / gl_FragCoord.w; - - #endif - - #ifdef FOG_EXP2 - - float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) ); - - #else - - float fogFactor = smoothstep( fogNear, fogFar, depth ); - - #endif - - gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); - -#endif diff --git a/src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl deleted file mode 100644 index ab7a15081ebcfc..00000000000000 --- a/src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl +++ /dev/null @@ -1,15 +0,0 @@ -#ifdef USE_FOG - - uniform vec3 fogColor; - - #ifdef FOG_EXP2 - - uniform float fogDensity; - - #else - - uniform float fogNear; - uniform float fogFar; - #endif - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl b/src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl deleted file mode 100644 index 1392a6097c96e5..00000000000000 --- a/src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_LIGHTMAP - - reflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage - -#endif diff --git a/src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl deleted file mode 100644 index a75c38f7edc244..00000000000000 --- a/src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl +++ /dev/null @@ -1,6 +0,0 @@ -#ifdef USE_LIGHTMAP - - uniform sampler2D lightMap; - uniform float lightMapIntensity; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl b/src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl deleted file mode 100644 index 87a787d3d4e4c2..00000000000000 --- a/src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl +++ /dev/null @@ -1,99 +0,0 @@ -vec3 diffuse = vec3( 1.0 ); - -GeometricContext geometry; -geometry.position = mvPosition.xyz; -geometry.normal = normalize( transformedNormal ); -geometry.viewDir = normalize( -mvPosition.xyz ); - -GeometricContext backGeometry; -backGeometry.position = geometry.position; -backGeometry.normal = -geometry.normal; -backGeometry.viewDir = geometry.viewDir; - -vLightFront = vec3( 0.0 ); - -#ifdef DOUBLE_SIDED - vLightBack = vec3( 0.0 ); -#endif - -IncidentLight directLight; -float dotNL; -vec3 directLightColor_Diffuse; - -#if NUM_POINT_LIGHTS > 0 - - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - - getPointDirectLightIrradiance( pointLights[ i ], geometry, directLight ); - - dotNL = dot( geometry.normal, directLight.direction ); - directLightColor_Diffuse = PI * directLight.color; - - vLightFront += saturate( dotNL ) * directLightColor_Diffuse; - - #ifdef DOUBLE_SIDED - - vLightBack += saturate( -dotNL ) * directLightColor_Diffuse; - - #endif - - } - -#endif - -#if NUM_SPOT_LIGHTS > 0 - - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - - getSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight ); - - dotNL = dot( geometry.normal, directLight.direction ); - directLightColor_Diffuse = PI * directLight.color; - - vLightFront += saturate( dotNL ) * directLightColor_Diffuse; - - #ifdef DOUBLE_SIDED - - vLightBack += saturate( -dotNL ) * directLightColor_Diffuse; - - #endif - } - -#endif - -#if NUM_DIR_LIGHTS > 0 - - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - getDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight ); - - dotNL = dot( geometry.normal, directLight.direction ); - directLightColor_Diffuse = PI * directLight.color; - - vLightFront += saturate( dotNL ) * directLightColor_Diffuse; - - #ifdef DOUBLE_SIDED - - vLightBack += saturate( -dotNL ) * directLightColor_Diffuse; - - #endif - - } - -#endif - -#if NUM_HEMI_LIGHTS > 0 - - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - - vLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry ); - - #ifdef DOUBLE_SIDED - - vLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry ); - - #endif - - } - -#endif diff --git a/src/renderers/shaders/ShaderChunk/lights_pars.glsl b/src/renderers/shaders/ShaderChunk/lights_pars.glsl deleted file mode 100644 index 53f569f6b02dc4..00000000000000 --- a/src/renderers/shaders/ShaderChunk/lights_pars.glsl +++ /dev/null @@ -1,300 +0,0 @@ -uniform vec3 ambientLightColor; - -vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { - - vec3 irradiance = ambientLightColor; - - #ifndef PHYSICALLY_CORRECT_LIGHTS - - irradiance *= PI; - - #endif - - return irradiance; - -} - -#if NUM_DIR_LIGHTS > 0 - - struct DirectionalLight { - vec3 direction; - vec3 color; - - int shadow; - float shadowBias; - float shadowRadius; - vec2 shadowMapSize; - }; - - uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; - - void getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) { - - directLight.color = directionalLight.color; - directLight.direction = directionalLight.direction; - directLight.visible = true; - - } - -#endif - - -#if NUM_POINT_LIGHTS > 0 - - struct PointLight { - vec3 position; - vec3 color; - float distance; - float decay; - - int shadow; - float shadowBias; - float shadowRadius; - vec2 shadowMapSize; - }; - - uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; - - // directLight is an out parameter as having it as a return value caused compiler errors on some devices - void getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) { - - vec3 lVector = pointLight.position - geometry.position; - directLight.direction = normalize( lVector ); - - float lightDistance = length( lVector ); - - if ( testLightInRange( lightDistance, pointLight.distance ) ) { - - directLight.color = pointLight.color; - directLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay ); - - directLight.visible = true; - - } else { - - directLight.color = vec3( 0.0 ); - directLight.visible = false; - - } - - } - -#endif - - -#if NUM_SPOT_LIGHTS > 0 - - struct SpotLight { - vec3 position; - vec3 direction; - vec3 color; - float distance; - float decay; - float coneCos; - float penumbraCos; - - int shadow; - float shadowBias; - float shadowRadius; - vec2 shadowMapSize; - }; - - uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; - - // directLight is an out parameter as having it as a return value caused compiler errors on some devices - void getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) { - - vec3 lVector = spotLight.position - geometry.position; - directLight.direction = normalize( lVector ); - - float lightDistance = length( lVector ); - float angleCos = dot( directLight.direction, spotLight.direction ); - - if ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) { - - float spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos ); - - directLight.color = spotLight.color; - directLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay ); - - directLight.visible = true; - - } else { - - directLight.color = vec3( 0.0 ); - directLight.visible = false; - - } - - } - -#endif - - -#if NUM_HEMI_LIGHTS > 0 - - struct HemisphereLight { - vec3 direction; - vec3 skyColor; - vec3 groundColor; - }; - - uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; - - vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) { - - float dotNL = dot( geometry.normal, hemiLight.direction ); - float hemiDiffuseWeight = 0.5 * dotNL + 0.5; - - vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); - - #ifndef PHYSICALLY_CORRECT_LIGHTS - - irradiance *= PI; - - #endif - - return irradiance; - - } - -#endif - - -#if defined( USE_ENVMAP ) && defined( PHYSICAL ) - - vec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) { - - #include - - vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix ); - - #ifdef ENVMAP_TYPE_CUBE - - vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz ); - - // TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level - // of a specular cubemap, or just the default level of a specially created irradiance cubemap. - - #ifdef TEXTURE_LOD_EXT - - vec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) ); - - #else - - // force the bias high to get the last LOD level as it is the most blurred. - vec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) ); - - #endif - - envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb; - - #elif defined( ENVMAP_TYPE_CUBE_UV ) - - vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz ); - vec4 envMapColor = textureCubeUV( queryVec, 1.0 ); - - #else - - vec4 envMapColor = vec4( 0.0 ); - - #endif - - return PI * envMapColor.rgb * envMapIntensity; - - } - - // taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html - float getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) { - - //float envMapWidth = pow( 2.0, maxMIPLevelScalar ); - //float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 ); - - float maxMIPLevelScalar = float( maxMIPLevel ); - float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 ); - - // clamp to allowable LOD ranges. - return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar ); - - } - - vec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) { - - #ifdef ENVMAP_MODE_REFLECTION - - vec3 reflectVec = reflect( -geometry.viewDir, geometry.normal ); - - #else - - vec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio ); - - #endif - - #include - - reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); - - float specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel ); - - #ifdef ENVMAP_TYPE_CUBE - - vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ); - - #ifdef TEXTURE_LOD_EXT - - vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel ); - - #else - - vec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel ); - - #endif - - envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb; - - #elif defined( ENVMAP_TYPE_CUBE_UV ) - - vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ); - vec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent)); - - #elif defined( ENVMAP_TYPE_EQUIREC ) - - vec2 sampleUV; - sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 ); - sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5; - - #ifdef TEXTURE_LOD_EXT - - vec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel ); - - #else - - vec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel ); - - #endif - - envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb; - - #elif defined( ENVMAP_TYPE_SPHERE ) - - vec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) ); - - #ifdef TEXTURE_LOD_EXT - - vec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel ); - - #else - - vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel ); - - #endif - - envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb; - - #endif - - return envMapColor.rgb * envMapIntensity; - - } - -#endif diff --git a/src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl b/src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl deleted file mode 100644 index 3bc610a44da972..00000000000000 --- a/src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -BlinnPhongMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularColor = specular; -material.specularShininess = shininess; -material.specularStrength = specularStrength; diff --git a/src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl deleted file mode 100644 index 3a84818ddc4b9f..00000000000000 --- a/src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl +++ /dev/null @@ -1,45 +0,0 @@ -varying vec3 vViewPosition; - -#ifndef FLAT_SHADED - - varying vec3 vNormal; - -#endif - - -struct BlinnPhongMaterial { - - vec3 diffuseColor; - vec3 specularColor; - float specularShininess; - float specularStrength; - -}; - -void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - - float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); - - vec3 irradiance = dotNL * directLight.color; - - #ifndef PHYSICALLY_CORRECT_LIGHTS - - irradiance *= PI; // punctual light - - #endif - - reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); - reflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength; - -} - -void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - - reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); - -} - -#define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong - -#define Material_LightProbeLOD( material ) (0) diff --git a/src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl b/src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl deleted file mode 100644 index c72658008dd165..00000000000000 --- a/src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl +++ /dev/null @@ -1,10 +0,0 @@ -PhysicalMaterial material; -material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); -material.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 ); -#ifdef STANDARD - material.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor ); -#else - material.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor ); - material.clearCoat = saturate( clearCoat ); // Burley clearcoat model - material.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 ); -#endif diff --git a/src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl deleted file mode 100644 index 22534c3a19c367..00000000000000 --- a/src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl +++ /dev/null @@ -1,91 +0,0 @@ -struct PhysicalMaterial { - - vec3 diffuseColor; - float specularRoughness; - vec3 specularColor; - - #ifndef STANDARD - float clearCoat; - float clearCoatRoughness; - #endif - -}; - -#define MAXIMUM_SPECULAR_COEFFICIENT 0.16 -#define DEFAULT_SPECULAR_COEFFICIENT 0.04 - -// Clear coat directional hemishperical reflectance (this approximation should be improved) -float clearCoatDHRApprox( const in float roughness, const in float dotNL ) { - - return DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) ); - -} - -void RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - - float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); - - vec3 irradiance = dotNL * directLight.color; - - #ifndef PHYSICALLY_CORRECT_LIGHTS - - irradiance *= PI; // punctual light - - #endif - - #ifndef STANDARD - float clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL ); - #else - float clearCoatDHR = 0.0; - #endif - - reflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness ); - reflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); - - #ifndef STANDARD - - reflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness ); - - #endif - -} - -void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - - reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); - -} - -void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - - #ifndef STANDARD - float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) ); - float dotNL = dotNV; - float clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL ); - #else - float clearCoatDHR = 0.0; - #endif - - reflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness ); - - #ifndef STANDARD - - reflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness ); - - #endif - -} - -#define RE_Direct RE_Direct_Physical -#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical -#define RE_IndirectSpecular RE_IndirectSpecular_Physical - -#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness ) -#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness ) - -// ref: http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf -float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { - - return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); - -} diff --git a/src/renderers/shaders/ShaderChunk/lights_template.glsl b/src/renderers/shaders/ShaderChunk/lights_template.glsl deleted file mode 100644 index 0b8576da97799e..00000000000000 --- a/src/renderers/shaders/ShaderChunk/lights_template.glsl +++ /dev/null @@ -1,136 +0,0 @@ -// -// This is a template that can be used to light a material, it uses pluggable RenderEquations (RE) -// for specific lighting scenarios. -// -// Instructions for use: -// - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined -// - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ??? -// - Create a material parameter that is to be passed as the third parameter to your lighting functions. -// -// TODO: -// - Add area light support. -// - Add sphere light support. -// - Add diffuse light probe (irradiance cubemap) support. -// - -GeometricContext geometry; - -geometry.position = - vViewPosition; -geometry.normal = normal; -geometry.viewDir = normalize( vViewPosition ); - -IncidentLight directLight; - -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) - - PointLight pointLight; - - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - - pointLight = pointLights[ i ]; - - getPointDirectLightIrradiance( pointLight, geometry, directLight ); - - #ifdef USE_SHADOWMAP - directLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0; - #endif - - RE_Direct( directLight, geometry, material, reflectedLight ); - - } - -#endif - -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - - SpotLight spotLight; - - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - - spotLight = spotLights[ i ]; - - getSpotDirectLightIrradiance( spotLight, geometry, directLight ); - - #ifdef USE_SHADOWMAP - directLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; - #endif - - RE_Direct( directLight, geometry, material, reflectedLight ); - - } - -#endif - -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) - - DirectionalLight directionalLight; - - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - - getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight ); - - #ifdef USE_SHADOWMAP - directLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - - RE_Direct( directLight, geometry, material, reflectedLight ); - - } - -#endif - -#if defined( RE_IndirectDiffuse ) - - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - - #ifdef USE_LIGHTMAP - - vec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; - - #ifndef PHYSICALLY_CORRECT_LIGHTS - - lightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage - - #endif - - irradiance += lightMapIrradiance; - - #endif - - #if ( NUM_HEMI_LIGHTS > 0 ) - - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry ); - - } - - #endif - - #if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV ) - - // TODO, replace 8 with the real maxMIPLevel - irradiance += getLightProbeIndirectIrradiance( /*lightProbe,*/ geometry, 8 ); - - #endif - - RE_IndirectDiffuse( irradiance, geometry, material, reflectedLight ); - -#endif - -#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) - - // TODO, replace 8 with the real maxMIPLevel - vec3 radiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_BlinnShininessExponent( material ), 8 ); - - #ifndef STANDARD - vec3 clearCoatRadiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 ); - #else - vec3 clearCoatRadiance = vec3( 0.0 ); - #endif - - RE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight ); - -#endif diff --git a/src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl b/src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl deleted file mode 100644 index 2a93ae1c073e14..00000000000000 --- a/src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT) - - gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl deleted file mode 100644 index 1752c5951495eb..00000000000000 --- a/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl +++ /dev/null @@ -1,11 +0,0 @@ -#ifdef USE_LOGDEPTHBUF - - uniform float logDepthBufFC; - - #ifdef USE_LOGDEPTHBUF_EXT - - varying float vFragDepth; - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl deleted file mode 100644 index 41972fcead48bf..00000000000000 --- a/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl +++ /dev/null @@ -1,11 +0,0 @@ -#ifdef USE_LOGDEPTHBUF - - #ifdef USE_LOGDEPTHBUF_EXT - - varying float vFragDepth; - - #endif - - uniform float logDepthBufFC; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl b/src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl deleted file mode 100644 index 2066809f5e30f9..00000000000000 --- a/src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl +++ /dev/null @@ -1,15 +0,0 @@ -#ifdef USE_LOGDEPTHBUF - - gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC; - - #ifdef USE_LOGDEPTHBUF_EXT - - vFragDepth = 1.0 + gl_Position.w; - - #else - - gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w; - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/map_fragment.glsl b/src/renderers/shaders/ShaderChunk/map_fragment.glsl deleted file mode 100644 index b5fb51b16c7ecf..00000000000000 --- a/src/renderers/shaders/ShaderChunk/map_fragment.glsl +++ /dev/null @@ -1,8 +0,0 @@ -#ifdef USE_MAP - - vec4 texelColor = texture2D( map, vUv ); - - texelColor = mapTexelToLinear( texelColor ); - diffuseColor *= texelColor; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl deleted file mode 100644 index d9a03464ba71ec..00000000000000 --- a/src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_MAP - - uniform sampler2D map; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl b/src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl deleted file mode 100644 index 17c752a7e8b8db..00000000000000 --- a/src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl +++ /dev/null @@ -1,6 +0,0 @@ -#ifdef USE_MAP - - vec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy ); - diffuseColor *= mapTexelToLinear( mapTexel ); - -#endif diff --git a/src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl deleted file mode 100644 index cc3c236659a05a..00000000000000 --- a/src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl +++ /dev/null @@ -1,6 +0,0 @@ -#ifdef USE_MAP - - uniform vec4 offsetRepeat; - uniform sampler2D map; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl b/src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl deleted file mode 100644 index be8f3694c752f4..00000000000000 --- a/src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl +++ /dev/null @@ -1,8 +0,0 @@ -float metalnessFactor = metalness; - -#ifdef USE_METALNESSMAP - - vec4 texelMetalness = texture2D( metalnessMap, vUv ); - metalnessFactor *= texelMetalness.r; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl deleted file mode 100644 index 1d9c869e0e10b4..00000000000000 --- a/src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_METALNESSMAP - - uniform sampler2D metalnessMap; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl b/src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl deleted file mode 100644 index b14763b1909e97..00000000000000 --- a/src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl +++ /dev/null @@ -1,8 +0,0 @@ -#ifdef USE_MORPHNORMALS - - objectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ]; - objectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ]; - objectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ]; - objectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ]; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl deleted file mode 100644 index a6664a526a1cec..00000000000000 --- a/src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl +++ /dev/null @@ -1,13 +0,0 @@ -#ifdef USE_MORPHTARGETS - - #ifndef USE_MORPHNORMALS - - uniform float morphTargetInfluences[ 8 ]; - - #else - - uniform float morphTargetInfluences[ 4 ]; - - #endif - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl b/src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl deleted file mode 100644 index baa0d6d944d818..00000000000000 --- a/src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl +++ /dev/null @@ -1,17 +0,0 @@ -#ifdef USE_MORPHTARGETS - - transformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ]; - transformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ]; - transformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ]; - transformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ]; - - #ifndef USE_MORPHNORMALS - - transformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ]; - transformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ]; - transformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ]; - transformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ]; - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/normal_flip.glsl b/src/renderers/shaders/ShaderChunk/normal_flip.glsl deleted file mode 100644 index 7474ec2256e6f7..00000000000000 --- a/src/renderers/shaders/ShaderChunk/normal_flip.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef DOUBLE_SIDED - float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 ); -#else - float flipNormal = 1.0; -#endif diff --git a/src/renderers/shaders/ShaderChunk/normal_fragment.glsl b/src/renderers/shaders/ShaderChunk/normal_fragment.glsl deleted file mode 100644 index 7baeb096e72168..00000000000000 --- a/src/renderers/shaders/ShaderChunk/normal_fragment.glsl +++ /dev/null @@ -1,23 +0,0 @@ -#ifdef FLAT_SHADED - - // Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ... - - vec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) ); - vec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) ); - vec3 normal = normalize( cross( fdx, fdy ) ); - -#else - - vec3 normal = normalize( vNormal ) * flipNormal; - -#endif - -#ifdef USE_NORMALMAP - - normal = perturbNormal2Arb( -vViewPosition, normal ); - -#elif defined( USE_BUMPMAP ) - - normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() ); - -#endif diff --git a/src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl deleted file mode 100644 index 54b93eb59fb3d4..00000000000000 --- a/src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl +++ /dev/null @@ -1,27 +0,0 @@ -#ifdef USE_NORMALMAP - - uniform sampler2D normalMap; - uniform vec2 normalScale; - - // Per-Pixel Tangent Space Normal Mapping - // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html - - vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) { - - vec3 q0 = dFdx( eye_pos.xyz ); - vec3 q1 = dFdy( eye_pos.xyz ); - vec2 st0 = dFdx( vUv.st ); - vec2 st1 = dFdy( vUv.st ); - - vec3 S = normalize( q0 * st1.t - q1 * st0.t ); - vec3 T = normalize( -q0 * st1.s + q1 * st0.s ); - vec3 N = normalize( surf_norm ); - - vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0; - mapN.xy = normalScale * mapN.xy; - mat3 tsn = mat3( S, T, N ); - return normalize( tsn * mapN ); - - } - -#endif diff --git a/src/renderers/shaders/ShaderChunk/packing.glsl b/src/renderers/shaders/ShaderChunk/packing.glsl deleted file mode 100644 index e701776a7b06c1..00000000000000 --- a/src/renderers/shaders/ShaderChunk/packing.glsl +++ /dev/null @@ -1,45 +0,0 @@ -vec3 packNormalToRGB( const in vec3 normal ) { - return normalize( normal ) * 0.5 + 0.5; -} - -vec3 unpackRGBToNormal( const in vec3 rgb ) { - return 1.0 - 2.0 * rgb.xyz; -} - -const float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1) -const float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1) - -const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. ); -const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. ); - -const float ShiftRight8 = 1. / 256.; - -vec4 packDepthToRGBA( const in float v ) { - - vec4 r = vec4( fract( v * PackFactors ), v ); - r.yzw -= r.xyz * ShiftRight8; // tidy overflow - return r * PackUpscale; - -} - -float unpackRGBAToDepth( const in vec4 v ) { - - return dot( v, UnpackFactors ); - -} - -// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions - -float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { - return ( viewZ + near ) / ( near - far ); -} -float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) { - return linearClipZ * ( near - far ) - near; -} - -float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { - return (( near + viewZ ) * far ) / (( far - near ) * viewZ ); -} -float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) { - return ( near * far ) / ( ( far - near ) * invClipZ - far ); -} diff --git a/src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl b/src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl deleted file mode 100644 index 412731941c17b0..00000000000000 --- a/src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl +++ /dev/null @@ -1,6 +0,0 @@ -#ifdef PREMULTIPLIED_ALPHA - - // Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation. - gl_FragColor.rgb *= gl_FragColor.a; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/project_vertex.glsl b/src/renderers/shaders/ShaderChunk/project_vertex.glsl deleted file mode 100644 index 7e04851492ccfa..00000000000000 --- a/src/renderers/shaders/ShaderChunk/project_vertex.glsl +++ /dev/null @@ -1,11 +0,0 @@ -#ifdef USE_SKINNING - - vec4 mvPosition = modelViewMatrix * skinned; - -#else - - vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 ); - -#endif - -gl_Position = projectionMatrix * mvPosition; diff --git a/src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl b/src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl deleted file mode 100644 index a2d24ad8c9360f..00000000000000 --- a/src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl +++ /dev/null @@ -1,8 +0,0 @@ -float roughnessFactor = roughness; - -#ifdef USE_ROUGHNESSMAP - - vec4 texelRoughness = texture2D( roughnessMap, vUv ); - roughnessFactor *= texelRoughness.r; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl deleted file mode 100644 index 0f257121d1a11a..00000000000000 --- a/src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_ROUGHNESSMAP - - uniform sampler2D roughnessMap; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl deleted file mode 100644 index ce581c28ba9de8..00000000000000 --- a/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl +++ /dev/null @@ -1,231 +0,0 @@ -#ifdef USE_SHADOWMAP - - #if NUM_DIR_LIGHTS > 0 - - uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ]; - - #endif - - #if NUM_SPOT_LIGHTS > 0 - - uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ]; - varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ]; - - #endif - - #if NUM_POINT_LIGHTS > 0 - - uniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ]; - - #endif - - float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { - - return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); - - } - - float texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) { - - const vec2 offset = vec2( 0.0, 1.0 ); - - vec2 texelSize = vec2( 1.0 ) / size; - vec2 centroidUV = floor( uv * size + 0.5 ) / size; - - float lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare ); - float lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare ); - float rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare ); - float rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare ); - - vec2 f = fract( uv * size + 0.5 ); - - float a = mix( lb, lt, f.y ); - float b = mix( rb, rt, f.y ); - float c = mix( a, b, f.x ); - - return c; - - } - - float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - - shadowCoord.xyz /= shadowCoord.w; - shadowCoord.z += shadowBias; - - // if ( something && something ) breaks ATI OpenGL shader compiler - // if ( all( something, something ) ) using this instead - - bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 ); - bool inFrustum = all( inFrustumVec ); - - bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 ); - - bool frustumTest = all( frustumTestVec ); - - if ( frustumTest ) { - - #if defined( SHADOWMAP_TYPE_PCF ) - - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - - float dx0 = - texelSize.x * shadowRadius; - float dy0 = - texelSize.y * shadowRadius; - float dx1 = + texelSize.x * shadowRadius; - float dy1 = + texelSize.y * shadowRadius; - - return ( - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) - ) * ( 1.0 / 9.0 ); - - #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) - - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - - float dx0 = - texelSize.x * shadowRadius; - float dy0 = - texelSize.y * shadowRadius; - float dx1 = + texelSize.x * shadowRadius; - float dy1 = + texelSize.y * shadowRadius; - - return ( - texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + - texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + - texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + - texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + - texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) + - texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + - texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + - texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + - texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) - ) * ( 1.0 / 9.0 ); - - #else // no percentage-closer filtering: - - return texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); - - #endif - - } - - return 1.0; - - } - - // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D - // vector suitable for 2D texture mapping. This code uses the following layout for the - // 2D texture: - // - // xzXZ - // y Y - // - // Y - Positive y direction - // y - Negative y direction - // X - Positive x direction - // x - Negative x direction - // Z - Positive z direction - // z - Negative z direction - // - // Source and test bed: - // https://gist.github.com/tschw/da10c43c467ce8afd0c4 - - vec2 cubeToUV( vec3 v, float texelSizeY ) { - - // Number of texels to avoid at the edge of each square - - vec3 absV = abs( v ); - - // Intersect unit cube - - float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); - absV *= scaleToCube; - - // Apply scale to avoid seams - - // two texels less per square (one texel will do for NEAREST) - v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); - - // Unwrap - - // space: -1 ... 1 range for each square - // - // #X## dim := ( 4 , 2 ) - // # # center := ( 1 , 1 ) - - vec2 planar = v.xy; - - float almostATexel = 1.5 * texelSizeY; - float almostOne = 1.0 - almostATexel; - - if ( absV.z >= almostOne ) { - - if ( v.z > 0.0 ) - planar.x = 4.0 - v.x; - - } else if ( absV.x >= almostOne ) { - - float signX = sign( v.x ); - planar.x = v.z * signX + 2.0 * signX; - - } else if ( absV.y >= almostOne ) { - - float signY = sign( v.y ); - planar.x = v.x + 2.0 * signY + 2.0; - planar.y = v.z * signY - 2.0; - - } - - // Transform to UV space - - // scale := 0.5 / dim - // translate := ( center + 0.5 ) / dim - return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); - - } - - float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - - vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); - - // for point lights, the uniform @vShadowCoord is re-purposed to hold - // the distance from the light to the world-space position of the fragment. - vec3 lightToPosition = shadowCoord.xyz; - - // bd3D = base direction 3D - vec3 bd3D = normalize( lightToPosition ); - // dp = distance from light to fragment position - float dp = ( length( lightToPosition ) - shadowBias ) / 1000.0; - - #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) - - vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; - - return ( - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) - ) * ( 1.0 / 9.0 ); - - #else // no percentage-closer filtering - - return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); - - #endif - - } - -#endif diff --git a/src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl deleted file mode 100644 index 13c5d8004dd736..00000000000000 --- a/src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl +++ /dev/null @@ -1,24 +0,0 @@ -#ifdef USE_SHADOWMAP - - #if NUM_DIR_LIGHTS > 0 - - uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ]; - - #endif - - #if NUM_SPOT_LIGHTS > 0 - - uniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ]; - varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ]; - - #endif - - #if NUM_POINT_LIGHTS > 0 - - uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ]; - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl b/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl deleted file mode 100644 index 8248e61209cb06..00000000000000 --- a/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl +++ /dev/null @@ -1,33 +0,0 @@ -#ifdef USE_SHADOWMAP - - #if NUM_DIR_LIGHTS > 0 - - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition; - - } - - #endif - - #if NUM_SPOT_LIGHTS > 0 - - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - - vSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition; - - } - - #endif - - #if NUM_POINT_LIGHTS > 0 - - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - - vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition; - - } - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl deleted file mode 100644 index 04b2dda156b074..00000000000000 --- a/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl +++ /dev/null @@ -1,50 +0,0 @@ -float getShadowMask() { - - float shadow = 1.0; - - #ifdef USE_SHADOWMAP - - #if NUM_DIR_LIGHTS > 0 - - DirectionalLight directionalLight; - - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - shadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - - } - - #endif - - #if NUM_SPOT_LIGHTS > 0 - - SpotLight spotLight; - - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - - spotLight = spotLights[ i ]; - shadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; - - } - - #endif - - #if NUM_POINT_LIGHTS > 0 - - PointLight pointLight; - - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - - pointLight = pointLights[ i ]; - shadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0; - - } - - #endif - - #endif - - return shadow; - -} diff --git a/src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl b/src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl deleted file mode 100644 index d1b3d3936fa72d..00000000000000 --- a/src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl +++ /dev/null @@ -1,8 +0,0 @@ -#ifdef USE_SKINNING - - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl deleted file mode 100644 index d7334f597568d0..00000000000000 --- a/src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl +++ /dev/null @@ -1,47 +0,0 @@ -#ifdef USE_SKINNING - - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - - #ifdef BONE_TEXTURE - - uniform sampler2D boneTexture; - uniform int boneTextureWidth; - uniform int boneTextureHeight; - - mat4 getBoneMatrix( const in float i ) { - - float j = i * 4.0; - float x = mod( j, float( boneTextureWidth ) ); - float y = floor( j / float( boneTextureWidth ) ); - - float dx = 1.0 / float( boneTextureWidth ); - float dy = 1.0 / float( boneTextureHeight ); - - y = dy * ( y + 0.5 ); - - vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) ); - vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) ); - vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) ); - vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) ); - - mat4 bone = mat4( v1, v2, v3, v4 ); - - return bone; - - } - - #else - - uniform mat4 boneMatrices[ MAX_BONES ]; - - mat4 getBoneMatrix( const in float i ) { - - mat4 bone = boneMatrices[ int(i) ]; - return bone; - - } - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderChunk/skinning_vertex.glsl b/src/renderers/shaders/ShaderChunk/skinning_vertex.glsl deleted file mode 100644 index 4d3e18f0bfc5fd..00000000000000 --- a/src/renderers/shaders/ShaderChunk/skinning_vertex.glsl +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef USE_SKINNING - - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - skinned = bindMatrixInverse * skinned; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl b/src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl deleted file mode 100644 index b378a67bd90559..00000000000000 --- a/src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef USE_SKINNING - - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl b/src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl deleted file mode 100644 index 8afac608c5ee00..00000000000000 --- a/src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl +++ /dev/null @@ -1,12 +0,0 @@ -float specularStrength; - -#ifdef USE_SPECULARMAP - - vec4 texelSpecular = texture2D( specularMap, vUv ); - specularStrength = texelSpecular.r; - -#else - - specularStrength = 1.0; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl deleted file mode 100644 index 3df2e4269f6ddb..00000000000000 --- a/src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef USE_SPECULARMAP - - uniform sampler2D specularMap; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl b/src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl deleted file mode 100644 index ce35d9ac329768..00000000000000 --- a/src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#if defined( TONE_MAPPING ) - - gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); - -#endif diff --git a/src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl deleted file mode 100644 index e41267277c913e..00000000000000 --- a/src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl +++ /dev/null @@ -1,39 +0,0 @@ -#define saturate(a) clamp( a, 0.0, 1.0 ) - -uniform float toneMappingExposure; -uniform float toneMappingWhitePoint; - -// exposure only -vec3 LinearToneMapping( vec3 color ) { - - return toneMappingExposure * color; - -} - -// source: https://www.cs.utah.edu/~reinhard/cdrom/ -vec3 ReinhardToneMapping( vec3 color ) { - - color *= toneMappingExposure; - return saturate( color / ( vec3( 1.0 ) + color ) ); - -} - -// source: http://filmicgames.com/archives/75 -#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) ) -vec3 Uncharted2ToneMapping( vec3 color ) { - - // John Hable's filmic operator from Uncharted 2 video game - color *= toneMappingExposure; - return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) ); - -} - -// source: http://filmicgames.com/archives/75 -vec3 OptimizedCineonToneMapping( vec3 color ) { - - // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson - color *= toneMappingExposure; - color = max( vec3( 0.0 ), color - 0.004 ); - return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); - -} diff --git a/src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl deleted file mode 100644 index 37274dbbfbaecf..00000000000000 --- a/src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) - - varying vec2 vUv2; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl deleted file mode 100644 index 6aaa13e304108e..00000000000000 --- a/src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl +++ /dev/null @@ -1,6 +0,0 @@ -#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) - - attribute vec2 uv2; - varying vec2 vUv2; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/uv2_vertex.glsl b/src/renderers/shaders/ShaderChunk/uv2_vertex.glsl deleted file mode 100644 index 72d546a36e3487..00000000000000 --- a/src/renderers/shaders/ShaderChunk/uv2_vertex.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) - - vUv2 = uv2; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl deleted file mode 100644 index d1bb9548cb14f0..00000000000000 --- a/src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP ) - - varying vec2 vUv; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl deleted file mode 100644 index d2e81dd526c1cc..00000000000000 --- a/src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl +++ /dev/null @@ -1,6 +0,0 @@ -#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP ) - - varying vec2 vUv; - uniform vec4 offsetRepeat; - -#endif diff --git a/src/renderers/shaders/ShaderChunk/uv_vertex.glsl b/src/renderers/shaders/ShaderChunk/uv_vertex.glsl deleted file mode 100644 index cbcdf48b47a351..00000000000000 --- a/src/renderers/shaders/ShaderChunk/uv_vertex.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP ) - - vUv = uv * offsetRepeat.zw + offsetRepeat.xy; - -#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl b/src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl deleted file mode 100644 index d1db3f9a04aceb..00000000000000 --- a/src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl +++ /dev/null @@ -1,13 +0,0 @@ -#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP ) - - #ifdef USE_SKINNING - - vec4 worldPosition = modelMatrix * skinned; - - #else - - vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 ); - - #endif - -#endif diff --git a/src/renderers/shaders/ShaderLib.js b/src/renderers/shaders/ShaderLib.js index 73370ec75b94c0..030cccdef44534 100644 --- a/src/renderers/shaders/ShaderLib.js +++ b/src/renderers/shaders/ShaderLib.js @@ -1,3 +1,11 @@ +import { ShaderChunk } from './ShaderChunk'; +import { UniformsUtils } from './UniformsUtils'; +import { Vector3 } from '../../math/Vector3'; +import { UniformsLib } from './UniformsLib'; +import { Color } from '../../math/Color'; + +var ShaderLib; + /** * Webgl Shader Library for three.js * @@ -7,90 +15,90 @@ */ -THREE.ShaderLib = { +ShaderLib = { 'basic': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'fog' ] + UniformsLib[ 'common' ], + UniformsLib[ 'aomap' ], + UniformsLib[ 'fog' ] ] ), - vertexShader: THREE.ShaderChunk[ 'meshbasic_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshbasic_frag' ] + vertexShader: ShaderChunk[ 'meshbasic_vert' ], + fragmentShader: ShaderChunk[ 'meshbasic_frag' ] }, 'lambert': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + UniformsLib[ 'common' ], + UniformsLib[ 'aomap' ], + UniformsLib[ 'lightmap' ], + UniformsLib[ 'emissivemap' ], + UniformsLib[ 'fog' ], + UniformsLib[ 'lights' ], { - "emissive" : { value: new THREE.Color( 0x000000 ) } + "emissive" : { value: new Color( 0x000000 ) } } ] ), - vertexShader: THREE.ShaderChunk[ 'meshlambert_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshlambert_frag' ] + vertexShader: ShaderChunk[ 'meshlambert_vert' ], + fragmentShader: ShaderChunk[ 'meshlambert_frag' ] }, 'phong': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'bumpmap' ], - THREE.UniformsLib[ 'normalmap' ], - THREE.UniformsLib[ 'displacementmap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + UniformsLib[ 'common' ], + UniformsLib[ 'aomap' ], + UniformsLib[ 'lightmap' ], + UniformsLib[ 'emissivemap' ], + UniformsLib[ 'bumpmap' ], + UniformsLib[ 'normalmap' ], + UniformsLib[ 'displacementmap' ], + UniformsLib[ 'fog' ], + UniformsLib[ 'lights' ], { - "emissive" : { value: new THREE.Color( 0x000000 ) }, - "specular" : { value: new THREE.Color( 0x111111 ) }, + "emissive" : { value: new Color( 0x000000 ) }, + "specular" : { value: new Color( 0x111111 ) }, "shininess": { value: 30 } } ] ), - vertexShader: THREE.ShaderChunk[ 'meshphong_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ] + vertexShader: ShaderChunk[ 'meshphong_vert' ], + fragmentShader: ShaderChunk[ 'meshphong_frag' ] }, 'standard': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'bumpmap' ], - THREE.UniformsLib[ 'normalmap' ], - THREE.UniformsLib[ 'displacementmap' ], - THREE.UniformsLib[ 'roughnessmap' ], - THREE.UniformsLib[ 'metalnessmap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + UniformsLib[ 'common' ], + UniformsLib[ 'aomap' ], + UniformsLib[ 'lightmap' ], + UniformsLib[ 'emissivemap' ], + UniformsLib[ 'bumpmap' ], + UniformsLib[ 'normalmap' ], + UniformsLib[ 'displacementmap' ], + UniformsLib[ 'roughnessmap' ], + UniformsLib[ 'metalnessmap' ], + UniformsLib[ 'fog' ], + UniformsLib[ 'lights' ], { - "emissive" : { value: new THREE.Color( 0x000000 ) }, + "emissive" : { value: new Color( 0x000000 ) }, "roughness": { value: 0.5 }, "metalness": { value: 0 }, "envMapIntensity" : { value: 1 }, // temporary @@ -98,31 +106,31 @@ THREE.ShaderLib = { ] ), - vertexShader: THREE.ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphysical_frag' ] + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] }, 'points': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'points' ], - THREE.UniformsLib[ 'fog' ] + UniformsLib[ 'points' ], + UniformsLib[ 'fog' ] ] ), - vertexShader: THREE.ShaderChunk[ 'points_vert' ], - fragmentShader: THREE.ShaderChunk[ 'points_frag' ] + vertexShader: ShaderChunk[ 'points_vert' ], + fragmentShader: ShaderChunk[ 'points_frag' ] }, 'dashed': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'fog' ], + UniformsLib[ 'common' ], + UniformsLib[ 'fog' ], { "scale" : { value: 1 }, @@ -132,22 +140,22 @@ THREE.ShaderLib = { ] ), - vertexShader: THREE.ShaderChunk[ 'linedashed_vert' ], - fragmentShader: THREE.ShaderChunk[ 'linedashed_frag' ] + vertexShader: ShaderChunk[ 'linedashed_vert' ], + fragmentShader: ShaderChunk[ 'linedashed_frag' ] }, 'depth': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'displacementmap' ] + UniformsLib[ 'common' ], + UniformsLib[ 'displacementmap' ] ] ), - vertexShader: THREE.ShaderChunk[ 'depth_vert' ], - fragmentShader: THREE.ShaderChunk[ 'depth_frag' ] + vertexShader: ShaderChunk[ 'depth_vert' ], + fragmentShader: ShaderChunk[ 'depth_frag' ] }, @@ -159,8 +167,8 @@ THREE.ShaderLib = { }, - vertexShader: THREE.ShaderChunk[ 'normal_vert' ], - fragmentShader: THREE.ShaderChunk[ 'normal_frag' ] + vertexShader: ShaderChunk[ 'normal_vert' ], + fragmentShader: ShaderChunk[ 'normal_frag' ] }, @@ -176,8 +184,8 @@ THREE.ShaderLib = { "opacity": { value: 1.0 } }, - vertexShader: THREE.ShaderChunk[ 'cube_vert' ], - fragmentShader: THREE.ShaderChunk[ 'cube_frag' ] + vertexShader: ShaderChunk[ 'cube_vert' ], + fragmentShader: ShaderChunk[ 'cube_frag' ] }, @@ -192,8 +200,8 @@ THREE.ShaderLib = { "tFlip": { value: - 1 } }, - vertexShader: THREE.ShaderChunk[ 'equirect_vert' ], - fragmentShader: THREE.ShaderChunk[ 'equirect_frag' ] + vertexShader: ShaderChunk[ 'equirect_vert' ], + fragmentShader: ShaderChunk[ 'equirect_frag' ] }, @@ -201,22 +209,22 @@ THREE.ShaderLib = { uniforms: { - "lightPos": { value: new THREE.Vector3() } + "lightPos": { value: new Vector3() } }, - vertexShader: THREE.ShaderChunk[ 'distanceRGBA_vert' ], - fragmentShader: THREE.ShaderChunk[ 'distanceRGBA_frag' ] + vertexShader: ShaderChunk[ 'distanceRGBA_vert' ], + fragmentShader: ShaderChunk[ 'distanceRGBA_frag' ] } }; -THREE.ShaderLib[ 'physical' ] = { +ShaderLib[ 'physical' ] = { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.ShaderLib[ 'standard' ].uniforms, + ShaderLib[ 'standard' ].uniforms, { "clearCoat": { value: 0 }, @@ -225,7 +233,10 @@ THREE.ShaderLib[ 'physical' ] = { ] ), - vertexShader: THREE.ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphysical_frag' ] + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] }; + + +export { ShaderLib }; \ No newline at end of file diff --git a/src/renderers/shaders/ShaderLib/cube_frag.glsl b/src/renderers/shaders/ShaderLib/cube_frag.glsl deleted file mode 100644 index 822084c9375ebf..00000000000000 --- a/src/renderers/shaders/ShaderLib/cube_frag.glsl +++ /dev/null @@ -1,14 +0,0 @@ -uniform samplerCube tCube; -uniform float tFlip; -uniform float opacity; - -varying vec3 vWorldPosition; - -#include - -void main() { - - gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) ); - gl_FragColor.a *= opacity; - -} diff --git a/src/renderers/shaders/ShaderLib/cube_vert.glsl b/src/renderers/shaders/ShaderLib/cube_vert.glsl deleted file mode 100644 index d2ca8a2b0754d6..00000000000000 --- a/src/renderers/shaders/ShaderLib/cube_vert.glsl +++ /dev/null @@ -1,12 +0,0 @@ -varying vec3 vWorldPosition; - -#include - -void main() { - - vWorldPosition = transformDirection( position, modelMatrix ); - - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/depth_frag.glsl b/src/renderers/shaders/ShaderLib/depth_frag.glsl deleted file mode 100644 index 4078a9c68fe797..00000000000000 --- a/src/renderers/shaders/ShaderLib/depth_frag.glsl +++ /dev/null @@ -1,43 +0,0 @@ -#if DEPTH_PACKING == 3200 - - uniform float opacity; - -#endif - -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - - vec4 diffuseColor = vec4( 1.0 ); - - #if DEPTH_PACKING == 3200 - - diffuseColor.a = opacity; - - #endif - - #include - #include - #include - - #include - - #if DEPTH_PACKING == 3200 - - gl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity ); - - #elif DEPTH_PACKING == 3201 - - gl_FragColor = packDepthToRGBA( gl_FragCoord.z ); - - #endif - -} diff --git a/src/renderers/shaders/ShaderLib/depth_vert.glsl b/src/renderers/shaders/ShaderLib/depth_vert.glsl deleted file mode 100644 index 590184a0d88a29..00000000000000 --- a/src/renderers/shaders/ShaderLib/depth_vert.glsl +++ /dev/null @@ -1,23 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - - #include - - #include - #include - #include - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl b/src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl deleted file mode 100644 index 22875fd3add12f..00000000000000 --- a/src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl +++ /dev/null @@ -1,14 +0,0 @@ -uniform vec3 lightPos; -varying vec4 vWorldPosition; - -#include -#include -#include - -void main () { - - #include - - gl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 ); - -} diff --git a/src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl b/src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl deleted file mode 100644 index 445102be1fb8ea..00000000000000 --- a/src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl +++ /dev/null @@ -1,20 +0,0 @@ -varying vec4 vWorldPosition; - -#include -#include -#include -#include - -void main() { - - #include - #include - #include - #include - #include - #include - #include - - vWorldPosition = worldPosition; - -} diff --git a/src/renderers/shaders/ShaderLib/equirect_frag.glsl b/src/renderers/shaders/ShaderLib/equirect_frag.glsl deleted file mode 100644 index 81648499b1e6fc..00000000000000 --- a/src/renderers/shaders/ShaderLib/equirect_frag.glsl +++ /dev/null @@ -1,17 +0,0 @@ -uniform sampler2D tEquirect; -uniform float tFlip; - -varying vec3 vWorldPosition; - -#include - -void main() { - - // gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) ); - vec3 direction = normalize( vWorldPosition ); - vec2 sampleUV; - sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 ); - sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5; - gl_FragColor = texture2D( tEquirect, sampleUV ); - -} diff --git a/src/renderers/shaders/ShaderLib/equirect_vert.glsl b/src/renderers/shaders/ShaderLib/equirect_vert.glsl deleted file mode 100644 index d2ca8a2b0754d6..00000000000000 --- a/src/renderers/shaders/ShaderLib/equirect_vert.glsl +++ /dev/null @@ -1,12 +0,0 @@ -varying vec3 vWorldPosition; - -#include - -void main() { - - vWorldPosition = transformDirection( position, modelMatrix ); - - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/linedashed_frag.glsl b/src/renderers/shaders/ShaderLib/linedashed_frag.glsl deleted file mode 100644 index 3c93173641c085..00000000000000 --- a/src/renderers/shaders/ShaderLib/linedashed_frag.glsl +++ /dev/null @@ -1,40 +0,0 @@ -uniform vec3 diffuse; -uniform float opacity; - -uniform float dashSize; -uniform float totalSize; - -varying float vLineDistance; - -#include -#include -#include -#include -#include - -void main() { - - #include - - if ( mod( vLineDistance, totalSize ) > dashSize ) { - - discard; - - } - - vec3 outgoingLight = vec3( 0.0 ); - vec4 diffuseColor = vec4( diffuse, opacity ); - - #include - #include - - outgoingLight = diffuseColor.rgb; // simple shader - - gl_FragColor = vec4( outgoingLight, diffuseColor.a ); - - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/linedashed_vert.glsl b/src/renderers/shaders/ShaderLib/linedashed_vert.glsl deleted file mode 100644 index 954d57cf1b6c04..00000000000000 --- a/src/renderers/shaders/ShaderLib/linedashed_vert.glsl +++ /dev/null @@ -1,23 +0,0 @@ -uniform float scale; -attribute float lineDistance; - -varying float vLineDistance; - -#include -#include -#include -#include - -void main() { - - #include - - vLineDistance = scale * lineDistance; - - vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); - gl_Position = projectionMatrix * mvPosition; - - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/meshbasic_frag.glsl b/src/renderers/shaders/ShaderLib/meshbasic_frag.glsl deleted file mode 100644 index 81d8119ee31700..00000000000000 --- a/src/renderers/shaders/ShaderLib/meshbasic_frag.glsl +++ /dev/null @@ -1,56 +0,0 @@ -uniform vec3 diffuse; -uniform float opacity; - -#ifndef FLAT_SHADED - - varying vec3 vNormal; - -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - - vec4 diffuseColor = vec4( diffuse, opacity ); - - #include - #include - #include - #include - #include - #include - - ReflectedLight reflectedLight; - reflectedLight.directDiffuse = vec3( 0.0 ); - reflectedLight.directSpecular = vec3( 0.0 ); - reflectedLight.indirectDiffuse = diffuseColor.rgb; - reflectedLight.indirectSpecular = vec3( 0.0 ); - - #include - - vec3 outgoingLight = reflectedLight.indirectDiffuse; - - #include - #include - - gl_FragColor = vec4( outgoingLight, diffuseColor.a ); - - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/meshbasic_vert.glsl b/src/renderers/shaders/ShaderLib/meshbasic_vert.glsl deleted file mode 100644 index 7db5a6dd8ebd4d..00000000000000 --- a/src/renderers/shaders/ShaderLib/meshbasic_vert.glsl +++ /dev/null @@ -1,37 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - #include - #include - #include - - #ifdef USE_ENVMAP - - #include - #include - #include - #include - - #endif - - #include - #include - #include - #include - #include - - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/meshlambert_frag.glsl b/src/renderers/shaders/ShaderLib/meshlambert_frag.glsl deleted file mode 100644 index 0a718794b9873c..00000000000000 --- a/src/renderers/shaders/ShaderLib/meshlambert_frag.glsl +++ /dev/null @@ -1,83 +0,0 @@ -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; - -varying vec3 vLightFront; - -#ifdef DOUBLE_SIDED - - varying vec3 vLightBack; - -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - - vec4 diffuseColor = vec4( diffuse, opacity ); - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - - #include - #include - #include - #include - #include - #include - #include - - // accumulation - reflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor ); - - #include - - reflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ); - - #ifdef DOUBLE_SIDED - - reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack; - - #else - - reflectedLight.directDiffuse = vLightFront; - - #endif - - reflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask(); - - // modulation - #include - - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - - #include - #include - - gl_FragColor = vec4( outgoingLight, diffuseColor.a ); - - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/meshlambert_vert.glsl b/src/renderers/shaders/ShaderLib/meshlambert_vert.glsl deleted file mode 100644 index d70ffa2fbc6e83..00000000000000 --- a/src/renderers/shaders/ShaderLib/meshlambert_vert.glsl +++ /dev/null @@ -1,48 +0,0 @@ -#define LAMBERT - -varying vec3 vLightFront; - -#ifdef DOUBLE_SIDED - - varying vec3 vLightBack; - -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - #include - #include - - #include - #include - #include - #include - #include - - #include - #include - #include - #include - #include - #include - - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/meshphong_frag.glsl b/src/renderers/shaders/ShaderLib/meshphong_frag.glsl deleted file mode 100644 index 5041e7a5f1949e..00000000000000 --- a/src/renderers/shaders/ShaderLib/meshphong_frag.glsl +++ /dev/null @@ -1,67 +0,0 @@ -#define PHONG - -uniform vec3 diffuse; -uniform vec3 emissive; -uniform vec3 specular; -uniform float shininess; -uniform float opacity; - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - - vec4 diffuseColor = vec4( diffuse, opacity ); - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - - #include - #include - #include - #include - #include - #include - #include - #include - #include - - // accumulation - #include - #include - - // modulation - #include - - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; - - #include - - gl_FragColor = vec4( outgoingLight, diffuseColor.a ); - - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/meshphong_vert.glsl b/src/renderers/shaders/ShaderLib/meshphong_vert.glsl deleted file mode 100644 index 84b9ade640a74b..00000000000000 --- a/src/renderers/shaders/ShaderLib/meshphong_vert.glsl +++ /dev/null @@ -1,55 +0,0 @@ -#define PHONG - -varying vec3 vViewPosition; - -#ifndef FLAT_SHADED - - varying vec3 vNormal; - -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - #include - #include - - #include - #include - #include - #include - #include - -#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED - - vNormal = normalize( transformedNormal ); - -#endif - - #include - #include - #include - #include - #include - #include - #include - - vViewPosition = - mvPosition.xyz; - - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/meshphysical_frag.glsl b/src/renderers/shaders/ShaderLib/meshphysical_frag.glsl deleted file mode 100644 index 9a050e10de7a65..00000000000000 --- a/src/renderers/shaders/ShaderLib/meshphysical_frag.glsl +++ /dev/null @@ -1,84 +0,0 @@ -#define PHYSICAL - -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float roughness; -uniform float metalness; -uniform float opacity; - -#ifndef STANDARD - uniform float clearCoat; - uniform float clearCoatRoughness; -#endif - -uniform float envMapIntensity; // temporary - -varying vec3 vViewPosition; - -#ifndef FLAT_SHADED - - varying vec3 vNormal; - -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - - vec4 diffuseColor = vec4( diffuse, opacity ); - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - - // accumulation - #include - #include - - // modulation - #include - - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; - - gl_FragColor = vec4( outgoingLight, diffuseColor.a ); - - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/meshphysical_vert.glsl b/src/renderers/shaders/ShaderLib/meshphysical_vert.glsl deleted file mode 100644 index 14c075e5e6d9b6..00000000000000 --- a/src/renderers/shaders/ShaderLib/meshphysical_vert.glsl +++ /dev/null @@ -1,54 +0,0 @@ -#define PHYSICAL - -varying vec3 vViewPosition; - -#ifndef FLAT_SHADED - - varying vec3 vNormal; - -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - #include - #include - - #include - #include - #include - #include - #include - -#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED - - vNormal = normalize( transformedNormal ); - -#endif - - #include - #include - #include - #include - #include - #include - #include - - vViewPosition = - mvPosition.xyz; - - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/normal_frag.glsl b/src/renderers/shaders/ShaderLib/normal_frag.glsl deleted file mode 100644 index e5519cdd890d24..00000000000000 --- a/src/renderers/shaders/ShaderLib/normal_frag.glsl +++ /dev/null @@ -1,16 +0,0 @@ -uniform float opacity; -varying vec3 vNormal; - -#include -#include -#include -#include - -void main() { - - #include - gl_FragColor = vec4( packNormalToRGB( vNormal ), opacity ); - - #include - -} diff --git a/src/renderers/shaders/ShaderLib/normal_vert.glsl b/src/renderers/shaders/ShaderLib/normal_vert.glsl deleted file mode 100644 index ed235ee86040a0..00000000000000 --- a/src/renderers/shaders/ShaderLib/normal_vert.glsl +++ /dev/null @@ -1,18 +0,0 @@ -varying vec3 vNormal; - -#include -#include -#include -#include - -void main() { - - vNormal = normalize( normalMatrix * normal ); - - #include - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/points_frag.glsl b/src/renderers/shaders/ShaderLib/points_frag.glsl deleted file mode 100644 index dbf516f4767da6..00000000000000 --- a/src/renderers/shaders/ShaderLib/points_frag.glsl +++ /dev/null @@ -1,33 +0,0 @@ -uniform vec3 diffuse; -uniform float opacity; - -#include -#include -#include -#include -#include -#include -#include - -void main() { - - #include - - vec3 outgoingLight = vec3( 0.0 ); - vec4 diffuseColor = vec4( diffuse, opacity ); - - #include - #include - #include - #include - - outgoingLight = diffuseColor.rgb; - - gl_FragColor = vec4( outgoingLight, diffuseColor.a ); - - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/points_vert.glsl b/src/renderers/shaders/ShaderLib/points_vert.glsl deleted file mode 100644 index ac53f3668cb66c..00000000000000 --- a/src/renderers/shaders/ShaderLib/points_vert.glsl +++ /dev/null @@ -1,27 +0,0 @@ -uniform float size; -uniform float scale; - -#include -#include -#include -#include -#include - -void main() { - - #include - #include - #include - - #ifdef USE_SIZEATTENUATION - gl_PointSize = size * ( scale / - mvPosition.z ); - #else - gl_PointSize = size; - #endif - - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/ShaderLib/shadow_frag.glsl b/src/renderers/shaders/ShaderLib/shadow_frag.glsl deleted file mode 100644 index 9dcd83a2ec3048..00000000000000 --- a/src/renderers/shaders/ShaderLib/shadow_frag.glsl +++ /dev/null @@ -1,14 +0,0 @@ -uniform float opacity; - -#include -#include -#include -#include -#include -#include - -void main() { - - gl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) ); - -} diff --git a/src/renderers/shaders/ShaderLib/shadow_vert.glsl b/src/renderers/shaders/ShaderLib/shadow_vert.glsl deleted file mode 100644 index e56bd60efa865e..00000000000000 --- a/src/renderers/shaders/ShaderLib/shadow_vert.glsl +++ /dev/null @@ -1,10 +0,0 @@ -#include - -void main() { - - #include - #include - #include - #include - -} diff --git a/src/renderers/shaders/UniformsLib.js b/src/renderers/shaders/UniformsLib.js index 72c9098acefb4e..0a3dab0d6cb8b6 100644 --- a/src/renderers/shaders/UniformsLib.js +++ b/src/renderers/shaders/UniformsLib.js @@ -1,16 +1,22 @@ +import { Vector4 } from '../../math/Vector4'; +import { Color } from '../../math/Color'; +import { Vector2 } from '../../math/Vector2'; + +var UniformsLib; + /** * Uniforms library for shared webgl shaders */ -THREE.UniformsLib = { +UniformsLib = { common: { - "diffuse": { value: new THREE.Color( 0xeeeeee ) }, + "diffuse": { value: new Color( 0xeeeeee ) }, "opacity": { value: 1.0 }, "map": { value: null }, - "offsetRepeat": { value: new THREE.Vector4( 0, 0, 1, 1 ) }, + "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) }, "specularMap": { value: null }, "alphaMap": { value: null }, @@ -52,7 +58,7 @@ THREE.UniformsLib = { normalmap: { "normalMap": { value: null }, - "normalScale": { value: new THREE.Vector2( 1, 1 ) } + "normalScale": { value: new Vector2( 1, 1 ) } }, @@ -81,7 +87,7 @@ THREE.UniformsLib = { "fogDensity": { value: 0.00025 }, "fogNear": { value: 1 }, "fogFar": { value: 2000 }, - "fogColor": { value: new THREE.Color( 0xffffff ) } + "fogColor": { value: new Color( 0xffffff ) } }, @@ -145,13 +151,16 @@ THREE.UniformsLib = { points: { - "diffuse": { value: new THREE.Color( 0xeeeeee ) }, + "diffuse": { value: new Color( 0xeeeeee ) }, "opacity": { value: 1.0 }, "size": { value: 1.0 }, "scale": { value: 1.0 }, "map": { value: null }, - "offsetRepeat": { value: new THREE.Vector4( 0, 0, 1, 1 ) } + "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) } } }; + + +export { UniformsLib }; \ No newline at end of file diff --git a/src/renderers/shaders/UniformsUtils.js b/src/renderers/shaders/UniformsUtils.js index b8b33ff0889926..15b65dd89688d8 100644 --- a/src/renderers/shaders/UniformsUtils.js +++ b/src/renderers/shaders/UniformsUtils.js @@ -1,8 +1,10 @@ +var UniformsUtils; + /** * Uniform Utilities */ -THREE.UniformsUtils = { +UniformsUtils = { merge: function ( uniforms ) { @@ -36,13 +38,13 @@ THREE.UniformsUtils = { var parameter_src = uniforms_src[ u ][ p ]; - if ( parameter_src instanceof THREE.Color || - parameter_src instanceof THREE.Vector2 || - parameter_src instanceof THREE.Vector3 || - parameter_src instanceof THREE.Vector4 || - parameter_src instanceof THREE.Matrix3 || - parameter_src instanceof THREE.Matrix4 || - parameter_src instanceof THREE.Texture ) { + if ( (parameter_src && parameter_src.isColor) || + (parameter_src && parameter_src.isVector2) || + (parameter_src && parameter_src.isVector3) || + (parameter_src && parameter_src.isVector4) || + (parameter_src && parameter_src.isMatrix3) || + (parameter_src && parameter_src.isMatrix4) || + (parameter_src && parameter_src.isTexture) ) { uniforms_dst[ u ][ p ] = parameter_src.clone(); @@ -65,3 +67,6 @@ THREE.UniformsUtils = { } }; + + +export { UniformsUtils }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLBufferRenderer.js b/src/renderers/webgl/WebGLBufferRenderer.js index 700344dddbc405..c0d6ee42c810cd 100644 --- a/src/renderers/webgl/WebGLBufferRenderer.js +++ b/src/renderers/webgl/WebGLBufferRenderer.js @@ -2,7 +2,8 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) { +function WebGLBufferRenderer ( _gl, extensions, _infoRender ) { + this.isWebGLBufferRenderer = true; var mode; @@ -37,7 +38,7 @@ THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) { var count = 0; - if ( position instanceof THREE.InterleavedBufferAttribute ) { + if ( (position && position.isInterleavedBufferAttribute) ) { count = position.data.count; @@ -62,3 +63,6 @@ THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) { this.renderInstances = renderInstances; }; + + +export { WebGLBufferRenderer }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLCapabilities.js b/src/renderers/webgl/WebGLCapabilities.js index ea08751785e3d3..854bd93c05b4d8 100644 --- a/src/renderers/webgl/WebGLCapabilities.js +++ b/src/renderers/webgl/WebGLCapabilities.js @@ -1,4 +1,5 @@ -THREE.WebGLCapabilities = function ( gl, extensions, parameters ) { +function WebGLCapabilities ( gl, extensions, parameters ) { + this.isWebGLCapabilities = true; var maxAnisotropy; @@ -88,3 +89,6 @@ THREE.WebGLCapabilities = function ( gl, extensions, parameters ) { } }; + + +export { WebGLCapabilities }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLClipping.js b/src/renderers/webgl/WebGLClipping.js index 095ecee094957a..ff8c044f2bcbc2 100644 --- a/src/renderers/webgl/WebGLClipping.js +++ b/src/renderers/webgl/WebGLClipping.js @@ -1,4 +1,8 @@ -THREE.WebGLClipping = function() { +import { Matrix3 } from '../../math/Matrix3'; +import { Plane } from '../../math/Plane'; + +function WebGLClipping() { + this.isWebGLClipping = true; var scope = this, @@ -7,8 +11,8 @@ THREE.WebGLClipping = function() { localClippingEnabled = false, renderingShadows = false, - plane = new THREE.Plane(), - viewNormalMatrix = new THREE.Matrix3(), + plane = new Plane(), + viewNormalMatrix = new Matrix3(), uniform = { value: null, needsUpdate: false }; @@ -150,3 +154,6 @@ THREE.WebGLClipping = function() { }; + + +export { WebGLClipping }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLExtensions.js b/src/renderers/webgl/WebGLExtensions.js index d7f972d9b76f55..05d7e516da291e 100644 --- a/src/renderers/webgl/WebGLExtensions.js +++ b/src/renderers/webgl/WebGLExtensions.js @@ -2,7 +2,8 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLExtensions = function ( gl ) { +function WebGLExtensions ( gl ) { + this.isWebGLExtensions = true; var extensions = {}; @@ -56,3 +57,6 @@ THREE.WebGLExtensions = function ( gl ) { }; }; + + +export { WebGLExtensions }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLGeometries.js b/src/renderers/webgl/WebGLGeometries.js index 9b63e24a92726d..377b6115eca5aa 100644 --- a/src/renderers/webgl/WebGLGeometries.js +++ b/src/renderers/webgl/WebGLGeometries.js @@ -1,8 +1,11 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLGeometries = function ( gl, properties, info ) { +function WebGLGeometries ( gl, properties, info ) { + this.isWebGLGeometries = true; var geometries = {}; @@ -20,15 +23,15 @@ THREE.WebGLGeometries = function ( gl, properties, info ) { var buffergeometry; - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { buffergeometry = geometry; - } else if ( geometry instanceof THREE.Geometry ) { + } else if ( (geometry && geometry.isGeometry) ) { if ( geometry._bufferGeometry === undefined ) { - geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object ); + geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); } @@ -91,7 +94,7 @@ THREE.WebGLGeometries = function ( gl, properties, info ) { function getAttributeBuffer( attribute ) { - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { return properties.get( attribute.data ).__webglBuffer; @@ -126,7 +129,7 @@ THREE.WebGLGeometries = function ( gl, properties, info ) { function removeAttributeBuffer( attribute ) { - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { properties.delete( attribute.data ); @@ -141,3 +144,6 @@ THREE.WebGLGeometries = function ( gl, properties, info ) { this.get = get; }; + + +export { WebGLGeometries }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLIndexedBufferRenderer.js b/src/renderers/webgl/WebGLIndexedBufferRenderer.js index f528f4cb23c01e..7db13c9e029244 100644 --- a/src/renderers/webgl/WebGLIndexedBufferRenderer.js +++ b/src/renderers/webgl/WebGLIndexedBufferRenderer.js @@ -2,7 +2,8 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) { +function WebGLIndexedBufferRenderer ( _gl, extensions, _infoRender ) { + this.isWebGLIndexedBufferRenderer = true; var mode; @@ -64,3 +65,6 @@ THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) { this.renderInstances = renderInstances; }; + + +export { WebGLIndexedBufferRenderer }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLLights.js b/src/renderers/webgl/WebGLLights.js index 924ab55a1b67e8..79919392703225 100644 --- a/src/renderers/webgl/WebGLLights.js +++ b/src/renderers/webgl/WebGLLights.js @@ -1,8 +1,13 @@ +import { Color } from '../../math/Color'; +import { Vector3 } from '../../math/Vector3'; +import { Vector2 } from '../../math/Vector2'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLLights = function () { +function WebGLLights () { + this.isWebGLLights = true; var lights = {}; @@ -20,21 +25,21 @@ THREE.WebGLLights = function () { case 'DirectionalLight': uniforms = { - direction: new THREE.Vector3(), - color: new THREE.Color(), + direction: new Vector3(), + color: new Color(), shadow: false, shadowBias: 0, shadowRadius: 1, - shadowMapSize: new THREE.Vector2() + shadowMapSize: new Vector2() }; break; case 'SpotLight': uniforms = { - position: new THREE.Vector3(), - direction: new THREE.Vector3(), - color: new THREE.Color(), + position: new Vector3(), + direction: new Vector3(), + color: new Color(), distance: 0, coneCos: 0, penumbraCos: 0, @@ -43,29 +48,29 @@ THREE.WebGLLights = function () { shadow: false, shadowBias: 0, shadowRadius: 1, - shadowMapSize: new THREE.Vector2() + shadowMapSize: new Vector2() }; break; case 'PointLight': uniforms = { - position: new THREE.Vector3(), - color: new THREE.Color(), + position: new Vector3(), + color: new Color(), distance: 0, decay: 0, shadow: false, shadowBias: 0, shadowRadius: 1, - shadowMapSize: new THREE.Vector2() + shadowMapSize: new Vector2() }; break; case 'HemisphereLight': uniforms = { - direction: new THREE.Vector3(), - skyColor: new THREE.Color(), - groundColor: new THREE.Color() + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() }; break; @@ -78,3 +83,6 @@ THREE.WebGLLights = function () { }; }; + + +export { WebGLLights }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLObjects.js b/src/renderers/webgl/WebGLObjects.js index 1bda38fde34efc..295709f56fc31f 100644 --- a/src/renderers/webgl/WebGLObjects.js +++ b/src/renderers/webgl/WebGLObjects.js @@ -1,10 +1,14 @@ +import { BufferAttribute } from '../../core/BufferAttribute'; +import { WebGLGeometries } from './WebGLGeometries'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLObjects = function ( gl, properties, info ) { +function WebGLObjects ( gl, properties, info ) { + this.isWebGLObjects = true; - var geometries = new THREE.WebGLGeometries( gl, properties, info ); + var geometries = new WebGLGeometries( gl, properties, info ); // @@ -14,7 +18,7 @@ THREE.WebGLObjects = function ( gl, properties, info ) { var geometry = geometries.get( object ); - if ( object.geometry instanceof THREE.Geometry ) { + if ( (object.geometry && object.geometry.isGeometry) ) { geometry.updateFromObject( object ); @@ -57,7 +61,7 @@ THREE.WebGLObjects = function ( gl, properties, info ) { function updateAttribute( attribute, bufferType ) { - var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute; + var data = ( (attribute && attribute.isInterleavedBufferAttribute) ) ? attribute.data : attribute; var attributeProperties = properties.get( data ); @@ -115,7 +119,7 @@ THREE.WebGLObjects = function ( gl, properties, info ) { function getAttributeBuffer( attribute ) { - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { return properties.get( attribute.data ).__webglBuffer; @@ -179,7 +183,7 @@ THREE.WebGLObjects = function ( gl, properties, info ) { // console.timeEnd( 'wireframe' ); var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; - var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 ); + var attribute = new BufferAttribute( new TypeArray( indices ), 1 ); updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); @@ -223,3 +227,6 @@ THREE.WebGLObjects = function ( gl, properties, info ) { this.update = update; }; + + +export { WebGLObjects }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLProgram.js b/src/renderers/webgl/WebGLProgram.js index 1e0353b56b9633..881ce70f71185f 100644 --- a/src/renderers/webgl/WebGLProgram.js +++ b/src/renderers/webgl/WebGLProgram.js @@ -1,4 +1,11 @@ -THREE.WebGLProgram = ( function () { +import { WebGLUniforms } from './WebGLUniforms'; +import { WebGLShader } from './WebGLShader'; +import { ShaderChunk } from '../shaders/ShaderChunk'; +import { NoToneMapping, AddOperation, MixOperation, MultiplyOperation, EquirectangularRefractionMapping, CubeRefractionMapping, SphericalReflectionMapping, EquirectangularReflectionMapping, CubeUVRefractionMapping, CubeUVReflectionMapping, CubeReflectionMapping, PCFSoftShadowMap, PCFShadowMap, CineonToneMapping, Uncharted2ToneMapping, ReinhardToneMapping, LinearToneMapping, GammaEncoding, RGBDEncoding, RGBM16Encoding, RGBM7Encoding, RGBEEncoding, sRGBEncoding, LinearEncoding } from '../../constants'; + +var WebGLProgram; + +WebGLProgram = ( function () { var programIdCount = 0; @@ -6,19 +13,19 @@ THREE.WebGLProgram = ( function () { switch ( encoding ) { - case THREE.LinearEncoding: + case LinearEncoding: return [ 'Linear','( value )' ]; - case THREE.sRGBEncoding: + case sRGBEncoding: return [ 'sRGB','( value )' ]; - case THREE.RGBEEncoding: + case RGBEEncoding: return [ 'RGBE','( value )' ]; - case THREE.RGBM7Encoding: + case RGBM7Encoding: return [ 'RGBM','( value, 7.0 )' ]; - case THREE.RGBM16Encoding: + case RGBM16Encoding: return [ 'RGBM','( value, 16.0 )' ]; - case THREE.RGBDEncoding: + case RGBDEncoding: return [ 'RGBD','( value, 256.0 )' ]; - case THREE.GammaEncoding: + case GammaEncoding: return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ]; default: throw new Error( 'unsupported encoding: ' + encoding ); @@ -47,19 +54,19 @@ THREE.WebGLProgram = ( function () { switch ( toneMapping ) { - case THREE.LinearToneMapping: + case LinearToneMapping: toneMappingName = "Linear"; break; - case THREE.ReinhardToneMapping: + case ReinhardToneMapping: toneMappingName = "Reinhard"; break; - case THREE.Uncharted2ToneMapping: + case Uncharted2ToneMapping: toneMappingName = "Uncharted2"; break; - case THREE.CineonToneMapping: + case CineonToneMapping: toneMappingName = "OptimizedCineon"; break; @@ -148,7 +155,7 @@ THREE.WebGLProgram = ( function () { function replace( match, include ) { - var replace = THREE.ShaderChunk[ include ]; + var replace = ShaderChunk[ include ]; if ( replace === undefined ) { @@ -198,11 +205,11 @@ THREE.WebGLProgram = ( function () { var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - if ( parameters.shadowMapType === THREE.PCFShadowMap ) { + if ( parameters.shadowMapType === PCFShadowMap ) { shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; @@ -216,22 +223,22 @@ THREE.WebGLProgram = ( function () { switch ( material.envMap.mapping ) { - case THREE.CubeReflectionMapping: - case THREE.CubeRefractionMapping: + case CubeReflectionMapping: + case CubeRefractionMapping: envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; break; - case THREE.CubeUVReflectionMapping: - case THREE.CubeUVRefractionMapping: + case CubeUVReflectionMapping: + case CubeUVRefractionMapping: envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; break; - case THREE.EquirectangularReflectionMapping: - case THREE.EquirectangularRefractionMapping: + case EquirectangularReflectionMapping: + case EquirectangularRefractionMapping: envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; break; - case THREE.SphericalReflectionMapping: + case SphericalReflectionMapping: envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; break; @@ -239,8 +246,8 @@ THREE.WebGLProgram = ( function () { switch ( material.envMap.mapping ) { - case THREE.CubeRefractionMapping: - case THREE.EquirectangularRefractionMapping: + case CubeRefractionMapping: + case EquirectangularRefractionMapping: envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; break; @@ -248,15 +255,15 @@ THREE.WebGLProgram = ( function () { switch ( material.combine ) { - case THREE.MultiplyOperation: + case MultiplyOperation: envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; break; - case THREE.MixOperation: + case MixOperation: envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; break; - case THREE.AddOperation: + case AddOperation: envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; break; @@ -280,7 +287,7 @@ THREE.WebGLProgram = ( function () { var prefixVertex, prefixFragment; - if ( material instanceof THREE.RawShaderMaterial ) { + if ( (material && material.isRawShaderMaterial) ) { prefixVertex = [ @@ -455,11 +462,11 @@ THREE.WebGLProgram = ( function () { 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', - ( parameters.toneMapping !== THREE.NoToneMapping ) ? "#define TONE_MAPPING" : '', - ( parameters.toneMapping !== THREE.NoToneMapping ) ? THREE.ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below - ( parameters.toneMapping !== THREE.NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', + ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '', + ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', - ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? THREE.ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below + ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', @@ -479,7 +486,7 @@ THREE.WebGLProgram = ( function () { fragmentShader = parseIncludes( fragmentShader, parameters ); fragmentShader = replaceLightNums( fragmentShader, parameters ); - if ( material instanceof THREE.ShaderMaterial === false ) { + if ( (material && material.isShaderMaterial) === false ) { vertexShader = unrollLoops( vertexShader ); fragmentShader = unrollLoops( fragmentShader ); @@ -492,8 +499,8 @@ THREE.WebGLProgram = ( function () { // console.log( '*VERTEX*', vertexGlsl ); // console.log( '*FRAGMENT*', fragmentGlsl ); - var glVertexShader = THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); - var glFragmentShader = THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); + var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); gl.attachShader( program, glVertexShader ); gl.attachShader( program, glFragmentShader ); @@ -580,7 +587,7 @@ THREE.WebGLProgram = ( function () { if ( cachedUniforms === undefined ) { cachedUniforms = - new THREE.WebGLUniforms( gl, program, renderer ); + new WebGLUniforms( gl, program, renderer ); } @@ -652,3 +659,6 @@ THREE.WebGLProgram = ( function () { }; } )(); + + +export { WebGLProgram }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLPrograms.js b/src/renderers/webgl/WebGLPrograms.js index 45398df0e0c4c4..504bb9cbcd1e17 100644 --- a/src/renderers/webgl/WebGLPrograms.js +++ b/src/renderers/webgl/WebGLPrograms.js @@ -1,4 +1,8 @@ -THREE.WebGLPrograms = function ( renderer, capabilities ) { +import { WebGLProgram } from './WebGLProgram'; +import { BackSide, DoubleSide, FlatShading, CubeUVRefractionMapping, CubeUVReflectionMapping, GammaEncoding, LinearEncoding } from '../../constants'; + +function WebGLPrograms ( renderer, capabilities ) { + this.isWebGLPrograms = true; var programs = []; @@ -49,7 +53,7 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { var maxBones = nVertexMatrices; - if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { + if ( object !== undefined && (object && object.isSkinnedMesh) ) { maxBones = Math.min( object.skeleton.bones.length, maxBones ); @@ -73,13 +77,13 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { if ( ! map ) { - encoding = THREE.LinearEncoding; + encoding = LinearEncoding; - } else if ( map instanceof THREE.Texture ) { + } else if ( (map && map.isTexture) ) { encoding = map.encoding; - } else if ( map instanceof THREE.WebGLRenderTarget ) { + } else if ( (map && map.isWebGLRenderTarget) ) { console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); encoding = map.texture.encoding; @@ -87,9 +91,9 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. - if ( encoding === THREE.LinearEncoding && gammaOverrideLinear ) { + if ( encoding === LinearEncoding && gammaOverrideLinear ) { - encoding = THREE.GammaEncoding; + encoding = GammaEncoding; } @@ -133,7 +137,7 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { envMap: !! material.envMap, envMapMode: material.envMap && material.envMap.mapping, envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ), - envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === THREE.CubeUVReflectionMapping ) || ( material.envMap.mapping === THREE.CubeUVRefractionMapping ) ), + envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ), lightMap: !! material.lightMap, aoMap: !! material.aoMap, emissiveMap: !! material.emissiveMap, @@ -152,9 +156,9 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { fog: !! fog, useFog: material.fog, - fogExp: fog instanceof THREE.FogExp2, + fogExp: (fog && fog.isFogExp2), - flatShading: material.shading === THREE.FlatShading, + flatShading: material.shading === FlatShading, sizeAttenuation: material.sizeAttenuation, logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, @@ -184,8 +188,8 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { premultipliedAlpha: material.premultipliedAlpha, alphaTest: material.alphaTest, - doubleSided: material.side === THREE.DoubleSide, - flipSided: material.side === THREE.BackSide, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false @@ -253,7 +257,7 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { if ( program === undefined ) { - program = new THREE.WebGLProgram( renderer, code, material, parameters ); + program = new WebGLProgram( renderer, code, material, parameters ); programs.push( program ); } @@ -282,3 +286,6 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { this.programs = programs; }; + + +export { WebGLPrograms }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLProperties.js b/src/renderers/webgl/WebGLProperties.js index 7637b85b79d8b4..b213545c0afeec 100644 --- a/src/renderers/webgl/WebGLProperties.js +++ b/src/renderers/webgl/WebGLProperties.js @@ -2,7 +2,8 @@ * @author fordacious / fordacious.github.io */ -THREE.WebGLProperties = function () { +function WebGLProperties () { + this.isWebGLProperties = true; var properties = {}; @@ -35,3 +36,6 @@ THREE.WebGLProperties = function () { }; }; + + +export { WebGLProperties }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLShader.js b/src/renderers/webgl/WebGLShader.js index 6fcbc37e60aebb..93ed5445681f58 100644 --- a/src/renderers/webgl/WebGLShader.js +++ b/src/renderers/webgl/WebGLShader.js @@ -1,4 +1,6 @@ -THREE.WebGLShader = ( function () { +var WebGLShader; + +WebGLShader = ( function () { function addLineNumbers( string ) { @@ -41,3 +43,6 @@ THREE.WebGLShader = ( function () { }; } )(); + + +export { WebGLShader }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLShadowMap.js b/src/renderers/webgl/WebGLShadowMap.js index 45016804159132..452dfe379f0fa1 100644 --- a/src/renderers/webgl/WebGLShadowMap.js +++ b/src/renderers/webgl/WebGLShadowMap.js @@ -1,22 +1,35 @@ +import { FrontSide, BackSide, DoubleSide, RGBAFormat, NearestFilter, PCFShadowMap, RGBADepthPacking } from '../../constants'; +import { WebGLRenderTarget } from '../WebGLRenderTarget'; +import { ShaderMaterial } from '../../materials/ShaderMaterial'; +import { UniformsUtils } from '../shaders/UniformsUtils'; +import { ShaderLib } from '../shaders/ShaderLib'; +import { MeshDepthMaterial } from '../../materials/MeshDepthMaterial'; +import { Vector4 } from '../../math/Vector4'; +import { Vector3 } from '../../math/Vector3'; +import { Vector2 } from '../../math/Vector2'; +import { Matrix4 } from '../../math/Matrix4'; +import { Frustum } from '../../math/Frustum'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { +function WebGLShadowMap ( _renderer, _lights, _objects, capabilities ) { + this.isWebGLShadowMap = true; var _gl = _renderer.context, _state = _renderer.state, - _frustum = new THREE.Frustum(), - _projScreenMatrix = new THREE.Matrix4(), + _frustum = new Frustum(), + _projScreenMatrix = new Matrix4(), _lightShadows = _lights.shadows, - _shadowMapSize = new THREE.Vector2(), - _maxShadowMapSize = new THREE.Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), + _shadowMapSize = new Vector2(), + _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), - _lookTarget = new THREE.Vector3(), - _lightPositionWorld = new THREE.Vector3(), + _lookTarget = new Vector3(), + _lightPositionWorld = new Vector3(), _renderList = [], @@ -31,28 +44,28 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { _materialCache = {}; var cubeDirections = [ - new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ), - new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 ) + new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), + new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) ]; var cubeUps = [ - new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), - new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 ) + new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), + new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) ]; var cube2DViewPorts = [ - new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(), - new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4() + new Vector4(), new Vector4(), new Vector4(), + new Vector4(), new Vector4(), new Vector4() ]; // init - var depthMaterialTemplate = new THREE.MeshDepthMaterial(); - depthMaterialTemplate.depthPacking = THREE.RGBADepthPacking; + var depthMaterialTemplate = new MeshDepthMaterial(); + depthMaterialTemplate.depthPacking = RGBADepthPacking; depthMaterialTemplate.clipping = true; - var distanceShader = THREE.ShaderLib[ "distanceRGBA" ]; - var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms ); + var distanceShader = ShaderLib[ "distanceRGBA" ]; + var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms ); for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { @@ -65,7 +78,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { _depthMaterials[ i ] = depthMaterial; - var distanceMaterial = new THREE.ShaderMaterial( { + var distanceMaterial = new ShaderMaterial( { defines: { 'USE_SHADOWMAP': '' }, @@ -90,7 +103,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { this.autoUpdate = true; this.needsUpdate = false; - this.type = THREE.PCFShadowMap; + this.type = PCFShadowMap; this.renderReverseSided = true; this.renderSingleSided = true; @@ -129,7 +142,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { _shadowMapSize.copy( shadow.mapSize ); _shadowMapSize.min( _maxShadowMapSize ); - if ( light instanceof THREE.PointLight ) { + if ( (light && light.isPointLight) ) { faceCount = 6; isPointLight = true; @@ -175,15 +188,15 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { if ( shadow.map === null ) { - var pars = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat }; + var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; - shadow.map = new THREE.WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); shadowCamera.updateProjectionMatrix(); } - if ( shadow instanceof THREE.SpotLightShadow ) { + if ( (shadow && shadow.isSpotLightShadow) ) { shadow.update( light ); @@ -255,7 +268,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { var geometry = _objects.update( object ); var material = object.material; - if ( material instanceof THREE.MultiMaterial ) { + if ( (material && material.isMultiMaterial) ) { var groups = geometry.groups; var materials = material.materials; @@ -318,11 +331,11 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { if ( material.morphTargets ) { - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - } else if ( geometry instanceof THREE.Geometry ) { + } else if ( (geometry && geometry.isGeometry) ) { useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; @@ -330,7 +343,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { } - var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning; + var useSkinning = (object && object.isSkinnedMesh) && material.skinning; var variantIndex = 0; @@ -381,16 +394,16 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { var side = material.side; - if ( scope.renderSingleSided && side == THREE.DoubleSide ) { + if ( scope.renderSingleSided && side == DoubleSide ) { - side = THREE.FrontSide; + side = FrontSide; } if ( scope.renderReverseSided ) { - if ( side === THREE.FrontSide ) side = THREE.BackSide; - else if ( side === THREE.BackSide ) side = THREE.FrontSide; + if ( side === FrontSide ) side = BackSide; + else if ( side === BackSide ) side = FrontSide; } @@ -416,7 +429,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { if ( object.visible === false ) return; - if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) { + if ( object.layers.test( camera.layers ) && ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) ) { if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { @@ -444,3 +457,6 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { } }; + + +export { WebGLShadowMap }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLState.js b/src/renderers/webgl/WebGLState.js index b03b5b09b31cce..f389dbe92d207a 100644 --- a/src/renderers/webgl/WebGLState.js +++ b/src/renderers/webgl/WebGLState.js @@ -1,15 +1,19 @@ +import { NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, CullFaceFront, CullFaceBack, CullFaceNone, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NoBlending, NormalBlending } from '../../constants'; +import { Vector4 } from '../../math/Vector4'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { +function WebGLState ( gl, extensions, paramThreeToGL ) { + this.isWebGLState = true; var _this = this; this.buffers = { - color: new THREE.WebGLColorBuffer( gl, this ), - depth: new THREE.WebGLDepthBuffer( gl, this ), - stencil: new THREE.WebGLStencilBuffer( gl, this ) + color: new WebGLColorBuffer( gl, this ), + depth: new WebGLDepthBuffer( gl, this ), + stencil: new WebGLStencilBuffer( gl, this ) }; var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); @@ -45,8 +49,8 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { var currentTextureSlot = null; var currentBoundTextures = {}; - var currentScissor = new THREE.Vector4(); - var currentViewport = new THREE.Vector4(); + var currentScissor = new Vector4(); + var currentViewport = new Vector4(); function createTexture( type, target, count ) { @@ -80,14 +84,14 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { this.clearStencil( 0 ); this.enable( gl.DEPTH_TEST ); - this.setDepthFunc( THREE.LessEqualDepth ); + this.setDepthFunc( LessEqualDepth ); this.setFlipSided( false ); - this.setCullFace( THREE.CullFaceBack ); + this.setCullFace( CullFaceBack ); this.enable( gl.CULL_FACE ); this.enable( gl.BLEND ); - this.setBlending( THREE.NormalBlending ); + this.setBlending( NormalBlending ); }; @@ -208,7 +212,7 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { - if ( blending !== THREE.NoBlending ) { + if ( blending !== NoBlending ) { this.enable( gl.BLEND ); @@ -222,7 +226,7 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { - if ( blending === THREE.AdditiveBlending ) { + if ( blending === AdditiveBlending ) { if ( premultipliedAlpha ) { @@ -236,7 +240,7 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { } - } else if ( blending === THREE.SubtractiveBlending ) { + } else if ( blending === SubtractiveBlending ) { if ( premultipliedAlpha ) { @@ -250,7 +254,7 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { } - } else if ( blending === THREE.MultiplyBlending ) { + } else if ( blending === MultiplyBlending ) { if ( premultipliedAlpha ) { @@ -285,7 +289,7 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { } - if ( blending === THREE.CustomBlending ) { + if ( blending === CustomBlending ) { blendEquationAlpha = blendEquationAlpha || blendEquation; blendSrcAlpha = blendSrcAlpha || blendSrc; @@ -398,17 +402,17 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { this.setCullFace = function ( cullFace ) { - if ( cullFace !== THREE.CullFaceNone ) { + if ( cullFace !== CullFaceNone ) { this.enable( gl.CULL_FACE ); if ( cullFace !== currentCullFace ) { - if ( cullFace === THREE.CullFaceBack ) { + if ( cullFace === CullFaceBack ) { gl.cullFace( gl.BACK ); - } else if ( cullFace === THREE.CullFaceFront ) { + } else if ( cullFace === CullFaceFront ) { gl.cullFace( gl.FRONT ); @@ -637,13 +641,14 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { }; -THREE.WebGLColorBuffer = function ( gl, state ) { +function WebGLColorBuffer ( gl, state ) { + this.isWebGLColorBuffer = true; var locked = false; - var color = new THREE.Vector4(); + var color = new Vector4(); var currentColorMask = null; - var currentColorClear = new THREE.Vector4(); + var currentColorClear = new Vector4(); this.setMask = function ( colorMask ) { @@ -680,13 +685,14 @@ THREE.WebGLColorBuffer = function ( gl, state ) { locked = false; currentColorMask = null; - currentColorClear = new THREE.Vector4(); + currentColorClear = new Vector4(); }; }; -THREE.WebGLDepthBuffer = function( gl, state ) { +function WebGLDepthBuffer( gl, state ) { + this.isWebGLDepthBuffer = true; var locked = false; @@ -727,42 +733,42 @@ THREE.WebGLDepthBuffer = function( gl, state ) { switch ( depthFunc ) { - case THREE.NeverDepth: + case NeverDepth: gl.depthFunc( gl.NEVER ); break; - case THREE.AlwaysDepth: + case AlwaysDepth: gl.depthFunc( gl.ALWAYS ); break; - case THREE.LessDepth: + case LessDepth: gl.depthFunc( gl.LESS ); break; - case THREE.LessEqualDepth: + case LessEqualDepth: gl.depthFunc( gl.LEQUAL ); break; - case THREE.EqualDepth: + case EqualDepth: gl.depthFunc( gl.EQUAL ); break; - case THREE.GreaterEqualDepth: + case GreaterEqualDepth: gl.depthFunc( gl.GEQUAL ); break; - case THREE.GreaterDepth: + case GreaterDepth: gl.depthFunc( gl.GREATER ); break; - case THREE.NotEqualDepth: + case NotEqualDepth: gl.depthFunc( gl.NOTEQUAL ); break; @@ -814,7 +820,8 @@ THREE.WebGLDepthBuffer = function( gl, state ) { }; -THREE.WebGLStencilBuffer = function ( gl, state ) { +function WebGLStencilBuffer ( gl, state ) { + this.isWebGLStencilBuffer = true; var locked = false; @@ -917,3 +924,6 @@ THREE.WebGLStencilBuffer = function ( gl, state ) { }; }; + + +export { WebGLStencilBuffer, WebGLDepthBuffer, WebGLColorBuffer, WebGLState }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLTextures.js b/src/renderers/webgl/WebGLTextures.js index e22a485e0826ab..cc12748d233753 100644 --- a/src/renderers/webgl/WebGLTextures.js +++ b/src/renderers/webgl/WebGLTextures.js @@ -1,8 +1,12 @@ +import { LinearFilter, NearestFilter, RGBFormat, RGBAFormat, FloatType, HalfFloatType, ClampToEdgeWrapping, NearestMipMapLinearFilter, NearestMipMapNearestFilter } from '../../constants'; +import { _Math } from '../../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { +function WebGLTextures ( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { + this.isWebGLTextures = true; var _infoMemory = info.memory; var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); @@ -37,7 +41,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie function isPowerOfTwo( image ) { - return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ); + return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height ); } @@ -46,8 +50,8 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = THREE.Math.nearestPowerOfTwo( image.width ); - canvas.height = THREE.Math.nearestPowerOfTwo( image.height ); + canvas.width = _Math.nearestPowerOfTwo( image.width ); + canvas.height = _Math.nearestPowerOfTwo( image.height ); var context = canvas.getContext( '2d' ); context.drawImage( image, 0, 0, canvas.width, canvas.height ); @@ -64,8 +68,8 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie function textureNeedsPowerOfTwo( texture ) { - if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true; - if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true; + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true; + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true; return false; @@ -75,7 +79,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie function filterFallback ( f ) { - if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { + if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { return _gl.NEAREST; @@ -158,7 +162,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie } - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { + if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) { for ( var i = 0; i < 6; i ++ ) { @@ -236,8 +240,8 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - var isCompressed = texture instanceof THREE.CompressedTexture; - var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture; + var isCompressed = (texture && texture.isCompressedTexture); + var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture); var cubeImage = []; @@ -284,7 +288,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie mipmap = mipmaps[ j ]; - if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { @@ -353,7 +357,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) { + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); @@ -362,7 +366,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); - if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) { + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); @@ -374,8 +378,8 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie if ( extension ) { - if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; - if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; + if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; + if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { @@ -425,13 +429,13 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie var mipmap, mipmaps = texture.mipmaps; - if ( texture instanceof THREE.DepthTexture ) { + if ( (texture && texture.isDepthTexture) ) { // populate depth texture with dummy data var internalFormat = _gl.DEPTH_COMPONENT; - if ( texture.type === THREE.FloatType ) { + if ( texture.type === FloatType ) { if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); internalFormat = _gl.DEPTH_COMPONENT32F; @@ -445,7 +449,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); - } else if ( texture instanceof THREE.DataTexture ) { + } else if ( (texture && texture.isDataTexture) ) { // use manually created mipmaps if available // if there are no manual mipmaps @@ -468,13 +472,13 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie } - } else if ( texture instanceof THREE.CompressedTexture ) { + } else if ( (texture && texture.isCompressedTexture) ) { for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; - if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { @@ -572,12 +576,12 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie // Setup resources for a Depth Texture for a FBO (needs an extension) function setupDepthTexture ( framebuffer, renderTarget ) { - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - if ( !( renderTarget.depthTexture instanceof THREE.DepthTexture ) ) { + if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) { throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); @@ -604,7 +608,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie var renderTargetProperties = properties.get( renderTarget ); - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); if ( renderTarget.depthTexture ) { @@ -652,7 +656,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie _infoMemory.textures ++; - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); // Setup framebuffer @@ -715,10 +719,10 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie var texture = renderTarget.texture; if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && - texture.minFilter !== THREE.NearestFilter && - texture.minFilter !== THREE.LinearFilter ) { + texture.minFilter !== NearestFilter && + texture.minFilter !== LinearFilter ) { - var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; var webglTexture = properties.get( texture ).__webglTexture; state.bindTexture( target, webglTexture ); @@ -736,3 +740,6 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie this.updateRenderTargetMipmap = updateRenderTargetMipmap; }; + + +export { WebGLTextures }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLUniforms.js b/src/renderers/webgl/WebGLUniforms.js index 9a954170dcaf74..ca68371f0a0562 100644 --- a/src/renderers/webgl/WebGLUniforms.js +++ b/src/renderers/webgl/WebGLUniforms.js @@ -1,3 +1,8 @@ +import { CubeTexture } from '../../textures/CubeTexture'; +import { Texture } from '../../textures/Texture'; + +var WebGLUniforms; + /** * * Uniforms of a program. @@ -53,10 +58,10 @@ * */ -THREE.WebGLUniforms = ( function() { // scope +WebGLUniforms = ( function() { // scope - var emptyTexture = new THREE.Texture(); - var emptyCubeTexture = new THREE.CubeTexture(); + var emptyTexture = new Texture(); + var emptyCubeTexture = new CubeTexture(); // --- Base for inner nodes (including the root) --- @@ -600,3 +605,6 @@ THREE.WebGLUniforms = ( function() { // scope return WebGLUniforms; } )(); + + +export { WebGLUniforms }; \ No newline at end of file diff --git a/src/renderers/webgl/plugins/LensFlarePlugin.js b/src/renderers/webgl/plugins/LensFlarePlugin.js index 788aa8a0003b85..fd836c2802ad87 100644 --- a/src/renderers/webgl/plugins/LensFlarePlugin.js +++ b/src/renderers/webgl/plugins/LensFlarePlugin.js @@ -1,9 +1,14 @@ +import { Box2 } from '../../../math/Box2'; +import { Vector2 } from '../../../math/Vector2'; +import { Vector3 } from '../../../math/Vector3'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ */ -THREE.LensFlarePlugin = function ( renderer, flares ) { +function LensFlarePlugin ( renderer, flares ) { + this.isLensFlarePlugin = true; var gl = renderer.context; var state = renderer.state; @@ -181,19 +186,19 @@ THREE.LensFlarePlugin = function ( renderer, flares ) { if ( flares.length === 0 ) return; - var tempPosition = new THREE.Vector3(); + var tempPosition = new Vector3(); var invAspect = viewport.w / viewport.z, halfViewportWidth = viewport.z * 0.5, halfViewportHeight = viewport.w * 0.5; var size = 16 / viewport.w, - scale = new THREE.Vector2( size * invAspect, size ); + scale = new Vector2( size * invAspect, size ); - var screenPosition = new THREE.Vector3( 1, 1, 0 ), - screenPositionPixels = new THREE.Vector2( 1, 1 ); + var screenPosition = new Vector3( 1, 1, 0 ), + screenPositionPixels = new Vector2( 1, 1 ); - var validArea = new THREE.Box2(); + var validArea = new Box2(); validArea.min.set( 0, 0 ); validArea.max.set( viewport.z - 16, viewport.w - 16 ); @@ -380,3 +385,6 @@ THREE.LensFlarePlugin = function ( renderer, flares ) { } }; + + +export { LensFlarePlugin }; \ No newline at end of file diff --git a/src/renderers/webgl/plugins/SpritePlugin.js b/src/renderers/webgl/plugins/SpritePlugin.js index 8b65cf0662534e..f1abbbbfeb98e9 100644 --- a/src/renderers/webgl/plugins/SpritePlugin.js +++ b/src/renderers/webgl/plugins/SpritePlugin.js @@ -1,9 +1,14 @@ +import { Texture } from '../../../textures/Texture'; +import { Vector3 } from '../../../math/Vector3'; +import { Quaternion } from '../../../math/Quaternion'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ */ -THREE.SpritePlugin = function ( renderer, sprites ) { +function SpritePlugin ( renderer, sprites ) { + this.isSpritePlugin = true; var gl = renderer.context; var state = renderer.state; @@ -15,9 +20,9 @@ THREE.SpritePlugin = function ( renderer, sprites ) { // decompose matrixWorld - var spritePosition = new THREE.Vector3(); - var spriteRotation = new THREE.Quaternion(); - var spriteScale = new THREE.Vector3(); + var spritePosition = new Vector3(); + var spriteRotation = new Quaternion(); + var spriteScale = new Vector3(); function init() { @@ -80,7 +85,7 @@ THREE.SpritePlugin = function ( renderer, sprites ) { context.fillStyle = 'white'; context.fillRect( 0, 0, 8, 8 ); - texture = new THREE.Texture( canvas ); + texture = new Texture( canvas ); texture.needsUpdate = true; } @@ -126,7 +131,7 @@ THREE.SpritePlugin = function ( renderer, sprites ) { gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); - if ( fog instanceof THREE.Fog ) { + if ( (fog && fog.isFog) ) { gl.uniform1f( uniforms.fogNear, fog.near ); gl.uniform1f( uniforms.fogFar, fog.far ); @@ -135,7 +140,7 @@ THREE.SpritePlugin = function ( renderer, sprites ) { oldFogType = 1; sceneFogType = 1; - } else if ( fog instanceof THREE.FogExp2 ) { + } else if ( (fog && fog.isFogExp2) ) { gl.uniform1f( uniforms.fogDensity, fog.density ); @@ -371,3 +376,6 @@ THREE.SpritePlugin = function ( renderer, sprites ) { } }; + + +export { SpritePlugin }; \ No newline at end of file diff --git a/src/scenes/Fog.js b/src/scenes/Fog.js index cb9b5e08ba9418..d35d8f2fc9066f 100644 --- a/src/scenes/Fog.js +++ b/src/scenes/Fog.js @@ -1,21 +1,27 @@ +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Fog = function ( color, near, far ) { +function Fog ( color, near, far ) { + this.isFog = true; this.name = ''; - this.color = new THREE.Color( color ); + this.color = new Color( color ); this.near = ( near !== undefined ) ? near : 1; this.far = ( far !== undefined ) ? far : 1000; }; -THREE.Fog.prototype.clone = function () { +Fog.prototype.clone = function () { - return new THREE.Fog( this.color.getHex(), this.near, this.far ); + return new Fog( this.color.getHex(), this.near, this.far ); }; + + +export { Fog }; \ No newline at end of file diff --git a/src/scenes/FogExp2.js b/src/scenes/FogExp2.js index 20247e95107f34..177640d1a18eb1 100644 --- a/src/scenes/FogExp2.js +++ b/src/scenes/FogExp2.js @@ -1,19 +1,25 @@ +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.FogExp2 = function ( color, density ) { +function FogExp2 ( color, density ) { + this.isFogExp2 = true; this.name = ''; - this.color = new THREE.Color( color ); + this.color = new Color( color ); this.density = ( density !== undefined ) ? density : 0.00025; }; -THREE.FogExp2.prototype.clone = function () { +FogExp2.prototype.clone = function () { - return new THREE.FogExp2( this.color.getHex(), this.density ); + return new FogExp2( this.color.getHex(), this.density ); }; + + +export { FogExp2 }; \ No newline at end of file diff --git a/src/scenes/Scene.js b/src/scenes/Scene.js index 91436e2136aa06..9a49df52262812 100644 --- a/src/scenes/Scene.js +++ b/src/scenes/Scene.js @@ -1,10 +1,13 @@ +import { Object3D } from '../core/Object3D'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Scene = function () { +function Scene () { + this.isScene = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Scene'; @@ -16,12 +19,12 @@ THREE.Scene = function () { }; -THREE.Scene.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Scene.prototype.constructor = THREE.Scene; +Scene.prototype = Object.create( Object3D.prototype ); +Scene.prototype.constructor = Scene; -THREE.Scene.prototype.copy = function ( source, recursive ) { +Scene.prototype.copy = function ( source, recursive ) { - THREE.Object3D.prototype.copy.call( this, source, recursive ); + Object3D.prototype.copy.call( this, source, recursive ); if ( source.background !== null ) this.background = source.background.clone(); if ( source.fog !== null ) this.fog = source.fog.clone(); @@ -33,3 +36,6 @@ THREE.Scene.prototype.copy = function ( source, recursive ) { return this; }; + + +export { Scene }; \ No newline at end of file diff --git a/src/textures/CanvasTexture.js b/src/textures/CanvasTexture.js index baf661ca1802e7..e73815a9248414 100644 --- a/src/textures/CanvasTexture.js +++ b/src/textures/CanvasTexture.js @@ -1,14 +1,20 @@ +import { Texture } from './Texture'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { +function CanvasTexture ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + this.isCanvasTexture = this.isTexture = true; - THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.needsUpdate = true; }; -THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture; +CanvasTexture.prototype = Object.create( Texture.prototype ); +CanvasTexture.prototype.constructor = CanvasTexture; + + +export { CanvasTexture }; \ No newline at end of file diff --git a/src/textures/CompressedTexture.js b/src/textures/CompressedTexture.js index 3e8937e5561ef0..c9821f9f08f354 100644 --- a/src/textures/CompressedTexture.js +++ b/src/textures/CompressedTexture.js @@ -1,10 +1,13 @@ +import { Texture } from './Texture'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { +function CompressedTexture ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.isCompressedTexture = this.isTexture = true; - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); this.image = { width: width, height: height }; this.mipmaps = mipmaps; @@ -21,5 +24,8 @@ THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mappi }; -THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture; +CompressedTexture.prototype = Object.create( Texture.prototype ); +CompressedTexture.prototype.constructor = CompressedTexture; + + +export { CompressedTexture }; \ No newline at end of file diff --git a/src/textures/CubeTexture.js b/src/textures/CubeTexture.js index 77023b6f7cd554..f9355cb73f4f54 100644 --- a/src/textures/CubeTexture.js +++ b/src/textures/CubeTexture.js @@ -1,22 +1,26 @@ +import { Texture } from './Texture'; +import { CubeReflectionMapping } from '../constants'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { +function CubeTexture ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.isCubeTexture = this.isTexture = true; images = images !== undefined ? images : []; - mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); this.flipY = false; }; -THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CubeTexture.prototype.constructor = THREE.CubeTexture; +CubeTexture.prototype = Object.create( Texture.prototype ); +CubeTexture.prototype.constructor = CubeTexture; -Object.defineProperty( THREE.CubeTexture.prototype, 'images', { +Object.defineProperty( CubeTexture.prototype, 'images', { get: function () { @@ -31,3 +35,6 @@ Object.defineProperty( THREE.CubeTexture.prototype, 'images', { } } ); + + +export { CubeTexture }; \ No newline at end of file diff --git a/src/textures/DataTexture.js b/src/textures/DataTexture.js index 02b065aed273cf..eed343e2fc07ef 100644 --- a/src/textures/DataTexture.js +++ b/src/textures/DataTexture.js @@ -1,20 +1,27 @@ +import { Texture } from './Texture'; +import { NearestFilter } from '../constants'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { +function DataTexture ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.isDataTexture = this.isTexture = true; - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); this.image = { data: data, width: width, height: height }; - this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; this.flipY = false; this.generateMipmaps = false; }; -THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.DataTexture.prototype.constructor = THREE.DataTexture; +DataTexture.prototype = Object.create( Texture.prototype ); +DataTexture.prototype.constructor = DataTexture; + + +export { DataTexture }; \ No newline at end of file diff --git a/src/textures/DepthTexture.js b/src/textures/DepthTexture.js index c368a70f2837a1..d89a7e38e5e325 100644 --- a/src/textures/DepthTexture.js +++ b/src/textures/DepthTexture.js @@ -1,22 +1,29 @@ +import { Texture } from './Texture'; +import { NearestFilter, UnsignedShortType, DepthFormat } from '../constants'; + /** * @author Matt DesLauriers / @mattdesl */ -THREE.DepthTexture = function ( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { +function DepthTexture ( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { + this.isDepthTexture = this.isTexture = true; - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, THREE.DepthFormat, type, anisotropy ); + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, DepthFormat, type, anisotropy ); this.image = { width: width, height: height }; - this.type = type !== undefined ? type : THREE.UnsignedShortType; + this.type = type !== undefined ? type : UnsignedShortType; - this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; this.flipY = false; this.generateMipmaps = false; }; -THREE.DepthTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.DepthTexture.prototype.constructor = THREE.DepthTexture; +DepthTexture.prototype = Object.create( Texture.prototype ); +DepthTexture.prototype.constructor = DepthTexture; + + +export { DepthTexture }; \ No newline at end of file diff --git a/src/textures/Texture.js b/src/textures/Texture.js index 3d82dc013ca825..e5184760584617 100644 --- a/src/textures/Texture.js +++ b/src/textures/Texture.js @@ -1,36 +1,43 @@ +import { EventDispatcher } from '../core/EventDispatcher'; +import { UVMapping } from '../constants'; +import { MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, LinearEncoding, UnsignedByteType, RGBAFormat, LinearMipMapLinearFilter, LinearFilter } from '../constants'; +import { _Math } from '../math/Math'; +import { Vector2 } from '../math/Vector2'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author szimek / https://github.com/szimek/ */ -THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { +function Texture ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.isTexture = true; - Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } ); + Object.defineProperty( this, 'id', { value: TextureIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.sourceFile = ''; - this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE; + this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; this.mipmaps = []; - this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING; + this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; - this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping; + this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; + this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; - this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; this.anisotropy = anisotropy !== undefined ? anisotropy : 1; - this.format = format !== undefined ? format : THREE.RGBAFormat; - this.type = type !== undefined ? type : THREE.UnsignedByteType; + this.format = format !== undefined ? format : RGBAFormat; + this.type = type !== undefined ? type : UnsignedByteType; - this.offset = new THREE.Vector2( 0, 0 ); - this.repeat = new THREE.Vector2( 1, 1 ); + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); this.generateMipmaps = true; this.premultiplyAlpha = false; @@ -42,19 +49,19 @@ THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, f // // Also changing the encoding after already used by a Material will not automatically make the Material // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. - this.encoding = encoding !== undefined ? encoding : THREE.LinearEncoding; + this.encoding = encoding !== undefined ? encoding : LinearEncoding; this.version = 0; this.onUpdate = null; }; -THREE.Texture.DEFAULT_IMAGE = undefined; -THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping; +Texture.DEFAULT_IMAGE = undefined; +Texture.DEFAULT_MAPPING = UVMapping; -THREE.Texture.prototype = { +Texture.prototype = { - constructor: THREE.Texture, + constructor: Texture, set needsUpdate( value ) { @@ -168,7 +175,7 @@ THREE.Texture.prototype = { if ( image.uuid === undefined ) { - image.uuid = THREE.Math.generateUUID(); // UGH + image.uuid = _Math.generateUUID(); // UGH } @@ -199,7 +206,7 @@ THREE.Texture.prototype = { transformUv: function ( uv ) { - if ( this.mapping !== THREE.UVMapping ) return; + if ( this.mapping !== UVMapping ) return; uv.multiply( this.repeat ); uv.add( this.offset ); @@ -208,17 +215,17 @@ THREE.Texture.prototype = { switch ( this.wrapS ) { - case THREE.RepeatWrapping: + case RepeatWrapping: uv.x = uv.x - Math.floor( uv.x ); break; - case THREE.ClampToEdgeWrapping: + case ClampToEdgeWrapping: uv.x = uv.x < 0 ? 0 : 1; break; - case THREE.MirroredRepeatWrapping: + case MirroredRepeatWrapping: if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { @@ -239,17 +246,17 @@ THREE.Texture.prototype = { switch ( this.wrapT ) { - case THREE.RepeatWrapping: + case RepeatWrapping: uv.y = uv.y - Math.floor( uv.y ); break; - case THREE.ClampToEdgeWrapping: + case ClampToEdgeWrapping: uv.y = uv.y < 0 ? 0 : 1; break; - case THREE.MirroredRepeatWrapping: + case MirroredRepeatWrapping: if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { @@ -276,6 +283,10 @@ THREE.Texture.prototype = { }; -Object.assign( THREE.Texture.prototype, THREE.EventDispatcher.prototype ); +Object.assign( Texture.prototype, EventDispatcher.prototype ); + +var count = 0; +function TextureIdCount () { return count++; }; + -THREE.TextureIdCount = 0; +export { TextureIdCount, Texture }; \ No newline at end of file diff --git a/src/textures/VideoTexture.js b/src/textures/VideoTexture.js index a0830777de7a54..49d87512c05ef9 100644 --- a/src/textures/VideoTexture.js +++ b/src/textures/VideoTexture.js @@ -1,10 +1,13 @@ +import { Texture } from './Texture'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { +function VideoTexture ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + this.isVideoTexture = this.isTexture = true; - THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.generateMipmaps = false; @@ -26,5 +29,8 @@ THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilt }; -THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.VideoTexture.prototype.constructor = THREE.VideoTexture; +VideoTexture.prototype = Object.create( Texture.prototype ); +VideoTexture.prototype.constructor = VideoTexture; + + +export { VideoTexture }; \ No newline at end of file From fea0abc4e53dd7e1f5b15a1e921f9631f2042ba9 Mon Sep 17 00:00:00 2001 From: Rich-Harris Date: Sat, 9 Jul 2016 00:00:16 -0400 Subject: [PATCH 2/4] rebuild --- build/three.js | 51355 +++++++++++++++++++++---------------------- build/three.min.js | 1009 +- 2 files changed, 25484 insertions(+), 26880 deletions(-) diff --git a/build/three.js b/build/three.js index 47fb73edde2f7d..3bceefc0b511c5 100644 --- a/build/three.js +++ b/build/three.js @@ -1,41761 +1,41342 @@ -// File:src/Three.js +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.THREE = global.THREE || {}))); +}(this, function (exports) { 'use strict'; -/** - * @author mrdoob / http://mrdoob.com/ - */ + /** + * https://github.com/mrdoob/eventdispatcher.js/ + */ -var THREE = { REVISION: '79dev' }; + function EventDispatcher () { + this.isEventDispatcher = true;}; -// + Object.assign( EventDispatcher.prototype, { -if ( typeof define === 'function' && define.amd ) { + addEventListener: function ( type, listener ) { - define( 'three', THREE ); + if ( this._listeners === undefined ) this._listeners = {}; -} else if ( 'undefined' !== typeof exports && 'undefined' !== typeof module ) { + var listeners = this._listeners; - module.exports = THREE; + if ( listeners[ type ] === undefined ) { -} + listeners[ type ] = []; -// Polyfills + } -if ( Number.EPSILON === undefined ) { + if ( listeners[ type ].indexOf( listener ) === - 1 ) { - Number.EPSILON = Math.pow( 2, - 52 ); + listeners[ type ].push( listener ); -} + } -// + }, -if ( Math.sign === undefined ) { + hasEventListener: function ( type, listener ) { - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + if ( this._listeners === undefined ) return false; - Math.sign = function ( x ) { + var listeners = this._listeners; - return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { - }; + return true; -} + } -if ( Function.prototype.name === undefined ) { + return false; - // Missing in IE9-11. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name + }, - Object.defineProperty( Function.prototype, 'name', { + removeEventListener: function ( type, listener ) { - get: function () { + if ( this._listeners === undefined ) return; - return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; + var listeners = this._listeners; + var listenerArray = listeners[ type ]; - } + if ( listenerArray !== undefined ) { - } ); + var index = listenerArray.indexOf( listener ); -} + if ( index !== - 1 ) { -if ( Object.assign === undefined ) { + listenerArray.splice( index, 1 ); - // Missing in IE. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + } - ( function () { + } - Object.assign = function ( target ) { + }, - 'use strict'; + dispatchEvent: function ( event ) { - if ( target === undefined || target === null ) { + if ( this._listeners === undefined ) return; - throw new TypeError( 'Cannot convert undefined or null to object' ); + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; - } + if ( listenerArray !== undefined ) { - var output = Object( target ); + event.target = this; - for ( var index = 1; index < arguments.length; index ++ ) { + var array = [], i = 0; + var length = listenerArray.length; - var source = arguments[ index ]; + for ( i = 0; i < length; i ++ ) { - if ( source !== undefined && source !== null ) { + array[ i ] = listenerArray[ i ]; - for ( var nextKey in source ) { + } + + for ( i = 0; i < length; i ++ ) { + + array[ i ].call( this, event ); + + } + + } + + } + + } ); + + var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; + var CullFaceNone = 0; + var CullFaceBack = 1; + var CullFaceFront = 2; + var CullFaceFrontBack = 3; + var FrontFaceDirectionCW = 0; + var FrontFaceDirectionCCW = 1; + var BasicShadowMap = 0; + var PCFShadowMap = 1; + var PCFSoftShadowMap = 2; + var FrontSide = 0; + var BackSide = 1; + var DoubleSide = 2; + var FlatShading = 1; + var SmoothShading = 2; + var NoColors = 0; + var FaceColors = 1; + var VertexColors = 2; + var NoBlending = 0; + var NormalBlending = 1; + var AdditiveBlending = 2; + var SubtractiveBlending = 3; + var MultiplyBlending = 4; + var CustomBlending = 5; + var AddEquation = 100; + var SubtractEquation = 101; + var ReverseSubtractEquation = 102; + var MinEquation = 103; + var MaxEquation = 104; + var ZeroFactor = 200; + var OneFactor = 201; + var SrcColorFactor = 202; + var OneMinusSrcColorFactor = 203; + var SrcAlphaFactor = 204; + var OneMinusSrcAlphaFactor = 205; + var DstAlphaFactor = 206; + var OneMinusDstAlphaFactor = 207; + var DstColorFactor = 208; + var OneMinusDstColorFactor = 209; + var SrcAlphaSaturateFactor = 210; + var NeverDepth = 0; + var AlwaysDepth = 1; + var LessDepth = 2; + var LessEqualDepth = 3; + var EqualDepth = 4; + var GreaterEqualDepth = 5; + var GreaterDepth = 6; + var NotEqualDepth = 7; + var MultiplyOperation = 0; + var MixOperation = 1; + var AddOperation = 2; + var NoToneMapping = 0; + var LinearToneMapping = 1; + var ReinhardToneMapping = 2; + var Uncharted2ToneMapping = 3; + var CineonToneMapping = 4; + var UVMapping = 300; + var CubeReflectionMapping = 301; + var CubeRefractionMapping = 302; + var EquirectangularReflectionMapping = 303; + var EquirectangularRefractionMapping = 304; + var SphericalReflectionMapping = 305; + var CubeUVReflectionMapping = 306; + var CubeUVRefractionMapping = 307; + var RepeatWrapping = 1000; + var ClampToEdgeWrapping = 1001; + var MirroredRepeatWrapping = 1002; + var NearestFilter = 1003; + var NearestMipMapNearestFilter = 1004; + var NearestMipMapLinearFilter = 1005; + var LinearFilter = 1006; + var LinearMipMapNearestFilter = 1007; + var LinearMipMapLinearFilter = 1008; + var UnsignedByteType = 1009; + var ByteType = 1010; + var ShortType = 1011; + var UnsignedShortType = 1012; + var IntType = 1013; + var UnsignedIntType = 1014; + var FloatType = 1015; + var HalfFloatType = 1025; + var UnsignedShort4444Type = 1016; + var UnsignedShort5551Type = 1017; + var UnsignedShort565Type = 1018; + var AlphaFormat = 1019; + var RGBFormat = 1020; + var RGBAFormat = 1021; + var LuminanceFormat = 1022; + var LuminanceAlphaFormat = 1023; + var RGBEFormat = RGBAFormat; + var DepthFormat = 1026; + var RGB_S3TC_DXT1_Format = 2001; + var RGBA_S3TC_DXT1_Format = 2002; + var RGBA_S3TC_DXT3_Format = 2003; + var RGBA_S3TC_DXT5_Format = 2004; + var RGB_PVRTC_4BPPV1_Format = 2100; + var RGB_PVRTC_2BPPV1_Format = 2101; + var RGBA_PVRTC_4BPPV1_Format = 2102; + var RGBA_PVRTC_2BPPV1_Format = 2103; + var RGB_ETC1_Format = 2151; + var LoopOnce = 2200; + var LoopRepeat = 2201; + var LoopPingPong = 2202; + var InterpolateDiscrete = 2300; + var InterpolateLinear = 2301; + var InterpolateSmooth = 2302; + var ZeroCurvatureEnding = 2400; + var ZeroSlopeEnding = 2401; + var WrapAroundEnding = 2402; + var TrianglesDrawMode = 0; + var TriangleStripDrawMode = 1; + var TriangleFanDrawMode = 2; + var LinearEncoding = 3000; + var sRGBEncoding = 3001; + var GammaEncoding = 3007; + var RGBEEncoding = 3002; + var LogLuvEncoding = 3003; + var RGBM7Encoding = 3004; + var RGBM16Encoding = 3005; + var RGBDEncoding = 3006; + var BasicDepthPacking = 3200; + var RGBADepthPacking = 3201; + + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ + + exports.Math = { + + DEG2RAD: Math.PI / 180, + RAD2DEG: 180 / Math.PI, + + generateUUID: function () { - if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { + // http://www.broofa.com/Tools/Math.uuid.htm - output[ nextKey ] = source[ nextKey ]; + var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); + var uuid = new Array( 36 ); + var rnd = 0, r; - } + return function generateUUID() { - } + for ( var i = 0; i < 36; i ++ ) { - } + if ( i === 8 || i === 13 || i === 18 || i === 23 ) { - } + uuid[ i ] = '-'; - return output; + } else if ( i === 14 ) { - }; + uuid[ i ] = '4'; - } )(); + } else { -} + if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; + r = rnd & 0xf; + rnd = rnd >> 4; + uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]; -// + } -Object.assign( THREE, { + } - // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button + return uuid.join( '' ); - MOUSE: { LEFT: 0, MIDDLE: 1, RIGHT: 2 }, + }; - // GL STATE CONSTANTS + }(), - CullFaceNone: 0, - CullFaceBack: 1, - CullFaceFront: 2, - CullFaceFrontBack: 3, + clamp: function ( value, min, max ) { - FrontFaceDirectionCW: 0, - FrontFaceDirectionCCW: 1, + return Math.max( min, Math.min( max, value ) ); - // SHADOWING TYPES + }, - BasicShadowMap: 0, - PCFShadowMap: 1, - PCFSoftShadowMap: 2, + // compute euclidian modulo of m % n + // https://en.wikipedia.org/wiki/Modulo_operation - // MATERIAL CONSTANTS + euclideanModulo: function ( n, m ) { - // side + return ( ( n % m ) + m ) % m; - FrontSide: 0, - BackSide: 1, - DoubleSide: 2, + }, - // shading + // Linear mapping from range to range - FlatShading: 1, - SmoothShading: 2, + mapLinear: function ( x, a1, a2, b1, b2 ) { - // colors + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - NoColors: 0, - FaceColors: 1, - VertexColors: 2, + }, - // blending modes + // http://en.wikipedia.org/wiki/Smoothstep - NoBlending: 0, - NormalBlending: 1, - AdditiveBlending: 2, - SubtractiveBlending: 3, - MultiplyBlending: 4, - CustomBlending: 5, + smoothstep: function ( x, min, max ) { - // custom blending equations - // (numbers start from 100 not to clash with other - // mappings to OpenGL constants defined in Texture.js) + if ( x <= min ) return 0; + if ( x >= max ) return 1; - AddEquation: 100, - SubtractEquation: 101, - ReverseSubtractEquation: 102, - MinEquation: 103, - MaxEquation: 104, + x = ( x - min ) / ( max - min ); - // custom blending destination factors + return x * x * ( 3 - 2 * x ); - ZeroFactor: 200, - OneFactor: 201, - SrcColorFactor: 202, - OneMinusSrcColorFactor: 203, - SrcAlphaFactor: 204, - OneMinusSrcAlphaFactor: 205, - DstAlphaFactor: 206, - OneMinusDstAlphaFactor: 207, + }, - // custom blending source factors + smootherstep: function ( x, min, max ) { - //ZeroFactor: 200, - //OneFactor: 201, - //SrcAlphaFactor: 204, - //OneMinusSrcAlphaFactor: 205, - //DstAlphaFactor: 206, - //OneMinusDstAlphaFactor: 207, - DstColorFactor: 208, - OneMinusDstColorFactor: 209, - SrcAlphaSaturateFactor: 210, + if ( x <= min ) return 0; + if ( x >= max ) return 1; - // depth modes + x = ( x - min ) / ( max - min ); - NeverDepth: 0, - AlwaysDepth: 1, - LessDepth: 2, - LessEqualDepth: 3, - EqualDepth: 4, - GreaterEqualDepth: 5, - GreaterDepth: 6, - NotEqualDepth: 7, + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + }, - // TEXTURE CONSTANTS + random16: function () { - MultiplyOperation: 0, - MixOperation: 1, - AddOperation: 2, + console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' ); + return Math.random(); - // Tone Mapping modes + }, - NoToneMapping: 0, // do not do any tone mapping, not even exposure (required for special purpose passes.) - LinearToneMapping: 1, // only apply exposure. - ReinhardToneMapping: 2, - Uncharted2ToneMapping: 3, // John Hable - CineonToneMapping: 4, // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson + // Random integer from interval - // Mapping modes + randInt: function ( low, high ) { - UVMapping: 300, + return low + Math.floor( Math.random() * ( high - low + 1 ) ); - CubeReflectionMapping: 301, - CubeRefractionMapping: 302, + }, - EquirectangularReflectionMapping: 303, - EquirectangularRefractionMapping: 304, + // Random float from interval - SphericalReflectionMapping: 305, - CubeUVReflectionMapping: 306, - CubeUVRefractionMapping: 307, + randFloat: function ( low, high ) { - // Wrapping modes + return low + Math.random() * ( high - low ); - RepeatWrapping: 1000, - ClampToEdgeWrapping: 1001, - MirroredRepeatWrapping: 1002, + }, - // Filters + // Random float from <-range/2, range/2> interval - NearestFilter: 1003, - NearestMipMapNearestFilter: 1004, - NearestMipMapLinearFilter: 1005, - LinearFilter: 1006, - LinearMipMapNearestFilter: 1007, - LinearMipMapLinearFilter: 1008, + randFloatSpread: function ( range ) { - // Data types + return range * ( 0.5 - Math.random() ); - UnsignedByteType: 1009, - ByteType: 1010, - ShortType: 1011, - UnsignedShortType: 1012, - IntType: 1013, - UnsignedIntType: 1014, - FloatType: 1015, - HalfFloatType: 1025, + }, - // Pixel types + degToRad: function ( degrees ) { - //UnsignedByteType: 1009, - UnsignedShort4444Type: 1016, - UnsignedShort5551Type: 1017, - UnsignedShort565Type: 1018, + return degrees * exports.Math.DEG2RAD; - // Pixel formats + }, - AlphaFormat: 1019, - RGBFormat: 1020, - RGBAFormat: 1021, - LuminanceFormat: 1022, - LuminanceAlphaFormat: 1023, - // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders - RGBEFormat: THREE.RGBAFormat, //1024; - DepthFormat: 1026, + radToDeg: function ( radians ) { - // DDS / ST3C Compressed texture formats + return radians * exports.Math.RAD2DEG; - RGB_S3TC_DXT1_Format: 2001, - RGBA_S3TC_DXT1_Format: 2002, - RGBA_S3TC_DXT3_Format: 2003, - RGBA_S3TC_DXT5_Format: 2004, + }, - // PVRTC compressed texture formats + isPowerOfTwo: function ( value ) { - RGB_PVRTC_4BPPV1_Format: 2100, - RGB_PVRTC_2BPPV1_Format: 2101, - RGBA_PVRTC_4BPPV1_Format: 2102, - RGBA_PVRTC_2BPPV1_Format: 2103, + return ( value & ( value - 1 ) ) === 0 && value !== 0; - // ETC compressed texture formats + }, - RGB_ETC1_Format: 2151, + nearestPowerOfTwo: function ( value ) { - // Loop styles for AnimationAction + return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); - LoopOnce: 2200, - LoopRepeat: 2201, - LoopPingPong: 2202, + }, - // Interpolation + nextPowerOfTwo: function ( value ) { - InterpolateDiscrete: 2300, - InterpolateLinear: 2301, - InterpolateSmooth: 2302, + value --; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + value ++; - // Interpolant ending modes + return value; - ZeroCurvatureEnding: 2400, - ZeroSlopeEnding: 2401, - WrapAroundEnding: 2402, + } - // Triangle Draw modes + }; - TrianglesDrawMode: 0, - TriangleStripDrawMode: 1, - TriangleFanDrawMode: 2, + /** + * @author mrdoob / http://mrdoob.com/ + * @author philogb / http://blog.thejit.org/ + * @author egraether / http://egraether.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - // Texture Encodings + function Vector2 ( x, y ) { + this.isVector2 = true; - LinearEncoding: 3000, // No encoding at all. - sRGBEncoding: 3001, - GammaEncoding: 3007, // uses GAMMA_FACTOR, for backwards compatibility with WebGLRenderer.gammaInput/gammaOutput + this.x = x || 0; + this.y = y || 0; - // The following Texture Encodings are for RGB-only (no alpha) HDR light emission sources. - // These encodings should not specified as output encodings except in rare situations. - RGBEEncoding: 3002, // AKA Radiance. - LogLuvEncoding: 3003, - RGBM7Encoding: 3004, - RGBM16Encoding: 3005, - RGBDEncoding: 3006, // MaxRange is 256. + }; - // Depth packing strategies + Vector2.prototype = { - BasicDepthPacking: 3200, // for writing to float textures for high precision or for visualizing results in RGB buffers - RGBADepthPacking: 3201 // for packing into RGBA buffers. + constructor: Vector2, -} ); + get width() { -// File:src/math/Color.js + return this.x; -/** - * @author mrdoob / http://mrdoob.com/ - */ + }, -THREE.Color = function ( r, g, b ) { + set width( value ) { - if ( g === undefined && b === undefined ) { + this.x = value; - // r is THREE.Color, hex or string - return this.set( r ); + }, - } + get height() { - return this.setRGB( r, g, b ); + return this.y; -}; + }, -THREE.Color.prototype = { + set height( value ) { - constructor: THREE.Color, + this.y = value; - r: 1, g: 1, b: 1, + }, - set: function ( value ) { + // - if ( value instanceof THREE.Color ) { + set: function ( x, y ) { - this.copy( value ); + this.x = x; + this.y = y; - } else if ( typeof value === 'number' ) { + return this; - this.setHex( value ); + }, - } else if ( typeof value === 'string' ) { + setScalar: function ( scalar ) { - this.setStyle( value ); + this.x = scalar; + this.y = scalar; - } + return this; - return this; + }, - }, + setX: function ( x ) { - setScalar: function ( scalar ) { + this.x = x; - this.r = scalar; - this.g = scalar; - this.b = scalar; + return this; - }, + }, - setHex: function ( hex ) { + setY: function ( y ) { - hex = Math.floor( hex ); + this.y = y; - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; + return this; - return this; + }, - }, + setComponent: function ( index, value ) { - setRGB: function ( r, g, b ) { + switch ( index ) { - this.r = r; - this.g = g; - this.b = b; + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); - return this; + } - }, + }, - setHSL: function () { + getComponent: function ( index ) { - function hue2rgb( p, q, t ) { + switch ( index ) { - if ( t < 0 ) t += 1; - if ( t > 1 ) t -= 1; - if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; - if ( t < 1 / 2 ) return q; - if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); - return p; + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); - } + } - return function setHSL( h, s, l ) { + }, - // h,s,l ranges are in 0.0 - 1.0 - h = THREE.Math.euclideanModulo( h, 1 ); - s = THREE.Math.clamp( s, 0, 1 ); - l = THREE.Math.clamp( l, 0, 1 ); + clone: function () { - if ( s === 0 ) { + return new this.constructor( this.x, this.y ); - this.r = this.g = this.b = l; + }, - } else { + copy: function ( v ) { - var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - var q = ( 2 * l ) - p; + this.x = v.x; + this.y = v.y; - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); + return this; - } + }, - return this; + add: function ( v, w ) { - }; + if ( w !== undefined ) { - }(), + console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - setStyle: function ( style ) { + } - function handleAlpha( string ) { + this.x += v.x; + this.y += v.y; - if ( string === undefined ) return; + return this; - if ( parseFloat( string ) < 1 ) { + }, - console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + addScalar: function ( s ) { - } + this.x += s; + this.y += s; - } + return this; + }, - var m; + addVectors: function ( a, b ) { - if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { + this.x = a.x + b.x; + this.y = a.y + b.y; - // rgb / hsl + return this; - var color; - var name = m[ 1 ]; - var components = m[ 2 ]; + }, - switch ( name ) { + addScaledVector: function ( v, s ) { - case 'rgb': - case 'rgba': + this.x += v.x * s; + this.y += v.y * s; - if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + return this; - // rgb(255,0,0) rgba(255,0,0,0.5) - this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; - this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; - this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; + }, - handleAlpha( color[ 5 ] ); + sub: function ( v, w ) { - return this; + if ( w !== undefined ) { - } + console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + } - // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) - this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; - this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; - this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; + this.x -= v.x; + this.y -= v.y; - handleAlpha( color[ 5 ] ); + return this; - return this; + }, - } + subScalar: function ( s ) { - break; + this.x -= s; + this.y -= s; - case 'hsl': - case 'hsla': + return this; - if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + }, - // hsl(120,50%,50%) hsla(120,50%,50%,0.5) - var h = parseFloat( color[ 1 ] ) / 360; - var s = parseInt( color[ 2 ], 10 ) / 100; - var l = parseInt( color[ 3 ], 10 ) / 100; + subVectors: function ( a, b ) { - handleAlpha( color[ 5 ] ); + this.x = a.x - b.x; + this.y = a.y - b.y; - return this.setHSL( h, s, l ); + return this; - } + }, - break; + multiply: function ( v ) { - } + this.x *= v.x; + this.y *= v.y; - } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { + return this; - // hex color + }, - var hex = m[ 1 ]; - var size = hex.length; + multiplyScalar: function ( scalar ) { - if ( size === 3 ) { + if ( isFinite( scalar ) ) { - // #ff0 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; + this.x *= scalar; + this.y *= scalar; - return this; + } else { - } else if ( size === 6 ) { + this.x = 0; + this.y = 0; - // #ff0000 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; + } - return this; + return this; - } + }, - } + divide: function ( v ) { - if ( style && style.length > 0 ) { + this.x /= v.x; + this.y /= v.y; - // color keywords - var hex = THREE.ColorKeywords[ style ]; + return this; - if ( hex !== undefined ) { + }, - // red - this.setHex( hex ); + divideScalar: function ( scalar ) { - } else { + return this.multiplyScalar( 1 / scalar ); - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); + }, - } + min: function ( v ) { - } + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); - return this; + return this; - }, + }, - clone: function () { + max: function ( v ) { - return new this.constructor( this.r, this.g, this.b ); + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); - }, + return this; - copy: function ( color ) { + }, - this.r = color.r; - this.g = color.g; - this.b = color.b; + clamp: function ( min, max ) { - return this; + // This function assumes min < max, if this assumption isn't true it will not operate correctly - }, + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - copyGammaToLinear: function ( color, gammaFactor ) { + return this; - if ( gammaFactor === undefined ) gammaFactor = 2.0; + }, - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); + clampScalar: function () { - return this; + var min, max; - }, + return function clampScalar( minVal, maxVal ) { - copyLinearToGamma: function ( color, gammaFactor ) { + if ( min === undefined ) { - if ( gammaFactor === undefined ) gammaFactor = 2.0; + min = new Vector2(); + max = new Vector2(); - var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; + } - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); + min.set( minVal, minVal ); + max.set( maxVal, maxVal ); - return this; + return this.clamp( min, max ); - }, + }; - convertGammaToLinear: function () { + }(), - var r = this.r, g = this.g, b = this.b; + clampLength: function ( min, max ) { - this.r = r * r; - this.g = g * g; - this.b = b * b; + var length = this.length(); - return this; + return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); - }, + }, - convertLinearToGamma: function () { + floor: function () { - this.r = Math.sqrt( this.r ); - this.g = Math.sqrt( this.g ); - this.b = Math.sqrt( this.b ); + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); - return this; + return this; - }, + }, - getHex: function () { + ceil: function () { - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); - }, + return this; - getHexString: function () { + }, - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); + round: function () { - }, + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); - getHSL: function ( optionalTarget ) { + return this; - // h,s,l ranges are in 0.0 - 1.0 + }, - var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; + roundToZero: function () { - var r = this.r, g = this.g, b = this.b; + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - var max = Math.max( r, g, b ); - var min = Math.min( r, g, b ); + return this; - var hue, saturation; - var lightness = ( min + max ) / 2.0; + }, - if ( min === max ) { + negate: function () { - hue = 0; - saturation = 0; + this.x = - this.x; + this.y = - this.y; - } else { + return this; - var delta = max - min; + }, - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + dot: function ( v ) { - switch ( max ) { + return this.x * v.x + this.y * v.y; - case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; - case g: hue = ( b - r ) / delta + 2; break; - case b: hue = ( r - g ) / delta + 4; break; + }, - } + lengthSq: function () { - hue /= 6; + return this.x * this.x + this.y * this.y; - } + }, - hsl.h = hue; - hsl.s = saturation; - hsl.l = lightness; + length: function () { - return hsl; + return Math.sqrt( this.x * this.x + this.y * this.y ); - }, + }, - getStyle: function () { + lengthManhattan: function() { - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; + return Math.abs( this.x ) + Math.abs( this.y ); - }, + }, - offsetHSL: function ( h, s, l ) { + normalize: function () { - var hsl = this.getHSL(); + return this.divideScalar( this.length() ); - hsl.h += h; hsl.s += s; hsl.l += l; + }, - this.setHSL( hsl.h, hsl.s, hsl.l ); + angle: function () { - return this; + // computes the angle in radians with respect to the positive x-axis - }, + var angle = Math.atan2( this.y, this.x ); - add: function ( color ) { + if ( angle < 0 ) angle += 2 * Math.PI; - this.r += color.r; - this.g += color.g; - this.b += color.b; + return angle; - return this; + }, - }, + distanceTo: function ( v ) { - addColors: function ( color1, color2 ) { + return Math.sqrt( this.distanceToSquared( v ) ); - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; + }, - return this; + distanceToSquared: function ( v ) { - }, + var dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; - addScalar: function ( s ) { + }, - this.r += s; - this.g += s; - this.b += s; + distanceToManhattan: function ( v ) { - return this; + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); - }, + }, - sub: function( color ) { + setLength: function ( length ) { - this.r = Math.max( 0, this.r - color.r ); - this.g = Math.max( 0, this.g - color.g ); - this.b = Math.max( 0, this.b - color.b ); + return this.multiplyScalar( length / this.length() ); - return this; + }, - }, + lerp: function ( v, alpha ) { - multiply: function ( color ) { + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; + return this; - return this; + }, - }, + lerpVectors: function ( v1, v2, alpha ) { - multiplyScalar: function ( s ) { + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - this.r *= s; - this.g *= s; - this.b *= s; + }, - return this; + equals: function ( v ) { - }, + return ( ( v.x === this.x ) && ( v.y === this.y ) ); - lerp: function ( color, alpha ) { + }, - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; + fromArray: function ( array, offset ) { - return this; + if ( offset === undefined ) offset = 0; - }, + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; - equals: function ( c ) { + return this; - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + }, - }, + toArray: function ( array, offset ) { - fromArray: function ( array, offset ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - if ( offset === undefined ) offset = 0; + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; - this.r = array[ offset ]; - this.g = array[ offset + 1 ]; - this.b = array[ offset + 2 ]; + return array; - return this; + }, - }, + fromAttribute: function ( attribute, index, offset ) { - toArray: function ( array, offset ) { + if ( offset === undefined ) offset = 0; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + index = index * attribute.itemSize + offset; - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; - return array; + return this; - } + }, -}; + rotateAround: function ( center, angle ) { -THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, -'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, -'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, -'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, -'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, -'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, -'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, -'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, -'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, -'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, -'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, -'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, -'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, -'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, -'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, -'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, -'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, -'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, -'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, -'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, -'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, -'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, -'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, -'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; - -// File:src/math/Quaternion.js + var c = Math.cos( angle ), s = Math.sin( angle ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ + var x = this.x - center.x; + var y = this.y - center.y; -THREE.Quaternion = function ( x, y, z, w ) { + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._w = ( w !== undefined ) ? w : 1; + return this; -}; + } -THREE.Quaternion.prototype = { + }; - constructor: THREE.Quaternion, + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + */ - get x () { + function Texture ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.isTexture = true; - return this._x; + Object.defineProperty( this, 'id', { value: TextureIdCount() } ); - }, + this.uuid = exports.Math.generateUUID(); - set x ( value ) { + this.name = ''; + this.sourceFile = ''; - this._x = value; - this.onChangeCallback(); + this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; + this.mipmaps = []; - }, + this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; - get y () { + this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; + this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; - return this._y; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; - }, + this.anisotropy = anisotropy !== undefined ? anisotropy : 1; - set y ( value ) { + this.format = format !== undefined ? format : RGBAFormat; + this.type = type !== undefined ? type : UnsignedByteType; - this._y = value; - this.onChangeCallback(); + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); - }, + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) - get z () { - return this._z; + // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. + // + // Also changing the encoding after already used by a Material will not automatically make the Material + // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. + this.encoding = encoding !== undefined ? encoding : LinearEncoding; - }, + this.version = 0; + this.onUpdate = null; - set z ( value ) { + }; - this._z = value; - this.onChangeCallback(); + Texture.DEFAULT_IMAGE = undefined; + Texture.DEFAULT_MAPPING = UVMapping; - }, + Texture.prototype = { - get w () { + constructor: Texture, - return this._w; + set needsUpdate( value ) { - }, + if ( value === true ) this.version ++; - set w ( value ) { + }, - this._w = value; - this.onChangeCallback(); + clone: function () { - }, + return new this.constructor().copy( this ); - set: function ( x, y, z, w ) { + }, - this._x = x; - this._y = y; - this._z = z; - this._w = w; + copy: function ( source ) { - this.onChangeCallback(); + this.image = source.image; + this.mipmaps = source.mipmaps.slice( 0 ); - return this; + this.mapping = source.mapping; - }, + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; - clone: function () { + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; - return new this.constructor( this._x, this._y, this._z, this._w ); + this.anisotropy = source.anisotropy; - }, + this.format = source.format; + this.type = source.type; - copy: function ( quaternion ) { + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; - this.onChangeCallback(); + return this; - return this; + }, - }, + toJSON: function ( meta ) { - setFromEuler: function ( euler, update ) { + if ( meta.textures[ this.uuid ] !== undefined ) { - if ( euler instanceof THREE.Euler === false ) { + return meta.textures[ this.uuid ]; - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + } - } + function getDataURL( image ) { - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m + var canvas; - var c1 = Math.cos( euler._x / 2 ); - var c2 = Math.cos( euler._y / 2 ); - var c3 = Math.cos( euler._z / 2 ); - var s1 = Math.sin( euler._x / 2 ); - var s2 = Math.sin( euler._y / 2 ); - var s3 = Math.sin( euler._z / 2 ); + if ( image.toDataURL !== undefined ) { - var order = euler.order; + canvas = image; - if ( order === 'XYZ' ) { + } else { - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = image.width; + canvas.height = image.height; - } else if ( order === 'YXZ' ) { + canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + } - } else if ( order === 'ZXY' ) { + if ( canvas.width > 2048 || canvas.height > 2048 ) { - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + return canvas.toDataURL( 'image/jpeg', 0.6 ); - } else if ( order === 'ZYX' ) { + } else { - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + return canvas.toDataURL( 'image/png' ); - } else if ( order === 'YZX' ) { + } - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + } - } else if ( order === 'XZY' ) { + var output = { + metadata: { + version: 4.4, + type: 'Texture', + generator: 'Texture.toJSON' + }, - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + uuid: this.uuid, + name: this.name, - } + mapping: this.mapping, - if ( update !== false ) this.onChangeCallback(); + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + wrap: [ this.wrapS, this.wrapT ], - return this; + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, - }, + flipY: this.flipY + }; - setFromAxisAngle: function ( axis, angle ) { + if ( this.image !== undefined ) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + // TODO: Move to THREE.Image - // assumes axis is normalized + var image = this.image; - var halfAngle = angle / 2, s = Math.sin( halfAngle ); + if ( image.uuid === undefined ) { - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); + image.uuid = exports.Math.generateUUID(); // UGH - this.onChangeCallback(); + } - return this; + if ( meta.images[ image.uuid ] === undefined ) { - }, + meta.images[ image.uuid ] = { + uuid: image.uuid, + url: getDataURL( image ) + }; - setFromRotationMatrix: function ( m ) { + } - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + output.image = image.uuid; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + } - var te = m.elements, + meta.textures[ this.uuid ] = output; - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], + return output; - trace = m11 + m22 + m33, - s; + }, - if ( trace > 0 ) { + dispose: function () { - s = 0.5 / Math.sqrt( trace + 1.0 ); + this.dispatchEvent( { type: 'dispose' } ); - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; + }, - } else if ( m11 > m22 && m11 > m33 ) { + transformUv: function ( uv ) { - s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + if ( this.mapping !== UVMapping ) return; - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; + uv.multiply( this.repeat ); + uv.add( this.offset ); - } else if ( m22 > m33 ) { + if ( uv.x < 0 || uv.x > 1 ) { - s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + switch ( this.wrapS ) { - this._w = ( m13 - m31 ) / s; - this._x = ( m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = ( m23 + m32 ) / s; + case RepeatWrapping: - } else { + uv.x = uv.x - Math.floor( uv.x ); + break; - s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + case ClampToEdgeWrapping: - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; + uv.x = uv.x < 0 ? 0 : 1; + break; - } + case MirroredRepeatWrapping: - this.onChangeCallback(); + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { - return this; + uv.x = Math.ceil( uv.x ) - uv.x; - }, + } else { - setFromUnitVectors: function () { + uv.x = uv.x - Math.floor( uv.x ); - // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final + } + break; - // assumes direction vectors vFrom and vTo are normalized + } - var v1, r; + } - var EPS = 0.000001; + if ( uv.y < 0 || uv.y > 1 ) { - return function setFromUnitVectors( vFrom, vTo ) { + switch ( this.wrapT ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + case RepeatWrapping: - r = vFrom.dot( vTo ) + 1; + uv.y = uv.y - Math.floor( uv.y ); + break; - if ( r < EPS ) { + case ClampToEdgeWrapping: - r = 0; + uv.y = uv.y < 0 ? 0 : 1; + break; - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + case MirroredRepeatWrapping: - v1.set( - vFrom.y, vFrom.x, 0 ); + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { - } else { + uv.y = Math.ceil( uv.y ) - uv.y; - v1.set( 0, - vFrom.z, vFrom.y ); + } else { - } + uv.y = uv.y - Math.floor( uv.y ); - } else { + } + break; - v1.crossVectors( vFrom, vTo ); + } - } + } - this._x = v1.x; - this._y = v1.y; - this._z = v1.z; - this._w = r; + if ( this.flipY ) { - return this.normalize(); + uv.y = 1 - uv.y; - }; + } - }(), + } - inverse: function () { + }; - return this.conjugate().normalize(); + Object.assign( Texture.prototype, EventDispatcher.prototype ); - }, + var count = 0; + function TextureIdCount () { return count++; }; - conjugate: function () { + /** + * @author mrdoob / http://mrdoob.com/ + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author philogb / http://blog.thejit.org/ + * @author jordi_ros / http://plattsoft.com + * @author D1plo1d / http://github.com/D1plo1d + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author timknip / http://www.floorplanner.com/ + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; + function Matrix4 () { + this.isMatrix4 = true; - this.onChangeCallback(); + this.elements = new Float32Array( [ - return this; + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - }, + ] ); - dot: function ( v ) { + if ( arguments.length > 0 ) { - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - }, + } - lengthSq: function () { + }; - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + Matrix4.prototype = { - }, + constructor: Matrix4, - length: function () { + set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + var te = this.elements; - }, + te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; + te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; + te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; + te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; - normalize: function () { + return this; - var l = this.length(); + }, - if ( l === 0 ) { + identity: function () { - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; + this.set( - } else { + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - l = 1 / l; + ); - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; + return this; - } + }, - this.onChangeCallback(); + clone: function () { - return this; + return new Matrix4().fromArray( this.elements ); - }, + }, - multiply: function ( q, p ) { + copy: function ( m ) { - if ( p !== undefined ) { + this.elements.set( m.elements ); - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); + return this; - } + }, - return this.multiplyQuaternions( this, q ); + copyPosition: function ( m ) { - }, + var te = this.elements; + var me = m.elements; - premultiply: function ( q ) { + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - return this.multiplyQuaternions( q, this ); + return this; - }, + }, - multiplyQuaternions: function ( a, b ) { + extractBasis: function ( xAxis, yAxis, zAxis ) { - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); - var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; - var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + return this; - this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; - this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; - this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; - this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + }, - this.onChangeCallback(); + makeBasis: function ( xAxis, yAxis, zAxis ) { - return this; + this.set( + xAxis.x, yAxis.x, zAxis.x, 0, + xAxis.y, yAxis.y, zAxis.y, 0, + xAxis.z, yAxis.z, zAxis.z, 0, + 0, 0, 0, 1 + ); - }, + return this; - slerp: function ( qb, t ) { + }, - if ( t === 0 ) return this; - if ( t === 1 ) return this.copy( qb ); + extractRotation: function () { - var x = this._x, y = this._y, z = this._z, w = this._w; + var v1; - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + return function extractRotation( m ) { - var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + if ( v1 === undefined ) v1 = new Vector3(); - if ( cosHalfTheta < 0 ) { + var te = this.elements; + var me = m.elements; - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; + var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); + var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); + var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); - cosHalfTheta = - cosHalfTheta; + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; - } else { + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; - this.copy( qb ); + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; - } + return this; - if ( cosHalfTheta >= 1.0 ) { + }; - this._w = w; - this._x = x; - this._y = y; - this._z = z; + }(), - return this; + makeRotationFromEuler: function ( euler ) { - } + if ( (euler && euler.isEuler) === false ) { - var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); + console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - if ( Math.abs( sinHalfTheta ) < 0.001 ) { + } - this._w = 0.5 * ( w + this._w ); - this._x = 0.5 * ( x + this._x ); - this._y = 0.5 * ( y + this._y ); - this._z = 0.5 * ( z + this._z ); + var te = this.elements; - return this; + var x = euler.x, y = euler.y, z = euler.z; + var a = Math.cos( x ), b = Math.sin( x ); + var c = Math.cos( y ), d = Math.sin( y ); + var e = Math.cos( z ), f = Math.sin( z ); - } + if ( euler.order === 'XYZ' ) { - var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); - var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + var ae = a * e, af = a * f, be = b * e, bf = b * f; - this._w = ( w * ratioA + this._w * ratioB ); - this._x = ( x * ratioA + this._x * ratioB ); - this._y = ( y * ratioA + this._y * ratioB ); - this._z = ( z * ratioA + this._z * ratioB ); + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; - this.onChangeCallback(); + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; - return this; + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; - }, + } else if ( euler.order === 'YXZ' ) { - equals: function ( quaternion ) { + var ce = c * e, cf = c * f, de = d * e, df = d * f; - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - }, + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; - fromArray: function ( array, offset ) { + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; - if ( offset === undefined ) offset = 0; + } else if ( euler.order === 'ZXY' ) { - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; + var ce = c * e, cf = c * f, de = d * e, df = d * f; - this.onChangeCallback(); + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - return this; + te[ 1 ] = cf + de * b; + te[ 5 ] = a * e; + te[ 9 ] = df - ce * b; - }, + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; - toArray: function ( array, offset ) { + } else if ( euler.order === 'ZYX' ) { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + var ae = a * e, af = a * f, be = b * e, bf = b * f; - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - return array; + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - }, + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; - onChange: function ( callback ) { + } else if ( euler.order === 'YZX' ) { - this.onChangeCallback = callback; + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - return this; + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - }, + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; - onChangeCallback: function () {} + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; -}; + } else if ( euler.order === 'XZY' ) { -Object.assign( THREE.Quaternion, { + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - slerp: function( qa, qb, qm, t ) { + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - return qm.copy( qa ).slerp( qb, t ); + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; - }, + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - slerpFlat: function( - dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + } - // fuzz-free, array-based Quaternion SLERP operation + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - var x0 = src0[ srcOffset0 + 0 ], - y0 = src0[ srcOffset0 + 1 ], - z0 = src0[ srcOffset0 + 2 ], - w0 = src0[ srcOffset0 + 3 ], + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - x1 = src1[ srcOffset1 + 0 ], - y1 = src1[ srcOffset1 + 1 ], - z1 = src1[ srcOffset1 + 2 ], - w1 = src1[ srcOffset1 + 3 ]; + return this; - if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + }, - var s = 1 - t, + makeRotationFromQuaternion: function ( q ) { - cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, + var te = this.elements; - dir = ( cos >= 0 ? 1 : - 1 ), - sqrSin = 1 - cos * cos; + var x = q.x, y = q.y, z = q.z, w = q.w; + var x2 = x + x, y2 = y + y, z2 = z + z; + var xx = x * x2, xy = x * y2, xz = x * z2; + var yy = y * y2, yz = y * z2, zz = z * z2; + var wx = w * x2, wy = w * y2, wz = w * z2; - // Skip the Slerp for tiny steps to avoid numeric problems: - if ( sqrSin > Number.EPSILON ) { + te[ 0 ] = 1 - ( yy + zz ); + te[ 4 ] = xy - wz; + te[ 8 ] = xz + wy; - var sin = Math.sqrt( sqrSin ), - len = Math.atan2( sin, cos * dir ); + te[ 1 ] = xy + wz; + te[ 5 ] = 1 - ( xx + zz ); + te[ 9 ] = yz - wx; - s = Math.sin( s * len ) / sin; - t = Math.sin( t * len ) / sin; + te[ 2 ] = xz - wy; + te[ 6 ] = yz + wx; + te[ 10 ] = 1 - ( xx + yy ); - } + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - var tDir = t * dir; + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; + return this; - // Normalize in case we just did a lerp: - if ( s === 1 - t ) { + }, - var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + lookAt: function () { - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; + var x, y, z; - } + return function lookAt( eye, target, up ) { - } + if ( x === undefined ) { - dst[ dstOffset ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; + x = new Vector3(); + y = new Vector3(); + z = new Vector3(); - } + } -} ); + var te = this.elements; -// File:src/math/Vector2.js + z.subVectors( eye, target ).normalize(); -/** - * @author mrdoob / http://mrdoob.com/ - * @author philogb / http://blog.thejit.org/ - * @author egraether / http://egraether.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + if ( z.lengthSq() === 0 ) { -THREE.Vector2 = function ( x, y ) { + z.z = 1; - this.x = x || 0; - this.y = y || 0; + } -}; + x.crossVectors( up, z ).normalize(); -THREE.Vector2.prototype = { + if ( x.lengthSq() === 0 ) { - constructor: THREE.Vector2, + z.z += 0.0001; + x.crossVectors( up, z ).normalize(); - get width() { + } - return this.x; + y.crossVectors( z, x ); - }, - set width( value ) { + te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x; + te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y; + te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z; - this.x = value; + return this; - }, + }; - get height() { + }(), - return this.y; + multiply: function ( m, n ) { - }, + if ( n !== undefined ) { - set height( value ) { + console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); + return this.multiplyMatrices( m, n ); - this.y = value; + } - }, + return this.multiplyMatrices( this, m ); - // + }, - set: function ( x, y ) { + premultiply: function ( m ) { - this.x = x; - this.y = y; + return this.multiplyMatrices( m, this ); - return this; + }, - }, + multiplyMatrices: function ( a, b ) { - setScalar: function ( scalar ) { + var ae = a.elements; + var be = b.elements; + var te = this.elements; - this.x = scalar; - this.y = scalar; + var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - return this; + var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - }, + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - setX: function ( x ) { + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - this.x = x; + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - return this; + te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; - }, + return this; - setY: function ( y ) { + }, - this.y = y; + multiplyToArray: function ( a, b, r ) { - return this; + var te = this.elements; - }, + this.multiplyMatrices( a, b ); - setComponent: function ( index, value ) { + r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ]; + r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ]; + r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ]; + r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ]; - switch ( index ) { + return this; - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( 'index is out of range: ' + index ); + }, - } + multiplyScalar: function ( s ) { - }, + var te = this.elements; - getComponent: function ( index ) { + te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; + te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; + te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; + te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; - switch ( index ) { + return this; - case 0: return this.x; - case 1: return this.y; - default: throw new Error( 'index is out of range: ' + index ); + }, - } + applyToVector3Array: function () { - }, + var v1; - clone: function () { + return function applyToVector3Array( array, offset, length ) { - return new this.constructor( this.x, this.y ); + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - }, + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - copy: function ( v ) { + v1.fromArray( array, j ); + v1.applyMatrix4( this ); + v1.toArray( array, j ); - this.x = v.x; - this.y = v.y; + } - return this; + return array; - }, + }; - add: function ( v, w ) { + }(), - if ( w !== undefined ) { + applyToBuffer: function () { - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + var v1; - } + return function applyToBuffer( buffer, offset, length ) { - this.x += v.x; - this.y += v.y; + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = buffer.length / buffer.itemSize; - return this; + for ( var i = 0, j = offset; i < length; i ++, j ++ ) { - }, + v1.x = buffer.getX( j ); + v1.y = buffer.getY( j ); + v1.z = buffer.getZ( j ); - addScalar: function ( s ) { + v1.applyMatrix4( this ); - this.x += s; - this.y += s; + buffer.setXYZ( v1.x, v1.y, v1.z ); - return this; + } - }, + return buffer; - addVectors: function ( a, b ) { + }; - this.x = a.x + b.x; - this.y = a.y + b.y; + }(), - return this; + determinant: function () { - }, + var te = this.elements; - addScaledVector: function ( v, s ) { + var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - this.x += v.x * s; - this.y += v.y * s; + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - return this; + return ( + n41 * ( + + n14 * n23 * n32 + - n13 * n24 * n32 + - n14 * n22 * n33 + + n12 * n24 * n33 + + n13 * n22 * n34 + - n12 * n23 * n34 + ) + + n42 * ( + + n11 * n23 * n34 + - n11 * n24 * n33 + + n14 * n21 * n33 + - n13 * n21 * n34 + + n13 * n24 * n31 + - n14 * n23 * n31 + ) + + n43 * ( + + n11 * n24 * n32 + - n11 * n22 * n34 + - n14 * n21 * n32 + + n12 * n21 * n34 + + n14 * n22 * n31 + - n12 * n24 * n31 + ) + + n44 * ( + - n13 * n22 * n31 + - n11 * n23 * n32 + + n11 * n22 * n33 + + n13 * n21 * n32 + - n12 * n21 * n33 + + n12 * n23 * n31 + ) - }, + ); - sub: function ( v, w ) { + }, - if ( w !== undefined ) { + transpose: function () { - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + var te = this.elements; + var tmp; - } + tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; + tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; + tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; - this.x -= v.x; - this.y -= v.y; + tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; + tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; + tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; - return this; + return this; - }, + }, - subScalar: function ( s ) { + flattenToArrayOffset: function ( array, offset ) { - this.x -= s; - this.y -= s; + console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + + "- just use .toArray instead." ); - return this; + return this.toArray( array, offset ); - }, + }, - subVectors: function ( a, b ) { + getPosition: function () { - this.x = a.x - b.x; - this.y = a.y - b.y; + var v1; - return this; + return function getPosition() { - }, + if ( v1 === undefined ) v1 = new Vector3(); + console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - multiply: function ( v ) { + return v1.setFromMatrixColumn( this, 3 ); - this.x *= v.x; - this.y *= v.y; + }; - return this; + }(), - }, + setPosition: function ( v ) { - multiplyScalar: function ( scalar ) { + var te = this.elements; - if ( isFinite( scalar ) ) { + te[ 12 ] = v.x; + te[ 13 ] = v.y; + te[ 14 ] = v.z; - this.x *= scalar; - this.y *= scalar; + return this; - } else { + }, - this.x = 0; - this.y = 0; + getInverse: function ( m, throwOnDegenerate ) { - } + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + var te = this.elements, + me = m.elements, - return this; + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], + n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], + n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], + n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], - }, + t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, + t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, + t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, + t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - divide: function ( v ) { + var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - this.x /= v.x; - this.y /= v.y; + if ( det === 0 ) { - return this; + var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; - }, + if ( throwOnDegenerate || false ) {} else { - divideScalar: function ( scalar ) { + console.warn( msg ); - return this.multiplyScalar( 1 / scalar ); + } - }, + return this.identity(); - min: function ( v ) { + } + + var detInv = 1 / det; - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; + te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; + te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; - return this; + te[ 4 ] = t12 * detInv; + te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; + te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; + te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; - }, + te[ 8 ] = t13 * detInv; + te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; + te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; + te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; - max: function ( v ) { + te[ 12 ] = t14 * detInv; + te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; + te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; + te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); + return this; - return this; + }, - }, + scale: function ( v ) { - clamp: function ( min, max ) { + var te = this.elements; + var x = v.x, y = v.y, z = v.z; - // This function assumes min < max, if this assumption isn't true it will not operate correctly + te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; + te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; + te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; + te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + return this; - return this; + }, - }, + getMaxScaleOnAxis: function () { - clampScalar: function () { + var te = this.elements; - var min, max; + var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; - return function clampScalar( minVal, maxVal ) { + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - if ( min === undefined ) { + }, - min = new THREE.Vector2(); - max = new THREE.Vector2(); + makeTranslation: function ( x, y, z ) { - } + this.set( - min.set( minVal, minVal ); - max.set( maxVal, maxVal ); + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 - return this.clamp( min, max ); + ); - }; + return this; - }(), + }, - clampLength: function ( min, max ) { + makeRotationX: function ( theta ) { - var length = this.length(); + var c = Math.cos( theta ), s = Math.sin( theta ); - return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); + this.set( - }, + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 - floor: function () { + ); - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); + return this; - return this; + }, - }, + makeRotationY: function ( theta ) { - ceil: function () { + var c = Math.cos( theta ), s = Math.sin( theta ); - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); + this.set( - return this; + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 - }, + ); - round: function () { + return this; - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); + }, - return this; + makeRotationZ: function ( theta ) { - }, + var c = Math.cos( theta ), s = Math.sin( theta ); - roundToZero: function () { + this.set( - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - return this; + ); - }, + return this; - negate: function () { + }, - this.x = - this.x; - this.y = - this.y; + makeRotationAxis: function ( axis, angle ) { - return this; + // Based on http://www.gamedev.net/reference/articles/article1199.asp - }, + var c = Math.cos( angle ); + var s = Math.sin( angle ); + var t = 1 - c; + var x = axis.x, y = axis.y, z = axis.z; + var tx = t * x, ty = t * y; - dot: function ( v ) { + this.set( - return this.x * v.x + this.y * v.y; + tx * x + c, tx * y - s * z, tx * z + s * y, 0, + tx * y + s * z, ty * y + c, ty * z - s * x, 0, + tx * z - s * y, ty * z + s * x, t * z * z + c, 0, + 0, 0, 0, 1 - }, + ); - lengthSq: function () { + return this; - return this.x * this.x + this.y * this.y; + }, - }, + makeScale: function ( x, y, z ) { - length: function () { + this.set( - return Math.sqrt( this.x * this.x + this.y * this.y ); + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 - }, + ); - lengthManhattan: function() { + return this; - return Math.abs( this.x ) + Math.abs( this.y ); + }, - }, + compose: function ( position, quaternion, scale ) { - normalize: function () { + this.makeRotationFromQuaternion( quaternion ); + this.scale( scale ); + this.setPosition( position ); - return this.divideScalar( this.length() ); + return this; - }, + }, - angle: function () { + decompose: function () { - // computes the angle in radians with respect to the positive x-axis + var vector, matrix; - var angle = Math.atan2( this.y, this.x ); + return function decompose( position, quaternion, scale ) { - if ( angle < 0 ) angle += 2 * Math.PI; + if ( vector === undefined ) { - return angle; + vector = new Vector3(); + matrix = new Matrix4(); - }, + } - distanceTo: function ( v ) { + var te = this.elements; - return Math.sqrt( this.distanceToSquared( v ) ); + var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - }, + // if determine is negative, we need to invert one scale + var det = this.determinant(); + if ( det < 0 ) { - distanceToSquared: function ( v ) { + sx = - sx; - var dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; + } - }, + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; - distanceToManhattan: function ( v ) { + // scale the rotation part - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); + matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() - }, + var invSX = 1 / sx; + var invSY = 1 / sy; + var invSZ = 1 / sz; - setLength: function ( length ) { + matrix.elements[ 0 ] *= invSX; + matrix.elements[ 1 ] *= invSX; + matrix.elements[ 2 ] *= invSX; - return this.multiplyScalar( length / this.length() ); + matrix.elements[ 4 ] *= invSY; + matrix.elements[ 5 ] *= invSY; + matrix.elements[ 6 ] *= invSY; - }, + matrix.elements[ 8 ] *= invSZ; + matrix.elements[ 9 ] *= invSZ; + matrix.elements[ 10 ] *= invSZ; - lerp: function ( v, alpha ) { + quaternion.setFromRotationMatrix( matrix ); - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; + scale.x = sx; + scale.y = sy; + scale.z = sz; - return this; + return this; - }, + }; - lerpVectors: function ( v1, v2, alpha ) { + }(), - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + makeFrustum: function ( left, right, bottom, top, near, far ) { - }, + var te = this.elements; + var x = 2 * near / ( right - left ); + var y = 2 * near / ( top - bottom ); - equals: function ( v ) { + var a = ( right + left ) / ( right - left ); + var b = ( top + bottom ) / ( top - bottom ); + var c = - ( far + near ) / ( far - near ); + var d = - 2 * far * near / ( far - near ); - return ( ( v.x === this.x ) && ( v.y === this.y ) ); + te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; + te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; - }, + return this; - fromArray: function ( array, offset ) { + }, - if ( offset === undefined ) offset = 0; + makePerspective: function ( fov, aspect, near, far ) { - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; + var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); + var ymin = - ymax; + var xmin = ymin * aspect; + var xmax = ymax * aspect; - return this; + return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); - }, + }, - toArray: function ( array, offset ) { + makeOrthographic: function ( left, right, top, bottom, near, far ) { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + var te = this.elements; + var w = 1.0 / ( right - left ); + var h = 1.0 / ( top - bottom ); + var p = 1.0 / ( far - near ); - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; + var x = ( right + left ) * w; + var y = ( top + bottom ) * h; + var z = ( far + near ) * p; - return array; + te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; + te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; - }, + return this; - fromAttribute: function ( attribute, index, offset ) { + }, - if ( offset === undefined ) offset = 0; + equals: function ( matrix ) { - index = index * attribute.itemSize + offset; + var te = this.elements; + var me = matrix.elements; - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; + for ( var i = 0; i < 16; i ++ ) { - return this; + if ( te[ i ] !== me[ i ] ) return false; - }, + } - rotateAround: function ( center, angle ) { + return true; - var c = Math.cos( angle ), s = Math.sin( angle ); + }, - var x = this.x - center.x; - var y = this.y - center.y; + fromArray: function ( array ) { - this.x = x * c - y * s + center.x; - this.y = x * s + y * c + center.y; + this.elements.set( array ); - return this; + return this; - } + }, -}; + toArray: function ( array, offset ) { -// File:src/math/Vector3.js + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; -/** - * @author mrdoob / http://mrdoob.com/ - * @author *kile / http://kile.stravaganza.org/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ + var te = this.elements; -THREE.Vector3 = function ( x, y, z ) { + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; -}; + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; -THREE.Vector3.prototype = { + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; - constructor: THREE.Vector3, + return array; - set: function ( x, y, z ) { + } - this.x = x; - this.y = y; - this.z = z; + }; - return this; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - }, + function Quaternion ( x, y, z, w ) { + this.isQuaternion = true; - setScalar: function ( scalar ) { + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._w = ( w !== undefined ) ? w : 1; - this.x = scalar; - this.y = scalar; - this.z = scalar; + }; - return this; + Quaternion.prototype = { - }, + constructor: Quaternion, - setX: function ( x ) { + get x () { - this.x = x; + return this._x; - return this; + }, - }, + set x ( value ) { - setY: function ( y ) { + this._x = value; + this.onChangeCallback(); - this.y = y; + }, - return this; + get y () { - }, + return this._y; - setZ: function ( z ) { + }, - this.z = z; + set y ( value ) { - return this; + this._y = value; + this.onChangeCallback(); - }, + }, - setComponent: function ( index, value ) { + get z () { - switch ( index ) { + return this._z; - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - default: throw new Error( 'index is out of range: ' + index ); + }, - } + set z ( value ) { - }, + this._z = value; + this.onChangeCallback(); - getComponent: function ( index ) { + }, - switch ( index ) { + get w () { - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - default: throw new Error( 'index is out of range: ' + index ); + return this._w; - } + }, - }, + set w ( value ) { - clone: function () { + this._w = value; + this.onChangeCallback(); - return new this.constructor( this.x, this.y, this.z ); + }, - }, + set: function ( x, y, z, w ) { - copy: function ( v ) { + this._x = x; + this._y = y; + this._z = z; + this._w = w; - this.x = v.x; - this.y = v.y; - this.z = v.z; + this.onChangeCallback(); - return this; + return this; - }, + }, - add: function ( v, w ) { + clone: function () { - if ( w !== undefined ) { + return new this.constructor( this._x, this._y, this._z, this._w ); - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + }, - } + copy: function ( quaternion ) { - this.x += v.x; - this.y += v.y; - this.z += v.z; + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; - return this; + this.onChangeCallback(); - }, + return this; - addScalar: function ( s ) { + }, - this.x += s; - this.y += s; - this.z += s; + setFromEuler: function ( euler, update ) { - return this; + if ( (euler && euler.isEuler) === false ) { - }, + throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - addVectors: function ( a, b ) { + } - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m - return this; + var c1 = Math.cos( euler._x / 2 ); + var c2 = Math.cos( euler._y / 2 ); + var c3 = Math.cos( euler._z / 2 ); + var s1 = Math.sin( euler._x / 2 ); + var s2 = Math.sin( euler._y / 2 ); + var s3 = Math.sin( euler._z / 2 ); - }, + var order = euler.order; - addScaledVector: function ( v, s ) { + if ( order === 'XYZ' ) { - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; - return this; + } else if ( order === 'YXZ' ) { - }, + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; - sub: function ( v, w ) { + } else if ( order === 'ZXY' ) { - if ( w !== undefined ) { + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + } else if ( order === 'ZYX' ) { - } + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; + } else if ( order === 'YZX' ) { - return this; + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; - }, + } else if ( order === 'XZY' ) { - subScalar: function ( s ) { + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; - this.x -= s; - this.y -= s; - this.z -= s; + } - return this; + if ( update !== false ) this.onChangeCallback(); - }, + return this; - subVectors: function ( a, b ) { + }, - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; + setFromAxisAngle: function ( axis, angle ) { - return this; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - }, + // assumes axis is normalized - multiply: function ( v, w ) { + var halfAngle = angle / 2, s = Math.sin( halfAngle ); - if ( w !== undefined ) { + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); + this.onChangeCallback(); - } + return this; - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; + }, - return this; + setFromRotationMatrix: function ( m ) { - }, + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - multiplyScalar: function ( scalar ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - if ( isFinite( scalar ) ) { + var te = m.elements, - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], - } else { + trace = m11 + m22 + m33, + s; - this.x = 0; - this.y = 0; - this.z = 0; + if ( trace > 0 ) { - } + s = 0.5 / Math.sqrt( trace + 1.0 ); - return this; + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; - }, + } else if ( m11 > m22 && m11 > m33 ) { - multiplyVectors: function ( a, b ) { + s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; - return this; + } else if ( m22 > m33 ) { - }, + s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - applyEuler: function () { + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; - var quaternion; + } else { - return function applyEuler( euler ) { + s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - if ( euler instanceof THREE.Euler === false ) { + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; - console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); + } - } + this.onChangeCallback(); - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + return this; - return this.applyQuaternion( quaternion.setFromEuler( euler ) ); + }, - }; + setFromUnitVectors: function () { - }(), + // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final - applyAxisAngle: function () { + // assumes direction vectors vFrom and vTo are normalized - var quaternion; + var v1, r; - return function applyAxisAngle( axis, angle ) { + var EPS = 0.000001; - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + return function setFromUnitVectors( vFrom, vTo ) { - return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); + if ( v1 === undefined ) v1 = new Vector3(); - }; + r = vFrom.dot( vTo ) + 1; - }(), + if ( r < EPS ) { - applyMatrix3: function ( m ) { + r = 0; - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; - this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; + v1.set( - vFrom.y, vFrom.x, 0 ); - return this; + } else { - }, + v1.set( 0, - vFrom.z, vFrom.y ); - applyMatrix4: function ( m ) { + } - // input: THREE.Matrix4 affine matrix + } else { - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + v1.crossVectors( vFrom, vTo ); - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; + } - return this; + this._x = v1.x; + this._y = v1.y; + this._z = v1.z; + this._w = r; - }, + return this.normalize(); - applyProjection: function ( m ) { + }; - // input: THREE.Matrix4 projection matrix + }(), - var x = this.x, y = this.y, z = this.z; - var e = m.elements; - var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide + inverse: function () { - this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d; - this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d; - this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d; + return this.conjugate().normalize(); - return this; + }, - }, + conjugate: function () { - applyQuaternion: function ( q ) { + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; - var x = this.x, y = this.y, z = this.z; - var qx = q.x, qy = q.y, qz = q.z, qw = q.w; + this.onChangeCallback(); - // calculate quat * vector + return this; - var ix = qw * x + qy * z - qz * y; - var iy = qw * y + qz * x - qx * z; - var iz = qw * z + qx * y - qy * x; - var iw = - qx * x - qy * y - qz * z; + }, - // calculate result * inverse quat + dot: function ( v ) { - this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; - this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; - this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - return this; + }, - }, + lengthSq: function () { - project: function () { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - var matrix; + }, - return function project( camera ) { + length: function () { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); - matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); - return this.applyProjection( matrix ); + }, - }; + normalize: function () { - }(), + var l = this.length(); - unproject: function () { + if ( l === 0 ) { - var matrix; + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; - return function unproject( camera ) { + } else { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + l = 1 / l; - matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); - return this.applyProjection( matrix ); + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; - }; + } - }(), + this.onChangeCallback(); - transformDirection: function ( m ) { + return this; - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction + }, - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + multiply: function ( q, p ) { - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; + if ( p !== undefined ) { - return this.normalize(); + console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); + return this.multiplyQuaternions( q, p ); - }, + } - divide: function ( v ) { + return this.multiplyQuaternions( this, q ); - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; + }, - return this; + premultiply: function ( q ) { - }, + return this.multiplyQuaternions( q, this ); - divideScalar: function ( scalar ) { + }, - return this.multiplyScalar( 1 / scalar ); + multiplyQuaternions: function ( a, b ) { - }, + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - min: function ( v ) { + var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; - return this; + this.onChangeCallback(); - }, + return this; - max: function ( v ) { + }, - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); + slerp: function ( qb, t ) { - return this; + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); - }, + var x = this._x, y = this._y, z = this._z, w = this._w; - clamp: function ( min, max ) { + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - // This function assumes min < max, if this assumption isn't true it will not operate correctly + var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + if ( cosHalfTheta < 0 ) { - return this; + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; - }, + cosHalfTheta = - cosHalfTheta; - clampScalar: function () { + } else { - var min, max; + this.copy( qb ); - return function clampScalar( minVal, maxVal ) { + } - if ( min === undefined ) { + if ( cosHalfTheta >= 1.0 ) { - min = new THREE.Vector3(); - max = new THREE.Vector3(); + this._w = w; + this._x = x; + this._y = y; + this._z = z; - } + return this; - min.set( minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal ); + } - return this.clamp( min, max ); + var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); - }; + if ( Math.abs( sinHalfTheta ) < 0.001 ) { - }(), + this._w = 0.5 * ( w + this._w ); + this._x = 0.5 * ( x + this._x ); + this._y = 0.5 * ( y + this._y ); + this._z = 0.5 * ( z + this._z ); - clampLength: function ( min, max ) { + return this; - var length = this.length(); + } - return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); + var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - }, + this._w = ( w * ratioA + this._w * ratioB ); + this._x = ( x * ratioA + this._x * ratioB ); + this._y = ( y * ratioA + this._y * ratioB ); + this._z = ( z * ratioA + this._z * ratioB ); - floor: function () { + this.onChangeCallback(); - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); + return this; - return this; + }, - }, + equals: function ( quaternion ) { - ceil: function () { + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); + }, - return this; + fromArray: function ( array, offset ) { - }, + if ( offset === undefined ) offset = 0; - round: function () { + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); + this.onChangeCallback(); - return this; + return this; - }, + }, - roundToZero: function () { + toArray: function ( array, offset ) { - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return this; + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; - }, + return array; - negate: function () { + }, - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; + onChange: function ( callback ) { - return this; + this.onChangeCallback = callback; - }, + return this; - dot: function ( v ) { + }, - return this.x * v.x + this.y * v.y + this.z * v.z; + onChangeCallback: function () {} - }, + }; - lengthSq: function () { + Object.assign( Quaternion, { - return this.x * this.x + this.y * this.y + this.z * this.z; + slerp: function( qa, qb, qm, t ) { - }, + return qm.copy( qa ).slerp( qb, t ); - length: function () { + }, - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + slerpFlat: function( + dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - }, + // fuzz-free, array-based Quaternion SLERP operation - lengthManhattan: function () { + var x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ], - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; - }, + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - normalize: function () { + var s = 1 - t, - return this.divideScalar( this.length() ); + cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - }, + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; - setLength: function ( length ) { + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { - return this.multiplyScalar( length / this.length() ); + var sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); - }, + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; - lerp: function ( v, alpha ) { + } - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; + var tDir = t * dir; - return this; + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; - }, + // Normalize in case we just did a lerp: + if ( s === 1 - t ) { - lerpVectors: function ( v1, v2, alpha ) { + var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; - }, + } - cross: function ( v, w ) { + } - if ( w !== undefined ) { + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); + } - } + } ); - var x = this.x, y = this.y, z = this.z; + /** + * @author mrdoob / http://mrdoob.com/ + * @author *kile / http://kile.stravaganza.org/ + * @author philogb / http://blog.thejit.org/ + * @author mikael emtinger / http://gomo.se/ + * @author egraether / http://egraether.com/ + * @author WestLangley / http://github.com/WestLangley + */ - this.x = y * v.z - z * v.y; - this.y = z * v.x - x * v.z; - this.z = x * v.y - y * v.x; + function Vector3 ( x, y, z ) { + this.isVector3 = true; - return this; + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; - }, + }; - crossVectors: function ( a, b ) { + Vector3.prototype = { - var ax = a.x, ay = a.y, az = a.z; - var bx = b.x, by = b.y, bz = b.z; + constructor: Vector3, - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; + set: function ( x, y, z ) { - return this; + this.x = x; + this.y = y; + this.z = z; - }, + return this; - projectOnVector: function ( vector ) { + }, - var scalar = vector.dot( this ) / vector.lengthSq(); - - return this.copy( vector ).multiplyScalar( scalar ); - - }, + setScalar: function ( scalar ) { - projectOnPlane: function () { + this.x = scalar; + this.y = scalar; + this.z = scalar; - var v1; + return this; - return function projectOnPlane( planeNormal ) { + }, - if ( v1 === undefined ) v1 = new THREE.Vector3(); + setX: function ( x ) { - v1.copy( this ).projectOnVector( planeNormal ); + this.x = x; - return this.sub( v1 ); + return this; - }; + }, - }(), + setY: function ( y ) { - reflect: function () { + this.y = y; - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length + return this; - var v1; + }, - return function reflect( normal ) { + setZ: function ( z ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + this.z = z; - return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + return this; - }; + }, - }(), + setComponent: function ( index, value ) { - angleTo: function ( v ) { + switch ( index ) { - var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) ); + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + default: throw new Error( 'index is out of range: ' + index ); - // clamp, to handle numerical problems + } - return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); + }, - }, + getComponent: function ( index ) { - distanceTo: function ( v ) { + switch ( index ) { - return Math.sqrt( this.distanceToSquared( v ) ); + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + default: throw new Error( 'index is out of range: ' + index ); - }, + } - distanceToSquared: function ( v ) { + }, - var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + clone: function () { - return dx * dx + dy * dy + dz * dz; + return new this.constructor( this.x, this.y, this.z ); - }, + }, - distanceToManhattan: function ( v ) { + copy: function ( v ) { - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + this.x = v.x; + this.y = v.y; + this.z = v.z; - }, + return this; - setFromSpherical: function( s ) { + }, - var sinPhiRadius = Math.sin( s.phi ) * s.radius; + add: function ( v, w ) { - this.x = sinPhiRadius * Math.sin( s.theta ); - this.y = Math.cos( s.phi ) * s.radius; - this.z = sinPhiRadius * Math.cos( s.theta ); + if ( w !== undefined ) { - return this; + console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - }, + } - setFromMatrixPosition: function ( m ) { + this.x += v.x; + this.y += v.y; + this.z += v.z; - return this.setFromMatrixColumn( m, 3 ); + return this; - }, + }, - setFromMatrixScale: function ( m ) { + addScalar: function ( s ) { - var sx = this.setFromMatrixColumn( m, 0 ).length(); - var sy = this.setFromMatrixColumn( m, 1 ).length(); - var sz = this.setFromMatrixColumn( m, 2 ).length(); + this.x += s; + this.y += s; + this.z += s; - this.x = sx; - this.y = sy; - this.z = sz; + return this; - return this; + }, - }, + addVectors: function ( a, b ) { - setFromMatrixColumn: function ( m, index ) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; - if ( typeof m === 'number' ) { + return this; - console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' ); - var temp = m - m = index; - index = temp; + }, - } + addScaledVector: function ( v, s ) { - return this.fromArray( m.elements, index * 4 ); + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; - }, + return this; - equals: function ( v ) { + }, - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + sub: function ( v, w ) { - }, + if ( w !== undefined ) { - fromArray: function ( array, offset ) { + console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - if ( offset === undefined ) offset = 0; + } - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; - return this; + return this; - }, + }, - toArray: function ( array, offset ) { + subScalar: function ( s ) { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + this.x -= s; + this.y -= s; + this.z -= s; - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; + return this; - return array; + }, - }, + subVectors: function ( a, b ) { - fromAttribute: function ( attribute, index, offset ) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; - if ( offset === undefined ) offset = 0; + return this; - index = index * attribute.itemSize + offset; + }, - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; + multiply: function ( v, w ) { - return this; + if ( w !== undefined ) { - } + console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); + return this.multiplyVectors( v, w ); -}; + } -// File:src/math/Vector4.js + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; -/** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ + return this; -THREE.Vector4 = function ( x, y, z, w ) { + }, - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = ( w !== undefined ) ? w : 1; + multiplyScalar: function ( scalar ) { -}; + if ( isFinite( scalar ) ) { -THREE.Vector4.prototype = { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; - constructor: THREE.Vector4, + } else { - set: function ( x, y, z, w ) { + this.x = 0; + this.y = 0; + this.z = 0; - this.x = x; - this.y = y; - this.z = z; - this.w = w; + } - return this; + return this; - }, + }, - setScalar: function ( scalar ) { + multiplyVectors: function ( a, b ) { - this.x = scalar; - this.y = scalar; - this.z = scalar; - this.w = scalar; + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; - return this; + return this; - }, + }, - setX: function ( x ) { + applyEuler: function () { - this.x = x; + var quaternion; - return this; + return function applyEuler( euler ) { - }, + if ( (euler && euler.isEuler) === false ) { - setY: function ( y ) { + console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - this.y = y; + } - return this; + if ( quaternion === undefined ) quaternion = new Quaternion(); - }, + return this.applyQuaternion( quaternion.setFromEuler( euler ) ); - setZ: function ( z ) { + }; - this.z = z; + }(), - return this; + applyAxisAngle: function () { - }, + var quaternion; - setW: function ( w ) { + return function applyAxisAngle( axis, angle ) { - this.w = w; + if ( quaternion === undefined ) quaternion = new Quaternion(); - return this; + return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); - }, + }; - setComponent: function ( index, value ) { + }(), - switch ( index ) { + applyMatrix3: function ( m ) { - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - case 3: this.w = value; break; - default: throw new Error( 'index is out of range: ' + index ); + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - } + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; + this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; - }, + return this; - getComponent: function ( index ) { + }, - switch ( index ) { + applyMatrix4: function ( m ) { - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - case 3: return this.w; - default: throw new Error( 'index is out of range: ' + index ); + // input: THREE.Matrix4 affine matrix - } + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - }, + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; - clone: function () { + return this; - return new this.constructor( this.x, this.y, this.z, this.w ); + }, - }, + applyProjection: function ( m ) { - copy: function ( v ) { + // input: THREE.Matrix4 projection matrix - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; + var x = this.x, y = this.y, z = this.z; + var e = m.elements; + var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide - return this; + this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d; + this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d; + this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d; - }, + return this; - add: function ( v, w ) { + }, - if ( w !== undefined ) { + applyQuaternion: function ( q ) { - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + var x = this.x, y = this.y, z = this.z; + var qx = q.x, qy = q.y, qz = q.z, qw = q.w; - } + // calculate quat * vector - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = - qx * x - qy * y - qz * z; - return this; + // calculate result * inverse quat - }, + this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; + this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; + this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; - addScalar: function ( s ) { + return this; - this.x += s; - this.y += s; - this.z += s; - this.w += s; + }, - return this; + project: function () { - }, + var matrix; - addVectors: function ( a, b ) { + return function project( camera ) { - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; + if ( matrix === undefined ) matrix = new Matrix4(); - return this; + matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); + return this.applyProjection( matrix ); - }, + }; - addScaledVector: function ( v, s ) { + }(), - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; + unproject: function () { - return this; + var matrix; - }, + return function unproject( camera ) { - sub: function ( v, w ) { + if ( matrix === undefined ) matrix = new Matrix4(); - if ( w !== undefined ) { + matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); + return this.applyProjection( matrix ); - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + }; - } + }(), - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; + transformDirection: function ( m ) { - return this; + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction - }, + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - subScalar: function ( s ) { + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; + return this.normalize(); - return this; + }, - }, + divide: function ( v ) { - subVectors: function ( a, b ) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; + return this; - return this; + }, - }, + divideScalar: function ( scalar ) { - multiplyScalar: function ( scalar ) { + return this.multiplyScalar( 1 / scalar ); - if ( isFinite( scalar ) ) { + }, - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; + min: function ( v ) { - } else { + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 0; + return this; - } + }, - return this; + max: function ( v ) { - }, + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); - applyMatrix4: function ( m ) { + return this; - var x = this.x, y = this.y, z = this.z, w = this.w; - var e = m.elements; + }, - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; - this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; + clamp: function ( min, max ) { - return this; + // This function assumes min < max, if this assumption isn't true it will not operate correctly - }, + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - divideScalar: function ( scalar ) { + return this; - return this.multiplyScalar( 1 / scalar ); + }, - }, + clampScalar: function () { - setAxisAngleFromQuaternion: function ( q ) { + var min, max; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + return function clampScalar( minVal, maxVal ) { - // q is assumed to be normalized + if ( min === undefined ) { - this.w = 2 * Math.acos( q.w ); + min = new Vector3(); + max = new Vector3(); - var s = Math.sqrt( 1 - q.w * q.w ); + } - if ( s < 0.0001 ) { + min.set( minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal ); - this.x = 1; - this.y = 0; - this.z = 0; + return this.clamp( min, max ); - } else { + }; - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; + }(), - } + clampLength: function ( min, max ) { - return this; + var length = this.length(); - }, + return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); - setAxisAngleFromRotationMatrix: function ( m ) { + }, - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + floor: function () { - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); - var angle, x, y, z, // variables for result - epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees + return this; - te = m.elements, + }, - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + ceil: function () { - if ( ( Math.abs( m12 - m21 ) < epsilon ) && - ( Math.abs( m13 - m31 ) < epsilon ) && - ( Math.abs( m23 - m32 ) < epsilon ) ) { + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms + return this; - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && - ( Math.abs( m13 + m31 ) < epsilon2 ) && - ( Math.abs( m23 + m32 ) < epsilon2 ) && - ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + }, - // this singularity is identity matrix so angle = 0 + round: function () { - this.set( 1, 0, 0, 0 ); + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); - return this; // zero angle, arbitrary axis + return this; - } + }, - // otherwise this singularity is angle = 180 + roundToZero: function () { - angle = Math.PI; + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - var xx = ( m11 + 1 ) / 2; - var yy = ( m22 + 1 ) / 2; - var zz = ( m33 + 1 ) / 2; - var xy = ( m12 + m21 ) / 4; - var xz = ( m13 + m31 ) / 4; - var yz = ( m23 + m32 ) / 4; + return this; - if ( ( xx > yy ) && ( xx > zz ) ) { + }, - // m11 is the largest diagonal term + negate: function () { - if ( xx < epsilon ) { + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; - x = 0; - y = 0.707106781; - z = 0.707106781; + return this; - } else { + }, - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; + dot: function ( v ) { - } + return this.x * v.x + this.y * v.y + this.z * v.z; - } else if ( yy > zz ) { + }, - // m22 is the largest diagonal term + lengthSq: function () { - if ( yy < epsilon ) { + return this.x * this.x + this.y * this.y + this.z * this.z; - x = 0.707106781; - y = 0; - z = 0.707106781; + }, - } else { + length: function () { - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - } + }, - } else { + lengthManhattan: function () { - // m33 is the largest diagonal term so base result on this + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - if ( zz < epsilon ) { + }, - x = 0.707106781; - y = 0.707106781; - z = 0; + normalize: function () { - } else { + return this.divideScalar( this.length() ); - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; + }, - } + setLength: function ( length ) { - } + return this.multiplyScalar( length / this.length() ); - this.set( x, y, z, angle ); + }, - return this; // return 180 deg rotation + lerp: function ( v, alpha ) { - } + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; - // as we have reached here there are no singularities so we can handle normally + return this; - var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + - ( m13 - m31 ) * ( m13 - m31 ) + - ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize + }, - if ( Math.abs( s ) < 0.001 ) s = 1; + lerpVectors: function ( v1, v2, alpha ) { - // prevent divide by zero, should not happen if matrix is orthogonal and should be - // caught by singularity test above, but I've left it in just in case + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + }, - return this; + cross: function ( v, w ) { - }, + if ( w !== undefined ) { - min: function ( v ) { + console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); + return this.crossVectors( v, w ); - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); - this.w = Math.min( this.w, v.w ); + } - return this; + var x = this.x, y = this.y, z = this.z; - }, + this.x = y * v.z - z * v.y; + this.y = z * v.x - x * v.z; + this.z = x * v.y - y * v.x; - max: function ( v ) { + return this; - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); - this.w = Math.max( this.w, v.w ); + }, - return this; + crossVectors: function ( a, b ) { - }, + var ax = a.x, ay = a.y, az = a.z; + var bx = b.x, by = b.y, bz = b.z; - clamp: function ( min, max ) { + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; - // This function assumes min < max, if this assumption isn't true it will not operate correctly + return this; - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - this.w = Math.max( min.w, Math.min( max.w, this.w ) ); + }, - return this; + projectOnVector: function ( vector ) { - }, + var scalar = vector.dot( this ) / vector.lengthSq(); + + return this.copy( vector ).multiplyScalar( scalar ); + + }, - clampScalar: function () { + projectOnPlane: function () { - var min, max; + var v1; - return function clampScalar( minVal, maxVal ) { + return function projectOnPlane( planeNormal ) { - if ( min === undefined ) { + if ( v1 === undefined ) v1 = new Vector3(); - min = new THREE.Vector4(); - max = new THREE.Vector4(); + v1.copy( this ).projectOnVector( planeNormal ); - } + return this.sub( v1 ); - min.set( minVal, minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal, maxVal ); + }; - return this.clamp( min, max ); + }(), - }; + reflect: function () { - }(), + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length - floor: function () { + var v1; - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); + return function reflect( normal ) { - return this; + if ( v1 === undefined ) v1 = new Vector3(); - }, + return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - ceil: function () { + }; - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + }(), - return this; + angleTo: function ( v ) { - }, + var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) ); - round: function () { + // clamp, to handle numerical problems - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); + return Math.acos( exports.Math.clamp( theta, - 1, 1 ) ); - return this; + }, - }, + distanceTo: function ( v ) { - roundToZero: function () { + return Math.sqrt( this.distanceToSquared( v ) ); - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); + }, - return this; + distanceToSquared: function ( v ) { - }, + var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - negate: function () { + return dx * dx + dy * dy + dz * dz; - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; + }, - return this; + distanceToManhattan: function ( v ) { - }, + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); - dot: function ( v ) { + }, - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + setFromSpherical: function( s ) { - }, + var sinPhiRadius = Math.sin( s.phi ) * s.radius; - lengthSq: function () { + this.x = sinPhiRadius * Math.sin( s.theta ); + this.y = Math.cos( s.phi ) * s.radius; + this.z = sinPhiRadius * Math.cos( s.theta ); - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + return this; - }, + }, - length: function () { + setFromMatrixPosition: function ( m ) { - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + return this.setFromMatrixColumn( m, 3 ); - }, + }, - lengthManhattan: function () { + setFromMatrixScale: function ( m ) { - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + var sx = this.setFromMatrixColumn( m, 0 ).length(); + var sy = this.setFromMatrixColumn( m, 1 ).length(); + var sz = this.setFromMatrixColumn( m, 2 ).length(); - }, + this.x = sx; + this.y = sy; + this.z = sz; - normalize: function () { + return this; - return this.divideScalar( this.length() ); + }, - }, + setFromMatrixColumn: function ( m, index ) { - setLength: function ( length ) { + if ( typeof m === 'number' ) { - return this.multiplyScalar( length / this.length() ); + console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' ); + var temp = m + m = index; + index = temp; - }, + } - lerp: function ( v, alpha ) { + return this.fromArray( m.elements, index * 4 ); - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - this.w += ( v.w - this.w ) * alpha; + }, - return this; + equals: function ( v ) { - }, + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - lerpVectors: function ( v1, v2, alpha ) { + }, - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + fromArray: function ( array, offset ) { - }, + if ( offset === undefined ) offset = 0; - equals: function ( v ) { + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + return this; - }, + }, - fromArray: function ( array, offset ) { + toArray: function ( array, offset ) { - if ( offset === undefined ) offset = 0; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; - return this; + return array; - }, + }, - toArray: function ( array, offset ) { + fromAttribute: function ( attribute, index, offset ) { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + if ( offset === undefined ) offset = 0; - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; + index = index * attribute.itemSize + offset; - return array; + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; - }, + return this; - fromAttribute: function ( attribute, index, offset ) { + } - if ( offset === undefined ) offset = 0; + }; - index = index * attribute.itemSize + offset; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; - this.w = attribute.array[ index + 3 ]; + function SpritePlugin ( renderer, sprites ) { + this.isSpritePlugin = true; - return this; + var gl = renderer.context; + var state = renderer.state; - } + var vertexBuffer, elementBuffer; + var program, attributes, uniforms; -}; + var texture; -// File:src/math/Euler.js + // decompose matrixWorld -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ + var spritePosition = new Vector3(); + var spriteRotation = new Quaternion(); + var spriteScale = new Vector3(); -THREE.Euler = function ( x, y, z, order ) { + function init() { - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._order = order || THREE.Euler.DefaultOrder; + var vertices = new Float32Array( [ + - 0.5, - 0.5, 0, 0, + 0.5, - 0.5, 1, 0, + 0.5, 0.5, 1, 1, + - 0.5, 0.5, 0, 1 + ] ); -}; + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); -THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); -THREE.Euler.DefaultOrder = 'XYZ'; + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); -THREE.Euler.prototype = { + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - constructor: THREE.Euler, + program = createProgram(); - get x () { + attributes = { + position: gl.getAttribLocation ( program, 'position' ), + uv: gl.getAttribLocation ( program, 'uv' ) + }; - return this._x; + uniforms = { + uvOffset: gl.getUniformLocation( program, 'uvOffset' ), + uvScale: gl.getUniformLocation( program, 'uvScale' ), - }, + rotation: gl.getUniformLocation( program, 'rotation' ), + scale: gl.getUniformLocation( program, 'scale' ), - set x ( value ) { + color: gl.getUniformLocation( program, 'color' ), + map: gl.getUniformLocation( program, 'map' ), + opacity: gl.getUniformLocation( program, 'opacity' ), - this._x = value; - this.onChangeCallback(); + modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), + projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), - }, + fogType: gl.getUniformLocation( program, 'fogType' ), + fogDensity: gl.getUniformLocation( program, 'fogDensity' ), + fogNear: gl.getUniformLocation( program, 'fogNear' ), + fogFar: gl.getUniformLocation( program, 'fogFar' ), + fogColor: gl.getUniformLocation( program, 'fogColor' ), - get y () { + alphaTest: gl.getUniformLocation( program, 'alphaTest' ) + }; - return this._y; + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = 8; + canvas.height = 8; - }, + var context = canvas.getContext( '2d' ); + context.fillStyle = 'white'; + context.fillRect( 0, 0, 8, 8 ); - set y ( value ) { + texture = new Texture( canvas ); + texture.needsUpdate = true; - this._y = value; - this.onChangeCallback(); + } - }, + this.render = function ( scene, camera ) { - get z () { + if ( sprites.length === 0 ) return; - return this._z; + // setup gl - }, + if ( program === undefined ) { - set z ( value ) { + init(); - this._z = value; - this.onChangeCallback(); + } - }, + gl.useProgram( program ); - get order () { + state.initAttributes(); + state.enableAttribute( attributes.position ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); - return this._order; + state.disable( gl.CULL_FACE ); + state.enable( gl.BLEND ); - }, + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 ); + gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); - set order ( value ) { + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - this._order = value; - this.onChangeCallback(); + gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); - }, + state.activeTexture( gl.TEXTURE0 ); + gl.uniform1i( uniforms.map, 0 ); - set: function ( x, y, z, order ) { + var oldFogType = 0; + var sceneFogType = 0; + var fog = scene.fog; - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; + if ( fog ) { - this.onChangeCallback(); + gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); - return this; + if ( (fog && fog.isFog) ) { - }, + gl.uniform1f( uniforms.fogNear, fog.near ); + gl.uniform1f( uniforms.fogFar, fog.far ); - clone: function () { + gl.uniform1i( uniforms.fogType, 1 ); + oldFogType = 1; + sceneFogType = 1; - return new this.constructor( this._x, this._y, this._z, this._order ); + } else if ( (fog && fog.isFogExp2) ) { - }, + gl.uniform1f( uniforms.fogDensity, fog.density ); - copy: function ( euler ) { + gl.uniform1i( uniforms.fogType, 2 ); + oldFogType = 2; + sceneFogType = 2; - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; + } - this.onChangeCallback(); + } else { - return this; + gl.uniform1i( uniforms.fogType, 0 ); + oldFogType = 0; + sceneFogType = 0; - }, + } - setFromRotationMatrix: function ( m, order, update ) { - var clamp = THREE.Math.clamp; + // update positions and sort - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - var te = m.elements; - var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; - var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; - var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + var sprite = sprites[ i ]; - order = order || this._order; + sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); + sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; - if ( order === 'XYZ' ) { + } - this._y = Math.asin( clamp( m13, - 1, 1 ) ); + sprites.sort( painterSortStable ); - if ( Math.abs( m13 ) < 0.99999 ) { + // render all sprites - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); + var scale = []; - } else { + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - this._x = Math.atan2( m32, m22 ); - this._z = 0; + var sprite = sprites[ i ]; + var material = sprite.material; - } + if ( material.visible === false ) continue; - } else if ( order === 'YXZ' ) { + gl.uniform1f( uniforms.alphaTest, material.alphaTest ); + gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); - if ( Math.abs( m23 ) < 0.99999 ) { + scale[ 0 ] = spriteScale.x; + scale[ 1 ] = spriteScale.y; - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); + var fogType = 0; - } else { + if ( scene.fog && material.fog ) { - this._y = Math.atan2( - m31, m11 ); - this._z = 0; + fogType = sceneFogType; - } + } - } else if ( order === 'ZXY' ) { + if ( oldFogType !== fogType ) { - this._x = Math.asin( clamp( m32, - 1, 1 ) ); + gl.uniform1i( uniforms.fogType, fogType ); + oldFogType = fogType; - if ( Math.abs( m32 ) < 0.99999 ) { + } - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); + if ( material.map !== null ) { - } else { + gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y ); + gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y ); - this._y = 0; - this._z = Math.atan2( m21, m11 ); + } else { - } + gl.uniform2f( uniforms.uvOffset, 0, 0 ); + gl.uniform2f( uniforms.uvScale, 1, 1 ); - } else if ( order === 'ZYX' ) { + } - this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + gl.uniform1f( uniforms.opacity, material.opacity ); + gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); - if ( Math.abs( m31 ) < 0.99999 ) { + gl.uniform1f( uniforms.rotation, material.rotation ); + gl.uniform2fv( uniforms.scale, scale ); - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); + state.setDepthTest( material.depthTest ); + state.setDepthWrite( material.depthWrite ); - } else { + if ( material.map ) { - this._x = 0; - this._z = Math.atan2( - m12, m22 ); + renderer.setTexture2D( material.map, 0 ); - } + } else { - } else if ( order === 'YZX' ) { + renderer.setTexture2D( texture, 0 ); - this._z = Math.asin( clamp( m21, - 1, 1 ) ); + } - if ( Math.abs( m21 ) < 0.99999 ) { + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); + } - } else { + // restore gl - this._x = 0; - this._y = Math.atan2( m13, m33 ); + state.enable( gl.CULL_FACE ); - } + renderer.resetGLState(); - } else if ( order === 'XZY' ) { + }; - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + function createProgram () { - if ( Math.abs( m12 ) < 0.99999 ) { + var program = gl.createProgram(); - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - } else { + gl.shaderSource( vertexShader, [ - this._x = Math.atan2( - m23, m33 ); - this._y = 0; + 'precision ' + renderer.getPrecision() + ' float;', - } + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform float rotation;', + 'uniform vec2 scale;', + 'uniform vec2 uvOffset;', + 'uniform vec2 uvScale;', - } else { + 'attribute vec2 position;', + 'attribute vec2 uv;', - console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); + 'varying vec2 vUV;', - } + 'void main() {', - this._order = order; + 'vUV = uvOffset + uv * uvScale;', - if ( update !== false ) this.onChangeCallback(); + 'vec2 alignedPosition = position * scale;', - return this; + 'vec2 rotatedPosition;', + 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', + 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', - }, + 'vec4 finalPosition;', - setFromQuaternion: function () { + 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', + 'finalPosition.xy += rotatedPosition;', + 'finalPosition = projectionMatrix * finalPosition;', - var matrix; + 'gl_Position = finalPosition;', - return function setFromQuaternion( q, order, update ) { + '}' - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + ].join( '\n' ) ); - matrix.makeRotationFromQuaternion( q ); + gl.shaderSource( fragmentShader, [ - return this.setFromRotationMatrix( matrix, order, update ); + 'precision ' + renderer.getPrecision() + ' float;', - }; + 'uniform vec3 color;', + 'uniform sampler2D map;', + 'uniform float opacity;', - }(), + 'uniform int fogType;', + 'uniform vec3 fogColor;', + 'uniform float fogDensity;', + 'uniform float fogNear;', + 'uniform float fogFar;', + 'uniform float alphaTest;', - setFromVector3: function ( v, order ) { + 'varying vec2 vUV;', - return this.set( v.x, v.y, v.z, order || this._order ); + 'void main() {', - }, + 'vec4 texture = texture2D( map, vUV );', - reorder: function () { + 'if ( texture.a < alphaTest ) discard;', - // WARNING: this discards revolution information -bhouston + 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', - var q = new THREE.Quaternion(); + 'if ( fogType > 0 ) {', - return function reorder( newOrder ) { + 'float depth = gl_FragCoord.z / gl_FragCoord.w;', + 'float fogFactor = 0.0;', - q.setFromEuler( this ); - - return this.setFromQuaternion( q, newOrder ); + 'if ( fogType == 1 ) {', - }; + 'fogFactor = smoothstep( fogNear, fogFar, depth );', - }(), + '} else {', - equals: function ( euler ) { + 'const float LOG2 = 1.442695;', + 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', + 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + '}', - }, + 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', - fromArray: function ( array ) { + '}', - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + '}' - this.onChangeCallback(); + ].join( '\n' ) ); - return this; + gl.compileShader( vertexShader ); + gl.compileShader( fragmentShader ); - }, + gl.attachShader( program, vertexShader ); + gl.attachShader( program, fragmentShader ); - toArray: function ( array, offset ) { + gl.linkProgram( program ); - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + return program; - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; + } - return array; + function painterSortStable ( a, b ) { - }, + if ( a.renderOrder !== b.renderOrder ) { - toVector3: function ( optionalResult ) { + return a.renderOrder - b.renderOrder; - if ( optionalResult ) { + } else if ( a.z !== b.z ) { - return optionalResult.set( this._x, this._y, this._z ); + return b.z - a.z; - } else { + } else { - return new THREE.Vector3( this._x, this._y, this._z ); + return b.id - a.id; - } + } - }, + } - onChange: function ( callback ) { + }; - this.onChangeCallback = callback; + /** + * @author bhouston / http://clara.io + */ - return this; + function Box2 ( min, max ) { + this.isBox2 = true; - }, + this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); - onChangeCallback: function () {} + }; -}; + Box2.prototype = { -// File:src/math/Line3.js + constructor: Box2, -/** - * @author bhouston / http://clara.io - */ + set: function ( min, max ) { -THREE.Line3 = function ( start, end ) { + this.min.copy( min ); + this.max.copy( max ); - this.start = ( start !== undefined ) ? start : new THREE.Vector3(); - this.end = ( end !== undefined ) ? end : new THREE.Vector3(); + return this; -}; + }, -THREE.Line3.prototype = { + setFromPoints: function ( points ) { - constructor: THREE.Line3, + this.makeEmpty(); - set: function ( start, end ) { + for ( var i = 0, il = points.length; i < il; i ++ ) { - this.start.copy( start ); - this.end.copy( end ); + this.expandByPoint( points[ i ] ); - return this; + } - }, + return this; - clone: function () { + }, - return new this.constructor().copy( this ); + setFromCenterAndSize: function () { - }, + var v1 = new Vector2(); - copy: function ( line ) { + return function setFromCenterAndSize( center, size ) { - this.start.copy( line.start ); - this.end.copy( line.end ); + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - return this; + return this; - }, + }; - center: function ( optionalTarget ) { + }(), - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + clone: function () { - }, + return new this.constructor().copy( this ); - delta: function ( optionalTarget ) { + }, - var result = optionalTarget || new THREE.Vector3(); - return result.subVectors( this.end, this.start ); + copy: function ( box ) { - }, + this.min.copy( box.min ); + this.max.copy( box.max ); - distanceSq: function () { + return this; - return this.start.distanceToSquared( this.end ); + }, - }, + makeEmpty: function () { - distance: function () { + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; - return this.start.distanceTo( this.end ); + return this; - }, + }, - at: function ( t, optionalTarget ) { + isEmpty: function () { - var result = optionalTarget || new THREE.Vector3(); + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - return this.delta( result ).multiplyScalar( t ).add( this.start ); + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - }, + }, - closestPointToPointParameter: function () { + center: function ( optionalTarget ) { - var startP = new THREE.Vector3(); - var startEnd = new THREE.Vector3(); + var result = optionalTarget || new Vector2(); + return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - return function closestPointToPointParameter( point, clampToLine ) { + }, - startP.subVectors( point, this.start ); - startEnd.subVectors( this.end, this.start ); + size: function ( optionalTarget ) { - var startEnd2 = startEnd.dot( startEnd ); - var startEnd_startP = startEnd.dot( startP ); + var result = optionalTarget || new Vector2(); + return result.subVectors( this.max, this.min ); - var t = startEnd_startP / startEnd2; + }, - if ( clampToLine ) { + expandByPoint: function ( point ) { - t = THREE.Math.clamp( t, 0, 1 ); + this.min.min( point ); + this.max.max( point ); - } + return this; - return t; + }, - }; + expandByVector: function ( vector ) { - }(), + this.min.sub( vector ); + this.max.add( vector ); - closestPointToPoint: function ( point, clampToLine, optionalTarget ) { + return this; - var t = this.closestPointToPointParameter( point, clampToLine ); + }, - var result = optionalTarget || new THREE.Vector3(); + expandByScalar: function ( scalar ) { - return this.delta( result ).multiplyScalar( t ).add( this.start ); + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - }, + return this; - applyMatrix4: function ( matrix ) { + }, - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); + containsPoint: function ( point ) { - return this; + if ( point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ) { - }, + return false; - equals: function ( line ) { + } - return line.start.equals( this.start ) && line.end.equals( this.end ); + return true; - } + }, -}; + containsBox: function ( box ) { -// File:src/math/Box2.js + if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && + ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) { -/** - * @author bhouston / http://clara.io - */ + return true; -THREE.Box2 = function ( min, max ) { + } - this.min = ( min !== undefined ) ? min : new THREE.Vector2( + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity ); + return false; -}; + }, -THREE.Box2.prototype = { + getParameter: function ( point, optionalTarget ) { - constructor: THREE.Box2, + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - set: function ( min, max ) { + var result = optionalTarget || new Vector2(); - this.min.copy( min ); - this.max.copy( max ); + return result.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); - return this; + }, - }, + intersectsBox: function ( box ) { - setFromPoints: function ( points ) { + // using 6 splitting planes to rule out intersections. - this.makeEmpty(); + if ( box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ) { - for ( var i = 0, il = points.length; i < il; i ++ ) { + return false; - this.expandByPoint( points[ i ] ); + } - } + return true; - return this; + }, - }, + clampPoint: function ( point, optionalTarget ) { - setFromCenterAndSize: function () { + var result = optionalTarget || new Vector2(); + return result.copy( point ).clamp( this.min, this.max ); - var v1 = new THREE.Vector2(); + }, - return function setFromCenterAndSize( center, size ) { + distanceToPoint: function () { - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + var v1 = new Vector2(); - return this; + return function distanceToPoint( point ) { - }; + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - }(), + }; - clone: function () { + }(), - return new this.constructor().copy( this ); + intersect: function ( box ) { - }, + this.min.max( box.min ); + this.max.min( box.max ); - copy: function ( box ) { + return this; - this.min.copy( box.min ); - this.max.copy( box.max ); + }, - return this; + union: function ( box ) { - }, + this.min.min( box.min ); + this.max.max( box.max ); - makeEmpty: function () { + return this; - this.min.x = this.min.y = + Infinity; - this.max.x = this.max.y = - Infinity; + }, - return this; + translate: function ( offset ) { - }, + this.min.add( offset ); + this.max.add( offset ); - isEmpty: function () { + return this; - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + }, - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + equals: function ( box ) { - }, + return box.min.equals( this.min ) && box.max.equals( this.max ); - center: function ( optionalTarget ) { + } - var result = optionalTarget || new THREE.Vector2(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + }; - }, + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - size: function ( optionalTarget ) { + function LensFlarePlugin ( renderer, flares ) { + this.isLensFlarePlugin = true; - var result = optionalTarget || new THREE.Vector2(); - return result.subVectors( this.max, this.min ); + var gl = renderer.context; + var state = renderer.state; - }, + var vertexBuffer, elementBuffer; + var shader, program, attributes, uniforms; - expandByPoint: function ( point ) { + var tempTexture, occlusionTexture; - this.min.min( point ); - this.max.max( point ); + function init() { - return this; + var vertices = new Float32Array( [ + - 1, - 1, 0, 0, + 1, - 1, 1, 0, + 1, 1, 1, 1, + - 1, 1, 0, 1 + ] ); - }, + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); - expandByVector: function ( vector ) { + // buffers - this.min.sub( vector ); - this.max.add( vector ); + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - return this; + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - }, + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - expandByScalar: function ( scalar ) { + // textures - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + tempTexture = gl.createTexture(); + occlusionTexture = gl.createTexture(); - return this; + state.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - }, + state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); + gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - containsPoint: function ( point ) { + shader = { - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ) { + vertexShader: [ - return false; + "uniform lowp int renderType;", - } + "uniform vec3 screenPosition;", + "uniform vec2 scale;", + "uniform float rotation;", - return true; + "uniform sampler2D occlusionMap;", - }, + "attribute vec2 position;", + "attribute vec2 uv;", - containsBox: function ( box ) { + "varying vec2 vUV;", + "varying float vVisibility;", - if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && - ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) { + "void main() {", - return true; + "vUV = uv;", - } + "vec2 pos = position;", - return false; + "if ( renderType == 2 ) {", - }, + "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );", - getParameter: function ( point, optionalTarget ) { + "vVisibility = visibility.r / 9.0;", + "vVisibility *= 1.0 - visibility.g / 9.0;", + "vVisibility *= visibility.b / 9.0;", + "vVisibility *= 1.0 - visibility.a / 9.0;", - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", + "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", - var result = optionalTarget || new THREE.Vector2(); + "}", - return result.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ) - ); + "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", - }, + "}" - intersectsBox: function ( box ) { + ].join( "\n" ), - // using 6 splitting planes to rule out intersections. + fragmentShader: [ - if ( box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y ) { + "uniform lowp int renderType;", - return false; + "uniform sampler2D map;", + "uniform float opacity;", + "uniform vec3 color;", - } + "varying vec2 vUV;", + "varying float vVisibility;", - return true; + "void main() {", - }, + // pink square - clampPoint: function ( point, optionalTarget ) { + "if ( renderType == 0 ) {", - var result = optionalTarget || new THREE.Vector2(); - return result.copy( point ).clamp( this.min, this.max ); + "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", - }, + // restore - distanceToPoint: function () { + "} else if ( renderType == 1 ) {", - var v1 = new THREE.Vector2(); + "gl_FragColor = texture2D( map, vUV );", - return function distanceToPoint( point ) { + // flare - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + "} else {", - }; + "vec4 texture = texture2D( map, vUV );", + "texture.a *= opacity * vVisibility;", + "gl_FragColor = texture;", + "gl_FragColor.rgb *= color;", - }(), + "}", - intersect: function ( box ) { + "}" - this.min.max( box.min ); - this.max.min( box.max ); + ].join( "\n" ) - return this; + }; - }, + program = createProgram( shader ); - union: function ( box ) { + attributes = { + vertex: gl.getAttribLocation ( program, "position" ), + uv: gl.getAttribLocation ( program, "uv" ) + }; - this.min.min( box.min ); - this.max.max( box.max ); + uniforms = { + renderType: gl.getUniformLocation( program, "renderType" ), + map: gl.getUniformLocation( program, "map" ), + occlusionMap: gl.getUniformLocation( program, "occlusionMap" ), + opacity: gl.getUniformLocation( program, "opacity" ), + color: gl.getUniformLocation( program, "color" ), + scale: gl.getUniformLocation( program, "scale" ), + rotation: gl.getUniformLocation( program, "rotation" ), + screenPosition: gl.getUniformLocation( program, "screenPosition" ) + }; - return this; + } - }, + /* + * Render lens flares + * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, + * reads these back and calculates occlusion. + */ - translate: function ( offset ) { + this.render = function ( scene, camera, viewport ) { - this.min.add( offset ); - this.max.add( offset ); + if ( flares.length === 0 ) return; - return this; + var tempPosition = new Vector3(); - }, + var invAspect = viewport.w / viewport.z, + halfViewportWidth = viewport.z * 0.5, + halfViewportHeight = viewport.w * 0.5; - equals: function ( box ) { + var size = 16 / viewport.w, + scale = new Vector2( size * invAspect, size ); - return box.min.equals( this.min ) && box.max.equals( this.max ); + var screenPosition = new Vector3( 1, 1, 0 ), + screenPositionPixels = new Vector2( 1, 1 ); - } + var validArea = new Box2(); -}; + validArea.min.set( 0, 0 ); + validArea.max.set( viewport.z - 16, viewport.w - 16 ); -// File:src/math/Box3.js + if ( program === undefined ) { -/** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - */ + init(); -THREE.Box3 = function ( min, max ) { + } - this.min = ( min !== undefined ) ? min : new THREE.Vector3( + Infinity, + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity ); + gl.useProgram( program ); -}; + state.initAttributes(); + state.enableAttribute( attributes.vertex ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); -THREE.Box3.prototype = { + // loop through all lens flares to update their occlusion and positions + // setup gl and common used attribs/uniforms - constructor: THREE.Box3, + gl.uniform1i( uniforms.occlusionMap, 0 ); + gl.uniform1i( uniforms.map, 1 ); - set: function ( min, max ) { + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 ); + gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); - this.min.copy( min ); - this.max.copy( max ); + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - return this; + state.disable( gl.CULL_FACE ); + state.setDepthWrite( false ); - }, + for ( var i = 0, l = flares.length; i < l; i ++ ) { - setFromArray: function ( array ) { + size = 16 / viewport.w; + scale.set( size * invAspect, size ); - var minX = + Infinity; - var minY = + Infinity; - var minZ = + Infinity; + // calc object screen position - var maxX = - Infinity; - var maxY = - Infinity; - var maxZ = - Infinity; + var flare = flares[ i ]; - for ( var i = 0, l = array.length; i < l; i += 3 ) { + tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] ); - var x = array[ i ]; - var y = array[ i + 1 ]; - var z = array[ i + 2 ]; + tempPosition.applyMatrix4( camera.matrixWorldInverse ); + tempPosition.applyProjection( camera.projectionMatrix ); - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; + // setup arrays for gl programs - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; + screenPosition.copy( tempPosition ); - } + // horizontal and vertical coordinate of the lower left corner of the pixels to copy - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8; + screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8; - }, + // screen cull - setFromPoints: function ( points ) { + if ( validArea.containsPoint( screenPositionPixels ) === true ) { - this.makeEmpty(); + // save current RGB to temp texture - for ( var i = 0, il = points.length; i < il; i ++ ) { + state.activeTexture( gl.TEXTURE0 ); + state.bindTexture( gl.TEXTURE_2D, null ); + state.activeTexture( gl.TEXTURE1 ); + state.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); - this.expandByPoint( points[ i ] ); - } + // render pink quad - return this; + gl.uniform1i( uniforms.renderType, 0 ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - }, + state.disable( gl.BLEND ); + state.enable( gl.DEPTH_TEST ); - setFromCenterAndSize: function () { + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - var v1 = new THREE.Vector3(); - return function setFromCenterAndSize( center, size ) { + // copy result to occlusionMap - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + state.activeTexture( gl.TEXTURE0 ); + state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); + gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); - return this; + // restore graphics - }; + gl.uniform1i( uniforms.renderType, 1 ); + state.disable( gl.DEPTH_TEST ); - }(), + state.activeTexture( gl.TEXTURE1 ); + state.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - setFromObject: function () { - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms + // update object positions - var v1 = new THREE.Vector3(); + flare.positionScreen.copy( screenPosition ); - return function setFromObject( object ) { + if ( flare.customUpdateCallback ) { - var scope = this; + flare.customUpdateCallback( flare ); - object.updateMatrixWorld( true ); + } else { - this.makeEmpty(); + flare.updateLensFlares(); - object.traverse( function ( node ) { + } - var geometry = node.geometry; + // render flares - if ( geometry !== undefined ) { + gl.uniform1i( uniforms.renderType, 2 ); + state.enable( gl.BLEND ); - if ( geometry instanceof THREE.Geometry ) { + for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { - var vertices = geometry.vertices; + var sprite = flare.lensFlares[ j ]; - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { - v1.copy( vertices[ i ] ); - v1.applyMatrix4( node.matrixWorld ); + screenPosition.x = sprite.x; + screenPosition.y = sprite.y; + screenPosition.z = sprite.z; - scope.expandByPoint( v1 ); + size = sprite.size * sprite.scale / viewport.w; - } + scale.x = size * invAspect; + scale.y = size; - } else if ( geometry instanceof THREE.BufferGeometry ) { + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform1f( uniforms.rotation, sprite.rotation ); - var attribute = geometry.attributes.position; + gl.uniform1f( uniforms.opacity, sprite.opacity ); + gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); - if ( attribute !== undefined ) { + state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); + renderer.setTexture2D( sprite.texture, 1 ); - var array, offset, stride; + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + } - array = attribute.data.array; - offset = attribute.offset; - stride = attribute.data.stride; + } - } else { + } - array = attribute.array; - offset = 0; - stride = 3; + } - } + // restore gl - for ( var i = offset, il = array.length; i < il; i += stride ) { + state.enable( gl.CULL_FACE ); + state.enable( gl.DEPTH_TEST ); + state.setDepthWrite( true ); - v1.fromArray( array, i ); - v1.applyMatrix4( node.matrixWorld ); + renderer.resetGLState(); - scope.expandByPoint( v1 ); + }; - } + function createProgram ( shader ) { - } + var program = gl.createProgram(); - } + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - } + var prefix = "precision " + renderer.getPrecision() + " float;\n"; - } ); + gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); + gl.shaderSource( vertexShader, prefix + shader.vertexShader ); - return this; + gl.compileShader( fragmentShader ); + gl.compileShader( vertexShader ); - }; + gl.attachShader( program, fragmentShader ); + gl.attachShader( program, vertexShader ); - }(), + gl.linkProgram( program ); - clone: function () { + return program; - return new this.constructor().copy( this ); + } - }, + }; - copy: function ( box ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.min.copy( box.min ); - this.max.copy( box.max ); + function CubeTexture ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.isCubeTexture = this.isTexture = true; - return this; + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - }, + Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - makeEmpty: function () { + this.flipY = false; - this.min.x = this.min.y = this.min.z = + Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; + }; - return this; + CubeTexture.prototype = Object.create( Texture.prototype ); + CubeTexture.prototype.constructor = CubeTexture; - }, + Object.defineProperty( CubeTexture.prototype, 'images', { - isEmpty: function () { + get: function () { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + return this.image; - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + }, - }, + set: function ( value ) { - center: function ( optionalTarget ) { + this.image = value; - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + } - }, + } ); - size: function ( optionalTarget ) { + /** + * + * Uniforms of a program. + * Those form a tree structure with a special top-level container for the root, + * which you get by calling 'new WebGLUniforms( gl, program, renderer )'. + * + * + * Properties of inner nodes including the top-level container: + * + * .seq - array of nested uniforms + * .map - nested uniforms by name + * + * + * Methods of all nodes except the top-level container: + * + * .setValue( gl, value, [renderer] ) + * + * uploads a uniform value(s) + * the 'renderer' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (renderer factorizations): + * + * .upload( gl, seq, values, renderer ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * .splitDynamic( seq, values ) : filteredSeq + * + * filters 'seq' entries with dynamic entry and removes them from 'seq' + * + * + * Methods of the top-level container (renderer factorizations): + * + * .setValue( gl, name, value ) + * + * sets uniform with name 'name' to 'value' + * + * .set( gl, obj, prop ) + * + * sets uniform from object and property with same name than uniform + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + * + * @author tschw + * + */ - var result = optionalTarget || new THREE.Vector3(); - return result.subVectors( this.max, this.min ); + exports.WebGLUniforms = ( function() { // scope - }, + var emptyTexture = new Texture(); + var emptyCubeTexture = new CubeTexture(); - expandByPoint: function ( point ) { + // --- Base for inner nodes (including the root) --- - this.min.min( point ); - this.max.max( point ); + var UniformContainer = function() { - return this; + this.seq = []; + this.map = {}; - }, + }, - expandByVector: function ( vector ) { + // --- Utilities --- - this.min.sub( vector ); - this.max.add( vector ); + // Array Caches (provide typed arrays for temporary by size) - return this; + arrayCacheF32 = [], + arrayCacheI32 = [], - }, + uncacheTemporaryArrays = function() { - expandByScalar: function ( scalar ) { + arrayCacheF32.length = 0; + arrayCacheI32.length = 0; - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + }, - return this; + // Flattening for arrays of vectors and matrices - }, + flatten = function( array, nBlocks, blockSize ) { - containsPoint: function ( point ) { + var firstElem = array[ 0 ]; - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y || - point.z < this.min.z || point.z > this.max.z ) { + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 - return false; + var n = nBlocks * blockSize, + r = arrayCacheF32[ n ]; - } + if ( r === undefined ) { - return true; + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; - }, + } - containsBox: function ( box ) { + if ( nBlocks !== 0 ) { - if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && - ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) && - ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) { + firstElem.toArray( r, 0 ); - return true; + for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { - } + offset += blockSize; + array[ i ].toArray( r, offset ); - return false; + } - }, + } - getParameter: function ( point, optionalTarget ) { + return r; - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + }, - var result = optionalTarget || new THREE.Vector3(); + // Texture unit allocation - return result.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ), - ( point.z - this.min.z ) / ( this.max.z - this.min.z ) - ); + allocTexUnits = function( renderer, n ) { - }, + var r = arrayCacheI32[ n ]; - intersectsBox: function ( box ) { + if ( r === undefined ) { - // using 6 splitting planes to rule out intersections. + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; - if ( box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y || - box.max.z < this.min.z || box.min.z > this.max.z ) { + } - return false; + for ( var i = 0; i !== n; ++ i ) + r[ i ] = renderer.allocTextureUnit(); - } + return r; - return true; + }, - }, + // --- Setters --- - intersectsSphere: ( function () { + // Note: Defining these methods externally, because they come in a bunch + // and this way their names minify. - var closestPoint; + // Single scalar - return function intersectsSphere( sphere ) { + setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); }, + setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); }, - if ( closestPoint === undefined ) closestPoint = new THREE.Vector3(); + // Single float vector (from flat array or THREE.VectorN) - // Find the point on the AABB closest to the sphere center. - this.clampPoint( sphere.center, closestPoint ); + setValue2fv = function( gl, v ) { - // If that point is inside the sphere, the AABB and sphere intersect. - return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + if ( v.x === undefined ) gl.uniform2fv( this.addr, v ); + else gl.uniform2f( this.addr, v.x, v.y ); - }; + }, - } )(), + setValue3fv = function( gl, v ) { - intersectsPlane: function ( plane ) { + if ( v.x !== undefined ) + gl.uniform3f( this.addr, v.x, v.y, v.z ); + else if ( v.r !== undefined ) + gl.uniform3f( this.addr, v.r, v.g, v.b ); + else + gl.uniform3fv( this.addr, v ); - // We compute the minimum and maximum dot product values. If those values - // are on the same side (back or front) of the plane, then there is no intersection. + }, - var min, max; + setValue4fv = function( gl, v ) { - if ( plane.normal.x > 0 ) { + if ( v.x === undefined ) gl.uniform4fv( this.addr, v ); + else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; + }, - } else { + // Single matrix (from flat array or MatrixN) - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; + setValue2fm = function( gl, v ) { - } + gl.uniformMatrix2fv( this.addr, false, v.elements || v ); - if ( plane.normal.y > 0 ) { + }, - min += plane.normal.y * this.min.y; - max += plane.normal.y * this.max.y; + setValue3fm = function( gl, v ) { - } else { + gl.uniformMatrix3fv( this.addr, false, v.elements || v ); - min += plane.normal.y * this.max.y; - max += plane.normal.y * this.min.y; + }, - } + setValue4fm = function( gl, v ) { - if ( plane.normal.z > 0 ) { + gl.uniformMatrix4fv( this.addr, false, v.elements || v ); - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; + }, - } else { + // Single texture (2D / Cube) - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; + setValueT1 = function( gl, v, renderer ) { - } + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTexture2D( v || emptyTexture, unit ); - return ( min <= plane.constant && max >= plane.constant ); + }, - }, + setValueT6 = function( gl, v, renderer ) { - clampPoint: function ( point, optionalTarget ) { + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTextureCube( v || emptyCubeTexture, unit ); - var result = optionalTarget || new THREE.Vector3(); - return result.copy( point ).clamp( this.min, this.max ); + }, - }, + // Integer / Boolean vectors or arrays thereof (always flat arrays) - distanceToPoint: function () { + setValue2iv = function( gl, v ) { gl.uniform2iv( this.addr, v ); }, + setValue3iv = function( gl, v ) { gl.uniform3iv( this.addr, v ); }, + setValue4iv = function( gl, v ) { gl.uniform4iv( this.addr, v ); }, - var v1 = new THREE.Vector3(); + // Helper to pick the right setter for the singular case - return function distanceToPoint( point ) { + getSingularSetter = function( type ) { - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + switch ( type ) { - }; + case 0x1406: return setValue1f; // FLOAT + case 0x8b50: return setValue2fv; // _VEC2 + case 0x8b51: return setValue3fv; // _VEC3 + case 0x8b52: return setValue4fv; // _VEC4 - }(), + case 0x8b5a: return setValue2fm; // _MAT2 + case 0x8b5b: return setValue3fm; // _MAT3 + case 0x8b5c: return setValue4fm; // _MAT4 - getBoundingSphere: function () { + case 0x8b5e: return setValueT1; // SAMPLER_2D + case 0x8b60: return setValueT6; // SAMPLER_CUBE - var v1 = new THREE.Vector3(); + case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 + case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 + case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 - return function getBoundingSphere( optionalTarget ) { + } - var result = optionalTarget || new THREE.Sphere(); + }, - result.center = this.center(); - result.radius = this.size( v1 ).length() * 0.5; + // Array of scalars - return result; + setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); }, + setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); }, - }; + // Array of vectors (flat or from THREE classes) - }(), + setValueV2a = function( gl, v ) { - intersect: function ( box ) { + gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); - this.min.max( box.min ); - this.max.min( box.max ); + }, - // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. - if( this.isEmpty() ) this.makeEmpty(); + setValueV3a = function( gl, v ) { - return this; + gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); - }, + }, - union: function ( box ) { + setValueV4a = function( gl, v ) { - this.min.min( box.min ); - this.max.max( box.max ); + gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); - return this; + }, - }, + // Array of matrices (flat or from THREE clases) - applyMatrix4: function () { + setValueM2a = function( gl, v ) { - var points = [ - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3() - ]; + gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); - return function applyMatrix4( matrix ) { + }, - // transform of empty box is an empty box. - if( this.isEmpty() ) return this; + setValueM3a = function( gl, v ) { - // NOTE: I am using a binary pattern to specify all 2^3 combinations below - points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 - points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 - points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 - points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 - points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 - points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 - points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 - points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 + gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); - this.setFromPoints( points ); + }, - return this; + setValueM4a = function( gl, v ) { - }; + gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); - }(), + }, - translate: function ( offset ) { + // Array of textures (2D / Cube) - this.min.add( offset ); - this.max.add( offset ); + setValueT1a = function( gl, v, renderer ) { - return this; + var n = v.length, + units = allocTexUnits( renderer, n ); - }, + gl.uniform1iv( this.addr, units ); - equals: function ( box ) { + for ( var i = 0; i !== n; ++ i ) { - return box.min.equals( this.min ) && box.max.equals( this.max ); + renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); - } + } -}; + }, -// File:src/math/Matrix3.js + setValueT6a = function( gl, v, renderer ) { -/** - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - * @author tschw - */ + var n = v.length, + units = allocTexUnits( renderer, n ); -THREE.Matrix3 = function () { + gl.uniform1iv( this.addr, units ); - this.elements = new Float32Array( [ + for ( var i = 0; i !== n; ++ i ) { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); - ] ); + } - if ( arguments.length > 0 ) { + }, - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - } + // Helper to pick the right setter for a pure (bottom-level) array -}; + getPureArraySetter = function( type ) { -THREE.Matrix3.prototype = { + switch ( type ) { - constructor: THREE.Matrix3, + case 0x1406: return setValue1fv; // FLOAT + case 0x8b50: return setValueV2a; // _VEC2 + case 0x8b51: return setValueV3a; // _VEC3 + case 0x8b52: return setValueV4a; // _VEC4 - set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + case 0x8b5a: return setValueM2a; // _MAT2 + case 0x8b5b: return setValueM3a; // _MAT3 + case 0x8b5c: return setValueM4a; // _MAT4 - var te = this.elements; + case 0x8b5e: return setValueT1a; // SAMPLER_2D + case 0x8b60: return setValueT6a; // SAMPLER_CUBE - te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; - te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; - te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; + case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL + case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 + case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 + case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 - return this; + } - }, + }, - identity: function () { + // --- Uniform Classes --- - this.set( + SingleUniform = function SingleUniform( id, activeInfo, addr ) { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + this.id = id; + this.addr = addr; + this.setValue = getSingularSetter( activeInfo.type ); - ); + // this.path = activeInfo.name; // DEBUG - return this; + }, - }, + PureArrayUniform = function( id, activeInfo, addr ) { - clone: function () { + this.id = id; + this.addr = addr; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - return new this.constructor().fromArray( this.elements ); + // this.path = activeInfo.name; // DEBUG - }, + }, - copy: function ( m ) { + StructuredUniform = function( id ) { - var me = m.elements; + this.id = id; - this.set( + UniformContainer.call( this ); // mix-in - me[ 0 ], me[ 3 ], me[ 6 ], - me[ 1 ], me[ 4 ], me[ 7 ], - me[ 2 ], me[ 5 ], me[ 8 ] + }; - ); + StructuredUniform.prototype.setValue = function( gl, value ) { - return this; + // Note: Don't need an extra 'renderer' parameter, since samplers + // are not allowed in structured uniforms. - }, + var seq = this.seq; - setFromMatrix4: function( m ) { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - var me = m.elements; + var u = seq[ i ]; + u.setValue( gl, value[ u.id ] ); - this.set( + } - me[ 0 ], me[ 4 ], me[ 8 ], - me[ 1 ], me[ 5 ], me[ 9 ], - me[ 2 ], me[ 6 ], me[ 10 ] + }; - ); + // --- Top-level --- - return this; + // Parser - builds up the property tree from the path strings - }, + var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g, + // extracts + // - the identifier (member name or array index) + // - followed by an optional right bracket (found when array index) + // - followed by an optional left bracket or dot (type of subscript) + // + // Note: These portions can be read in a non-overlapping fashion and + // allow straightforward parsing of the hierarchy that WebGL encodes + // in the uniform names. - applyToVector3Array: function () { + addUniform = function( container, uniformObject ) { - var v1; + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; - return function applyToVector3Array( array, offset, length ) { + }, - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + parseUniform = function( activeInfo, addr, container ) { - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + var path = activeInfo.name, + pathLength = path.length; - v1.fromArray( array, j ); - v1.applyMatrix3( this ); - v1.toArray( array, j ); + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; - } + for (; ;) { - return array; + var match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex, - }; + id = match[ 1 ], + idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; - }(), + if ( idIsIndex ) id = id | 0; // convert to integer - applyToBuffer: function () { + if ( subscript === undefined || + subscript === '[' && matchEnd + 2 === pathLength ) { + // bare name or "pure" bottom-level array "[0]" suffix - var v1; + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); - return function applyToBuffer( buffer, offset, length ) { + break; - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = buffer.length / buffer.itemSize; + } else { + // step into inner node / create it in case it doesn't exist - for ( var i = 0, j = offset; i < length; i ++, j ++ ) { + var map = container.map, + next = map[ id ]; - v1.x = buffer.getX( j ); - v1.y = buffer.getY( j ); - v1.z = buffer.getZ( j ); + if ( next === undefined ) { - v1.applyMatrix3( this ); + next = new StructuredUniform( id ); + addUniform( container, next ); - buffer.setXYZ( v1.x, v1.y, v1.z ); + } - } + container = next; - return buffer; + } - }; + } - }(), + }, - multiplyScalar: function ( s ) { + // Root Container - var te = this.elements; + WebGLUniforms = function WebGLUniforms( gl, program, renderer ) { - te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; - te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; - te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; + UniformContainer.call( this ); - return this; + this.renderer = renderer; - }, + var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); - determinant: function () { + for ( var i = 0; i !== n; ++ i ) { - var te = this.elements; + var info = gl.getActiveUniform( program, i ), + path = info.name, + addr = gl.getUniformLocation( program, path ); - var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], - d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], - g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; + parseUniform( info, addr, this ); - return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + } - }, + }; - getInverse: function ( matrix, throwOnDegenerate ) { - if ( matrix instanceof THREE.Matrix4 ) { + WebGLUniforms.prototype.setValue = function( gl, name, value ) { - console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); + var u = this.map[ name ]; - } + if ( u !== undefined ) u.setValue( gl, value, this.renderer ); - var me = matrix.elements, - te = this.elements, + }; - n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], - n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], - n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], + WebGLUniforms.prototype.set = function( gl, object, name ) { - t11 = n33 * n22 - n32 * n23, - t12 = n32 * n13 - n33 * n12, - t13 = n23 * n12 - n22 * n13, + var u = this.map[ name ]; - det = n11 * t11 + n21 * t12 + n31 * t13; + if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer ); - if ( det === 0 ) { + }; - var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; + WebGLUniforms.prototype.setOptional = function( gl, object, name ) { - if ( throwOnDegenerate || false ) { + var v = object[ name ]; - throw new Error( msg ); + if ( v !== undefined ) this.setValue( gl, name, v ); - } else { + }; - console.warn( msg ); - } + // Static interface - return this.identity(); - } - - var detInv = 1 / det; + WebGLUniforms.upload = function( gl, seq, values, renderer ) { - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; - te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - te[ 3 ] = t12 * detInv; - te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; - te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + var u = seq[ i ], + v = values[ u.id ]; - te[ 6 ] = t13 * detInv; - te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; - te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + if ( v.needsUpdate !== false ) { + // note: always updating when .needsUpdate is undefined - return this; + u.setValue( gl, v.value, renderer ); - }, + } - transpose: function () { + } - var tmp, m = this.elements; + }; - tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; - tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; - tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; + WebGLUniforms.seqWithValue = function( seq, values ) { - return this; + var r = []; - }, + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - flattenToArrayOffset: function ( array, offset ) { + var u = seq[ i ]; + if ( u.id in values ) r.push( u ); - console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + - "- just use .toArray instead." ); + } - return this.toArray( array, offset ); + return r; - }, + }; - getNormalMatrix: function ( matrix4 ) { + WebGLUniforms.splitDynamic = function( seq, values ) { - return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); + var r = null, + n = seq.length, + w = 0; - }, + for ( var i = 0; i !== n; ++ i ) { - transposeIntoArray: function ( r ) { + var u = seq[ i ], + v = values[ u.id ]; - var m = this.elements; + if ( v && v.dynamic === true ) { - r[ 0 ] = m[ 0 ]; - r[ 1 ] = m[ 3 ]; - r[ 2 ] = m[ 6 ]; - r[ 3 ] = m[ 1 ]; - r[ 4 ] = m[ 4 ]; - r[ 5 ] = m[ 7 ]; - r[ 6 ] = m[ 2 ]; - r[ 7 ] = m[ 5 ]; - r[ 8 ] = m[ 8 ]; + if ( r === null ) r = []; + r.push( u ); - return this; + } else { - }, + // in-place compact 'seq', removing the matches + if ( w < i ) seq[ w ] = u; + ++ w; - fromArray: function ( array ) { + } - this.elements.set( array ); + } - return this; + if ( w < n ) seq.length = w; - }, + return r; - toArray: function ( array, offset ) { + }; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + WebGLUniforms.evalDynamic = function( seq, values, object, camera ) { - var te = this.elements; + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; + var v = values[ seq[ i ].id ], + f = v.onUpdateCallback; - array[ offset + 3 ] = te[ 3 ]; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; + if ( f !== undefined ) f.call( v, object, camera ); - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - array[ offset + 8 ] = te[ 8 ]; + } - return array; + }; - } + return WebGLUniforms; -}; + } )(); -// File:src/math/Matrix4.js + /** + * @author mrdoob / http://mrdoob.com/ + */ -/** - * @author mrdoob / http://mrdoob.com/ - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author jordi_ros / http://plattsoft.com - * @author D1plo1d / http://github.com/D1plo1d - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author timknip / http://www.floorplanner.com/ - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - */ + function WebGLTextures ( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { + this.isWebGLTextures = true; -THREE.Matrix4 = function () { + var _infoMemory = info.memory; + var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); - this.elements = new Float32Array( [ + // - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + function clampToMaxSize ( image, maxSize ) { - ] ); + if ( image.width > maxSize || image.height > maxSize ) { - if ( arguments.length > 0 ) { + // Warning: Scaling through the canvas will only work with images that use + // premultiplied alpha. - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); + var scale = maxSize / Math.max( image.width, image.height ); - } + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = Math.floor( image.width * scale ); + canvas.height = Math.floor( image.height * scale ); -}; + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); -THREE.Matrix4.prototype = { + console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); - constructor: THREE.Matrix4, + return canvas; - set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + } - var te = this.elements; + return image; - te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; - te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; - te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; - te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; + } - return this; + function isPowerOfTwo( image ) { - }, + return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height ); - identity: function () { + } - this.set( + function makePowerOfTwo( image ) { - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { - ); + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = exports.Math.nearestPowerOfTwo( image.width ); + canvas.height = exports.Math.nearestPowerOfTwo( image.height ); - return this; + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, canvas.width, canvas.height ); - }, + console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); - clone: function () { + return canvas; - return new THREE.Matrix4().fromArray( this.elements ); + } - }, + return image; - copy: function ( m ) { + } - this.elements.set( m.elements ); + function textureNeedsPowerOfTwo( texture ) { - return this; + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true; + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true; - }, + return false; - copyPosition: function ( m ) { + } - var te = this.elements; - var me = m.elements; + // Fallback filters for non-power-of-2 textures - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; + function filterFallback ( f ) { - return this; + if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { - }, + return _gl.NEAREST; - extractBasis: function ( xAxis, yAxis, zAxis ) { + } - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); + return _gl.LINEAR; - return this; + } - }, + // - makeBasis: function ( xAxis, yAxis, zAxis ) { + function onTextureDispose( event ) { - this.set( - xAxis.x, yAxis.x, zAxis.x, 0, - xAxis.y, yAxis.y, zAxis.y, 0, - xAxis.z, yAxis.z, zAxis.z, 0, - 0, 0, 0, 1 - ); + var texture = event.target; - return this; + texture.removeEventListener( 'dispose', onTextureDispose ); - }, + deallocateTexture( texture ); - extractRotation: function () { + _infoMemory.textures --; - var v1; - return function extractRotation( m ) { + } - if ( v1 === undefined ) v1 = new THREE.Vector3(); + function onRenderTargetDispose( event ) { - var te = this.elements; - var me = m.elements; + var renderTarget = event.target; - var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); - var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); - var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; + deallocateRenderTarget( renderTarget ); - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; + _infoMemory.textures --; - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; + } - return this; + // - }; + function deallocateTexture( texture ) { - }(), + var textureProperties = properties.get( texture ); - makeRotationFromEuler: function ( euler ) { + if ( texture.image && textureProperties.__image__webglTextureCube ) { - if ( euler instanceof THREE.Euler === false ) { + // cube texture - console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + _gl.deleteTexture( textureProperties.__image__webglTextureCube ); - } + } else { - var te = this.elements; + // 2D texture - var x = euler.x, y = euler.y, z = euler.z; - var a = Math.cos( x ), b = Math.sin( x ); - var c = Math.cos( y ), d = Math.sin( y ); - var e = Math.cos( z ), f = Math.sin( z ); + if ( textureProperties.__webglInit === undefined ) return; - if ( euler.order === 'XYZ' ) { + _gl.deleteTexture( textureProperties.__webglTexture ); - var ae = a * e, af = a * f, be = b * e, bf = b * f; + } - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; + // remove all webgl properties + properties.delete( texture ); - te[ 1 ] = af + be * d; - te[ 5 ] = ae - bf * d; - te[ 9 ] = - b * c; + } - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; + function deallocateRenderTarget( renderTarget ) { - } else if ( euler.order === 'YXZ' ) { + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - var ce = c * e, cf = c * f, de = d * e, df = d * f; + if ( ! renderTarget ) return; - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; + if ( textureProperties.__webglTexture !== undefined ) { - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; + _gl.deleteTexture( textureProperties.__webglTexture ); - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; + } - } else if ( euler.order === 'ZXY' ) { + if ( renderTarget.depthTexture ) { - var ce = c * e, cf = c * f, de = d * e, df = d * f; + renderTarget.depthTexture.dispose(); - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; + } - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; + if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) { - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; + for ( var i = 0; i < 6; i ++ ) { - } else if ( euler.order === 'ZYX' ) { + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); - var ae = a * e, af = a * f, be = b * e, bf = b * f; + } - te[ 0 ] = c * e; - te[ 4 ] = be * d - af; - te[ 8 ] = ae * d + bf; + } else { - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; + } - } else if ( euler.order === 'YZX' ) { + properties.delete( renderTarget.texture ); + properties.delete( renderTarget ); - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + } - te[ 0 ] = c * e; - te[ 4 ] = bd - ac * f; - te[ 8 ] = bc * f + ad; + // - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; - } else if ( euler.order === 'XZY' ) { + function setTexture2D( texture, slot ) { - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + var textureProperties = properties.get( texture ); - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; + var image = texture.image; - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; + if ( image === undefined ) { - } + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + } else if ( image.complete === false ) { - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); - return this; + } else { - }, + uploadTexture( textureProperties, texture, slot ); + return; - makeRotationFromQuaternion: function ( q ) { + } - var te = this.elements; + } - var x = q.x, y = q.y, z = q.z, w = q.w; - var x2 = x + x, y2 = y + y, z2 = z + z; - var xx = x * x2, xy = x * y2, xz = x * z2; - var yy = y * y2, yz = y * z2, zz = z * z2; - var wx = w * x2, wy = w * y2, wz = w * z2; + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - te[ 0 ] = 1 - ( yy + zz ); - te[ 4 ] = xy - wz; - te[ 8 ] = xz + wy; + } - te[ 1 ] = xy + wz; - te[ 5 ] = 1 - ( xx + zz ); - te[ 9 ] = yz - wx; + function setTextureCube ( texture, slot ) { - te[ 2 ] = xz - wy; - te[ 6 ] = yz + wx; - te[ 10 ] = 1 - ( xx + yy ); + var textureProperties = properties.get( texture ); - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + if ( texture.image.length === 6 ) { - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - return this; + if ( ! textureProperties.__image__webglTextureCube ) { - }, + texture.addEventListener( 'dispose', onTextureDispose ); - lookAt: function () { + textureProperties.__image__webglTextureCube = _gl.createTexture(); - var x, y, z; + _infoMemory.textures ++; - return function lookAt( eye, target, up ) { + } - if ( x === undefined ) { + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - x = new THREE.Vector3(); - y = new THREE.Vector3(); - z = new THREE.Vector3(); + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - } + var isCompressed = (texture && texture.isCompressedTexture); + var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture); - var te = this.elements; + var cubeImage = []; - z.subVectors( eye, target ).normalize(); + for ( var i = 0; i < 6; i ++ ) { - if ( z.lengthSq() === 0 ) { + if ( ! isCompressed && ! isDataTexture ) { - z.z = 1; + cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); - } + } else { - x.crossVectors( up, z ).normalize(); + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; - if ( x.lengthSq() === 0 ) { + } - z.z += 0.0001; - x.crossVectors( up, z ).normalize(); + } - } + var image = cubeImage[ 0 ], + isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - y.crossVectors( z, x ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); + for ( var i = 0; i < 6; i ++ ) { - te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x; - te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y; - te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z; + if ( ! isCompressed ) { - return this; + if ( isDataTexture ) { - }; + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); - }(), + } else { - multiply: function ( m, n ) { + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); - if ( n !== undefined ) { + } - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); + } else { - } + var mipmap, mipmaps = cubeImage[ i ].mipmaps; - return this.multiplyMatrices( this, m ); + for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { - }, + mipmap = mipmaps[ j ]; - premultiply: function ( m ) { + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - return this.multiplyMatrices( m, this ); + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - }, + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - multiplyMatrices: function ( a, b ) { + } else { - var ae = a.elements; - var be = b.elements; - var te = this.elements; + console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" ); - var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; - var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; - var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; - var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + } - var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; - var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; - var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; - var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; + } else { - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + } - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + } - te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + } - return this; + } - }, + if ( texture.generateMipmaps && isPowerOfTwoImage ) { - multiplyToArray: function ( a, b, r ) { + _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - var te = this.elements; + } - this.multiplyMatrices( a, b ); + textureProperties.__version = texture.version; - r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ]; - r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ]; - r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ]; - r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ]; + if ( texture.onUpdate ) texture.onUpdate( texture ); - return this; + } else { - }, + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - multiplyScalar: function ( s ) { + } - var te = this.elements; + } - te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; - te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; - te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; - te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; + } - return this; + function setTextureCubeDynamic ( texture, slot ) { - }, + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); - applyToVector3Array: function () { + } - var v1; + function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) { - return function applyToVector3Array( array, offset, length ) { + var extension; - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + if ( isPowerOfTwoImage ) { - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); - v1.fromArray( array, j ); - v1.applyMatrix4( this ); - v1.toArray( array, j ); + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); - } + } else { - return array; + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - }; + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { - }(), + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); - applyToBuffer: function () { + } - var v1; + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); - return function applyToBuffer( buffer, offset, length ) { + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = buffer.length / buffer.itemSize; + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); - for ( var i = 0, j = offset; i < length; i ++, j ++ ) { + } - v1.x = buffer.getX( j ); - v1.y = buffer.getY( j ); - v1.z = buffer.getZ( j ); + } - v1.applyMatrix4( this ); + extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - buffer.setXYZ( v1.x, v1.y, v1.z ); + if ( extension ) { - } + if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; + if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; - return buffer; + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { - }; + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; - }(), + } - determinant: function () { + } - var te = this.elements; + } - var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; - var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; - var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; - var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + function uploadTexture( textureProperties, texture, slot ) { - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + if ( textureProperties.__webglInit === undefined ) { - return ( - n41 * ( - + n14 * n23 * n32 - - n13 * n24 * n32 - - n14 * n22 * n33 - + n12 * n24 * n33 - + n13 * n22 * n34 - - n12 * n23 * n34 - ) + - n42 * ( - + n11 * n23 * n34 - - n11 * n24 * n33 - + n14 * n21 * n33 - - n13 * n21 * n34 - + n13 * n24 * n31 - - n14 * n23 * n31 - ) + - n43 * ( - + n11 * n24 * n32 - - n11 * n22 * n34 - - n14 * n21 * n32 - + n12 * n21 * n34 - + n14 * n22 * n31 - - n12 * n24 * n31 - ) + - n44 * ( - - n13 * n22 * n31 - - n11 * n23 * n32 - + n11 * n22 * n33 - + n13 * n21 * n32 - - n12 * n21 * n33 - + n12 * n23 * n31 - ) + textureProperties.__webglInit = true; - ); + texture.addEventListener( 'dispose', onTextureDispose ); - }, + textureProperties.__webglTexture = _gl.createTexture(); - transpose: function () { + _infoMemory.textures ++; - var te = this.elements; - var tmp; + } - tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; - tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; - tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; - tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; - tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); - return this; + var image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); - }, + if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { - flattenToArrayOffset: function ( array, offset ) { + image = makePowerOfTwo( image ); - console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + - "- just use .toArray instead." ); + } - return this.toArray( array, offset ); + var isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - }, + setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); - getPosition: function () { + var mipmap, mipmaps = texture.mipmaps; - var v1; + if ( (texture && texture.isDepthTexture) ) { - return function getPosition() { + // populate depth texture with dummy data - if ( v1 === undefined ) v1 = new THREE.Vector3(); - console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); + var internalFormat = _gl.DEPTH_COMPONENT; - return v1.setFromMatrixColumn( this, 3 ); + if ( texture.type === FloatType ) { - }; + if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); + internalFormat = _gl.DEPTH_COMPONENT32F; - }(), + } else if ( _isWebGL2 ) { - setPosition: function ( v ) { + // WebGL 2.0 requires signed internalformat for glTexImage2D + internalFormat = _gl.DEPTH_COMPONENT16; - var te = this.elements; + } - te[ 12 ] = v.x; - te[ 13 ] = v.y; - te[ 14 ] = v.z; + state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); - return this; + } else if ( (texture && texture.isDataTexture) ) { - }, + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - getInverse: function ( m, throwOnDegenerate ) { + if ( mipmaps.length > 0 && isPowerOfTwoImage ) { - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - var te = this.elements, - me = m.elements, + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], - n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], - n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], - n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, - t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, - t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, - t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + } - var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + texture.generateMipmaps = false; - if ( det === 0 ) { + } else { - var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); - if ( throwOnDegenerate || false ) { + } - throw new Error( msg ); + } else if ( (texture && texture.isCompressedTexture) ) { - } else { + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - console.warn( msg ); + mipmap = mipmaps[ i ]; - } + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - return this.identity(); + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - } - - var detInv = 1 / det; + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; - te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; - te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; + } else { - te[ 4 ] = t12 * detInv; - te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; - te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; - te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; + console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); - te[ 8 ] = t13 * detInv; - te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; - te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; - te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; + } - te[ 12 ] = t14 * detInv; - te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; - te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; - te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; + } else { - return this; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - }, + } - scale: function ( v ) { + } - var te = this.elements; - var x = v.x, y = v.y, z = v.z; + } else { - te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; - te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; - te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; - te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; + // regular Texture (image, video, canvas) - return this; + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - }, + if ( mipmaps.length > 0 && isPowerOfTwoImage ) { - getMaxScaleOnAxis: function () { + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - var te = this.elements; + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); - var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; - var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; - var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + } - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + texture.generateMipmaps = false; - }, + } else { - makeTranslation: function ( x, y, z ) { + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); - this.set( + } - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 + } - ); + if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D ); - return this; + textureProperties.__version = texture.version; - }, + if ( texture.onUpdate ) texture.onUpdate( texture ); - makeRotationX: function ( theta ) { + } - var c = Math.cos( theta ), s = Math.sin( theta ); + // Render targets - this.set( + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) { - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 + var glFormat = paramThreeToGL( renderTarget.texture.format ); + var glType = paramThreeToGL( renderTarget.texture.type ); + state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - ); + } - return this; + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage ( renderbuffer, renderTarget ) { - }, + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); - makeRotationY: function ( theta ) { + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - var c = Math.cos( theta ), s = Math.sin( theta ); + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - this.set( + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - ); + } else { - return this; + // FIXME: We don't support !depth !stencil + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); - }, + } - makeRotationZ: function ( theta ) { + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); - var c = Math.cos( theta ), s = Math.sin( theta ); + } - this.set( + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture ( framebuffer, renderTarget ) { - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); - ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - return this; + if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) { - }, + throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); - makeRotationAxis: function ( axis, angle ) { + } - // Based on http://www.gamedev.net/reference/articles/article1199.asp + // upload an empty depth texture with framebuffer size + if ( !properties.get( renderTarget.depthTexture ).__webglTexture || + renderTarget.depthTexture.image.width !== renderTarget.width || + renderTarget.depthTexture.image.height !== renderTarget.height ) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } - var c = Math.cos( angle ); - var s = Math.sin( angle ); - var t = 1 - c; - var x = axis.x, y = axis.y, z = axis.z; - var tx = t * x, ty = t * y; + setTexture2D( renderTarget.depthTexture, 0 ); - this.set( + var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); - tx * x + c, tx * y - s * z, tx * z + s * y, 0, - tx * y + s * z, ty * y + c, ty * z - s * x, 0, - tx * z - s * y, ty * z + s * x, t * z * z + c, 0, - 0, 0, 0, 1 + } - ); + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { - return this; + var renderTargetProperties = properties.get( renderTarget ); - }, + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); - makeScale: function ( x, y, z ) { + if ( renderTarget.depthTexture ) { - this.set( + if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets'); - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); - ); + } else { - return this; + if ( isCube ) { - }, + renderTargetProperties.__webglDepthbuffer = []; - compose: function ( position, quaternion, scale ) { + for ( var i = 0; i < 6; i ++ ) { - this.makeRotationFromQuaternion( quaternion ); - this.scale( scale ); - this.setPosition( position ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); - return this; + } - }, + } else { - decompose: function () { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); - var vector, matrix; + } - return function decompose( position, quaternion, scale ) { + } - if ( vector === undefined ) { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - vector = new THREE.Vector3(); - matrix = new THREE.Matrix4(); + } - } + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { - var te = this.elements; + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); - var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); - var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - // if determine is negative, we need to invert one scale - var det = this.determinant(); - if ( det < 0 ) { + textureProperties.__webglTexture = _gl.createTexture(); - sx = - sx; + _infoMemory.textures ++; - } + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; + // Setup framebuffer - // scale the rotation part + if ( isCube ) { - matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() + renderTargetProperties.__webglFramebuffer = []; - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; + for ( var i = 0; i < 6; i ++ ) { - matrix.elements[ 0 ] *= invSX; - matrix.elements[ 1 ] *= invSX; - matrix.elements[ 2 ] *= invSX; + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - matrix.elements[ 4 ] *= invSY; - matrix.elements[ 5 ] *= invSY; - matrix.elements[ 6 ] *= invSY; + } - matrix.elements[ 8 ] *= invSZ; - matrix.elements[ 9 ] *= invSZ; - matrix.elements[ 10 ] *= invSZ; + } else { - quaternion.setFromRotationMatrix( matrix ); + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); - scale.x = sx; - scale.y = sy; - scale.z = sz; + } - return this; + // Setup color buffer - }; + if ( isCube ) { - }(), + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); - makeFrustum: function ( left, right, bottom, top, near, far ) { + for ( var i = 0; i < 6; i ++ ) { - var te = this.elements; - var x = 2 * near / ( right - left ); - var y = 2 * near / ( top - bottom ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); - var a = ( right + left ) / ( right - left ); - var b = ( top + bottom ) / ( top - bottom ); - var c = - ( far + near ) / ( far - near ); - var d = - 2 * far * near / ( far - near ); + } - te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; - te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; + if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); - return this; + } else { - }, + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); - makePerspective: function ( fov, aspect, near, far ) { + if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); + state.bindTexture( _gl.TEXTURE_2D, null ); - var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 ); - var ymin = - ymax; - var xmin = ymin * aspect; - var xmax = ymax * aspect; + } - return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); + // Setup depth and stencil buffers - }, + if ( renderTarget.depthBuffer ) { - makeOrthographic: function ( left, right, top, bottom, near, far ) { + setupDepthRenderbuffer( renderTarget ); - var te = this.elements; - var w = 1.0 / ( right - left ); - var h = 1.0 / ( top - bottom ); - var p = 1.0 / ( far - near ); + } - var x = ( right + left ) * w; - var y = ( top + bottom ) * h; - var z = ( far + near ) * p; + } - te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; - te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; + function updateRenderTargetMipmap( renderTarget ) { - return this; + var texture = renderTarget.texture; - }, + if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && + texture.minFilter !== NearestFilter && + texture.minFilter !== LinearFilter ) { - equals: function ( matrix ) { + var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + var webglTexture = properties.get( texture ).__webglTexture; - var te = this.elements; - var me = matrix.elements; + state.bindTexture( target, webglTexture ); + _gl.generateMipmap( target ); + state.bindTexture( target, null ); - for ( var i = 0; i < 16; i ++ ) { + } - if ( te[ i ] !== me[ i ] ) return false; + } - } + this.setTexture2D = setTexture2D; + this.setTextureCube = setTextureCube; + this.setTextureCubeDynamic = setTextureCubeDynamic; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; - return true; + }; - }, + /** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author philogb / http://blog.thejit.org/ + * @author mikael emtinger / http://gomo.se/ + * @author egraether / http://egraether.com/ + * @author WestLangley / http://github.com/WestLangley + */ - fromArray: function ( array ) { + function Vector4 ( x, y, z, w ) { + this.isVector4 = true; - this.elements.set( array ); + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = ( w !== undefined ) ? w : 1; - return this; + }; - }, + Vector4.prototype = { - toArray: function ( array, offset ) { + constructor: Vector4, - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + set: function ( x, y, z, w ) { - var te = this.elements; + this.x = x; + this.y = y; + this.z = z; + this.w = w; - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; + return this; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; + }, - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; + setScalar: function ( scalar ) { - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; - return array; + return this; - } + }, -}; + setX: function ( x ) { -// File:src/math/Ray.js + this.x = x; -/** - * @author bhouston / http://clara.io - */ + return this; -THREE.Ray = function ( origin, direction ) { + }, - this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3(); - this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3(); + setY: function ( y ) { -}; + this.y = y; -THREE.Ray.prototype = { + return this; - constructor: THREE.Ray, + }, - set: function ( origin, direction ) { + setZ: function ( z ) { - this.origin.copy( origin ); - this.direction.copy( direction ); + this.z = z; - return this; + return this; - }, + }, - clone: function () { + setW: function ( w ) { - return new this.constructor().copy( this ); + this.w = w; - }, + return this; - copy: function ( ray ) { + }, - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); + setComponent: function ( index, value ) { - return this; + switch ( index ) { - }, + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + case 3: this.w = value; break; + default: throw new Error( 'index is out of range: ' + index ); - at: function ( t, optionalTarget ) { + } - var result = optionalTarget || new THREE.Vector3(); + }, - return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + getComponent: function ( index ) { - }, + switch ( index ) { - lookAt: function ( v ) { + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + case 3: return this.w; + default: throw new Error( 'index is out of range: ' + index ); - this.direction.copy( v ).sub( this.origin ).normalize(); + } - return this; + }, - }, + clone: function () { - recast: function () { + return new this.constructor( this.x, this.y, this.z, this.w ); - var v1 = new THREE.Vector3(); + }, - return function recast( t ) { + copy: function ( v ) { - this.origin.copy( this.at( t, v1 ) ); + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; - return this; + return this; - }; + }, - }(), + add: function ( v, w ) { - closestPointToPoint: function ( point, optionalTarget ) { + if ( w !== undefined ) { - var result = optionalTarget || new THREE.Vector3(); - result.subVectors( point, this.origin ); - var directionDistance = result.dot( this.direction ); + console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - if ( directionDistance < 0 ) { + } - return result.copy( this.origin ); + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; - } + return this; - return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + }, - }, + addScalar: function ( s ) { - distanceToPoint: function ( point ) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; - return Math.sqrt( this.distanceSqToPoint( point ) ); + return this; - }, + }, - distanceSqToPoint: function () { + addVectors: function ( a, b ) { - var v1 = new THREE.Vector3(); + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; - return function distanceSqToPoint( point ) { + return this; - var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); + }, - // point behind the ray + addScaledVector: function ( v, s ) { - if ( directionDistance < 0 ) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; - return this.origin.distanceToSquared( point ); + return this; - } + }, - v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + sub: function ( v, w ) { - return v1.distanceToSquared( point ); + if ( w !== undefined ) { - }; + console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - }(), + } - distanceSqToSegment: function () { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; - var segCenter = new THREE.Vector3(); - var segDir = new THREE.Vector3(); - var diff = new THREE.Vector3(); + return this; - return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + }, - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h - // It returns the min distance between the ray and the segment - // defined by v0 and v1 - // It can also set two optional targets : - // - The closest point on the ray - // - The closest point on the segment + subScalar: function ( s ) { - segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); - segDir.copy( v1 ).sub( v0 ).normalize(); - diff.copy( this.origin ).sub( segCenter ); + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; - var segExtent = v0.distanceTo( v1 ) * 0.5; - var a01 = - this.direction.dot( segDir ); - var b0 = diff.dot( this.direction ); - var b1 = - diff.dot( segDir ); - var c = diff.lengthSq(); - var det = Math.abs( 1 - a01 * a01 ); - var s0, s1, sqrDist, extDet; + return this; - if ( det > 0 ) { + }, - // The ray and segment are not parallel. + subVectors: function ( a, b ) { - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; - if ( s0 >= 0 ) { + return this; - if ( s1 >= - extDet ) { + }, - if ( s1 <= extDet ) { + multiplyScalar: function ( scalar ) { - // region 0 - // Minimum at interior points of ray and segment. + if ( isFinite( scalar ) ) { - var invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; - } else { + } else { - // region 1 + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + } - } + return this; - } else { + }, - // region 5 + applyMatrix4: function ( m ) { - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + var x = this.x, y = this.y, z = this.z, w = this.w; + var e = m.elements; - } + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; + this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; - } else { + return this; - if ( s1 <= - extDet ) { + }, - // region 4 + divideScalar: function ( scalar ) { - s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + return this.multiplyScalar( 1 / scalar ); - } else if ( s1 <= extDet ) { + }, - // region 3 + setAxisAngleFromQuaternion: function ( q ) { - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - } else { + // q is assumed to be normalized - // region 2 + this.w = 2 * Math.acos( q.w ); - s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + var s = Math.sqrt( 1 - q.w * q.w ); - } + if ( s < 0.0001 ) { - } + this.x = 1; + this.y = 0; + this.z = 0; - } else { + } else { - // Ray and segment are parallel. + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + } - } + return this; - if ( optionalPointOnRay ) { + }, - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + setAxisAngleFromRotationMatrix: function ( m ) { - } + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - if ( optionalPointOnSegment ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); + var angle, x, y, z, // variables for result + epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - } + te = m.elements, - return sqrDist; + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - }; + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { - }(), + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms - intersectSphere: function () { + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && + ( Math.abs( m13 + m31 ) < epsilon2 ) && + ( Math.abs( m23 + m32 ) < epsilon2 ) && + ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - var v1 = new THREE.Vector3(); + // this singularity is identity matrix so angle = 0 - return function intersectSphere( sphere, optionalTarget ) { + this.set( 1, 0, 0, 0 ); - v1.subVectors( sphere.center, this.origin ); - var tca = v1.dot( this.direction ); - var d2 = v1.dot( v1 ) - tca * tca; - var radius2 = sphere.radius * sphere.radius; + return this; // zero angle, arbitrary axis - if ( d2 > radius2 ) return null; + } - var thc = Math.sqrt( radius2 - d2 ); + // otherwise this singularity is angle = 180 - // t0 = first intersect point - entrance on front of sphere - var t0 = tca - thc; + angle = Math.PI; - // t1 = second intersect point - exit point on back of sphere - var t1 = tca + thc; + var xx = ( m11 + 1 ) / 2; + var yy = ( m22 + 1 ) / 2; + var zz = ( m33 + 1 ) / 2; + var xy = ( m12 + m21 ) / 4; + var xz = ( m13 + m31 ) / 4; + var yz = ( m23 + m32 ) / 4; - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) return null; + if ( ( xx > yy ) && ( xx > zz ) ) { - // test to see if t0 is behind the ray: - // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, - // in order to always return an intersect point that is in front of the ray. - if ( t0 < 0 ) return this.at( t1, optionalTarget ); + // m11 is the largest diagonal term - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, optionalTarget ); + if ( xx < epsilon ) { - }; + x = 0; + y = 0.707106781; + z = 0.707106781; - }(), + } else { - intersectsSphere: function ( sphere ) { + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; - return this.distanceToPoint( sphere.center ) <= sphere.radius; + } - }, + } else if ( yy > zz ) { - distanceToPlane: function ( plane ) { + // m22 is the largest diagonal term - var denominator = plane.normal.dot( this.direction ); + if ( yy < epsilon ) { - if ( denominator === 0 ) { + x = 0.707106781; + y = 0; + z = 0.707106781; - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { + } else { - return 0; + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; - } + } - // Null is preferable to undefined since undefined means.... it is undefined + } else { - return null; + // m33 is the largest diagonal term so base result on this - } + if ( zz < epsilon ) { - var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + x = 0.707106781; + y = 0.707106781; + z = 0; - // Return if the ray never intersects the plane + } else { - return t >= 0 ? t : null; + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; - }, + } - intersectPlane: function ( plane, optionalTarget ) { + } - var t = this.distanceToPlane( plane ); + this.set( x, y, z, angle ); - if ( t === null ) { + return this; // return 180 deg rotation - return null; + } - } + // as we have reached here there are no singularities so we can handle normally - return this.at( t, optionalTarget ); + var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - }, + if ( Math.abs( s ) < 0.001 ) s = 1; + // prevent divide by zero, should not happen if matrix is orthogonal and should be + // caught by singularity test above, but I've left it in just in case + this.x = ( m32 - m23 ) / s; + this.y = ( m13 - m31 ) / s; + this.z = ( m21 - m12 ) / s; + this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); - intersectsPlane: function ( plane ) { + return this; - // check if the ray lies on the plane first + }, - var distToPoint = plane.distanceToPoint( this.origin ); + min: function ( v ) { - if ( distToPoint === 0 ) { + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + this.w = Math.min( this.w, v.w ); - return true; + return this; - } + }, - var denominator = plane.normal.dot( this.direction ); + max: function ( v ) { - if ( denominator * distToPoint < 0 ) { + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); + this.w = Math.max( this.w, v.w ); - return true; + return this; - } + }, - // ray origin is behind the plane (and is pointing behind it) + clamp: function ( min, max ) { - return false; + // This function assumes min < max, if this assumption isn't true it will not operate correctly - }, + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + this.w = Math.max( min.w, Math.min( max.w, this.w ) ); - intersectBox: function ( box, optionalTarget ) { + return this; - var tmin, tmax, tymin, tymax, tzmin, tzmax; + }, - var invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; + clampScalar: function () { - var origin = this.origin; + var min, max; - if ( invdirx >= 0 ) { + return function clampScalar( minVal, maxVal ) { - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; + if ( min === undefined ) { - } else { + min = new Vector4(); + max = new Vector4(); - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; + } - } + min.set( minVal, minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal, maxVal ); - if ( invdiry >= 0 ) { + return this.clamp( min, max ); - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; + }; - } else { + }(), - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; + floor: function () { - } + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + this.w = Math.floor( this.w ); - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + return this; - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN + }, - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; + ceil: function () { - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + this.w = Math.ceil( this.w ); - if ( invdirz >= 0 ) { + return this; - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; + }, - } else { + round: function () { - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + this.w = Math.round( this.w ); - } + return this; - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + }, - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + roundToZero: function () { - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - //return point closest to the ray (positive side) + return this; - if ( tmax < 0 ) return null; + }, - return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); + negate: function () { - }, + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; - intersectsBox: ( function () { + return this; - var v = new THREE.Vector3(); + }, - return function intersectsBox( box ) { + dot: function ( v ) { - return this.intersectBox( box, v ) !== null; + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - }; + }, - } )(), + lengthSq: function () { - intersectTriangle: function () { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - // Compute the offset origin, edges, and normal. - var diff = new THREE.Vector3(); - var edge1 = new THREE.Vector3(); - var edge2 = new THREE.Vector3(); - var normal = new THREE.Vector3(); + }, - return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { + length: function () { - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - edge1.subVectors( b, a ); - edge2.subVectors( c, a ); - normal.crossVectors( edge1, edge2 ); + }, - // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, - // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by - // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) - // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) - // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) - var DdN = this.direction.dot( normal ); - var sign; + lengthManhattan: function () { - if ( DdN > 0 ) { + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - if ( backfaceCulling ) return null; - sign = 1; + }, - } else if ( DdN < 0 ) { + normalize: function () { - sign = - 1; - DdN = - DdN; + return this.divideScalar( this.length() ); - } else { + }, - return null; + setLength: function ( length ) { - } + return this.multiplyScalar( length / this.length() ); - diff.subVectors( this.origin, a ); - var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); + }, - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { + lerp: function ( v, alpha ) { - return null; + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + this.w += ( v.w - this.w ) * alpha; - } + return this; - var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); + }, - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { + lerpVectors: function ( v1, v2, alpha ) { - return null; + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - } + }, - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { + equals: function ( v ) { - return null; + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - } + }, - // Line intersects triangle, check if ray does. - var QdN = - sign * diff.dot( normal ); + fromArray: function ( array, offset ) { - // t < 0, no intersection - if ( QdN < 0 ) { + if ( offset === undefined ) offset = 0; - return null; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; - } + return this; - // Ray intersects triangle. - return this.at( QdN / DdN, optionalTarget ); + }, - }; + toArray: function ( array, offset ) { - }(), + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - applyMatrix4: function ( matrix4 ) { + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; - this.direction.add( this.origin ).applyMatrix4( matrix4 ); - this.origin.applyMatrix4( matrix4 ); - this.direction.sub( this.origin ); - this.direction.normalize(); + return array; - return this; + }, - }, + fromAttribute: function ( attribute, index, offset ) { - equals: function ( ray ) { + if ( offset === undefined ) offset = 0; - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + index = index * attribute.itemSize + offset; - } + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; + this.w = attribute.array[ index + 3 ]; -}; + return this; -// File:src/math/Sphere.js + } -/** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + }; -THREE.Sphere = function ( center, radius ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.center = ( center !== undefined ) ? center : new THREE.Vector3(); - this.radius = ( radius !== undefined ) ? radius : 0; + function WebGLState ( gl, extensions, paramThreeToGL ) { + this.isWebGLState = true; -}; + var _this = this; -THREE.Sphere.prototype = { + this.buffers = { + color: new WebGLColorBuffer( gl, this ), + depth: new WebGLDepthBuffer( gl, this ), + stencil: new WebGLStencilBuffer( gl, this ) + }; - constructor: THREE.Sphere, + var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + var newAttributes = new Uint8Array( maxVertexAttributes ); + var enabledAttributes = new Uint8Array( maxVertexAttributes ); + var attributeDivisors = new Uint8Array( maxVertexAttributes ); - set: function ( center, radius ) { + var capabilities = {}; - this.center.copy( center ); - this.radius = radius; + var compressedTextureFormats = null; - return this; + var currentBlending = null; + var currentBlendEquation = null; + var currentBlendSrc = null; + var currentBlendDst = null; + var currentBlendEquationAlpha = null; + var currentBlendSrcAlpha = null; + var currentBlendDstAlpha = null; + var currentPremultipledAlpha = false; - }, + var currentFlipSided = null; + var currentCullFace = null; - setFromPoints: function () { + var currentLineWidth = null; - var box = new THREE.Box3(); + var currentPolygonOffsetFactor = null; + var currentPolygonOffsetUnits = null; - return function setFromPoints( points, optionalCenter ) { + var currentScissorTest = null; - var center = this.center; + var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); - if ( optionalCenter !== undefined ) { + var currentTextureSlot = null; + var currentBoundTextures = {}; - center.copy( optionalCenter ); + var currentScissor = new Vector4(); + var currentViewport = new Vector4(); - } else { + function createTexture( type, target, count ) { - box.setFromPoints( points ).center( center ); + var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + var texture = gl.createTexture(); - } + gl.bindTexture( type, texture ); + gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - var maxRadiusSq = 0; + for ( var i = 0; i < count; i ++ ) { - for ( var i = 0, il = points.length; i < il; i ++ ) { + gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + } - } + return texture; - this.radius = Math.sqrt( maxRadiusSq ); + } - return this; + var emptyTextures = {}; + emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 ); + emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 ); - }; + // - }(), + this.init = function () { - clone: function () { + this.clearColor( 0, 0, 0, 1 ); + this.clearDepth( 1 ); + this.clearStencil( 0 ); - return new this.constructor().copy( this ); + this.enable( gl.DEPTH_TEST ); + this.setDepthFunc( LessEqualDepth ); - }, + this.setFlipSided( false ); + this.setCullFace( CullFaceBack ); + this.enable( gl.CULL_FACE ); - copy: function ( sphere ) { + this.enable( gl.BLEND ); + this.setBlending( NormalBlending ); - this.center.copy( sphere.center ); - this.radius = sphere.radius; + }; - return this; + this.initAttributes = function () { - }, + for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { - empty: function () { + newAttributes[ i ] = 0; - return ( this.radius <= 0 ); + } - }, + }; - containsPoint: function ( point ) { + this.enableAttribute = function ( attribute ) { - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + newAttributes[ attribute ] = 1; - }, + if ( enabledAttributes[ attribute ] === 0 ) { - distanceToPoint: function ( point ) { + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; - return ( point.distanceTo( this.center ) - this.radius ); + } - }, + if ( attributeDivisors[ attribute ] !== 0 ) { - intersectsSphere: function ( sphere ) { + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - var radiusSum = this.radius + sphere.radius; + extension.vertexAttribDivisorANGLE( attribute, 0 ); + attributeDivisors[ attribute ] = 0; - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + } - }, + }; - intersectsBox: function ( box ) { + this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) { - return box.intersectsSphere( this ); + newAttributes[ attribute ] = 1; - }, + if ( enabledAttributes[ attribute ] === 0 ) { - intersectsPlane: function ( plane ) { + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; - // We use the following equation to compute the signed distance from - // the center of the sphere to the plane. - // - // distance = q * n - d - // - // If this distance is greater than the radius of the sphere, - // then there is no intersection. + } - return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { - }, + extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; - clampPoint: function ( point, optionalTarget ) { + } - var deltaLengthSq = this.center.distanceToSquared( point ); + }; - var result = optionalTarget || new THREE.Vector3(); + this.disableUnusedAttributes = function () { - result.copy( point ); + for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { - if ( deltaLengthSq > ( this.radius * this.radius ) ) { + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { - result.sub( this.center ).normalize(); - result.multiplyScalar( this.radius ).add( this.center ); + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; - } + } - return result; + } - }, + }; - getBoundingBox: function ( optionalTarget ) { + this.enable = function ( id ) { - var box = optionalTarget || new THREE.Box3(); + if ( capabilities[ id ] !== true ) { - box.set( this.center, this.center ); - box.expandByScalar( this.radius ); + gl.enable( id ); + capabilities[ id ] = true; - return box; + } - }, + }; - applyMatrix4: function ( matrix ) { + this.disable = function ( id ) { - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); + if ( capabilities[ id ] !== false ) { - return this; + gl.disable( id ); + capabilities[ id ] = false; - }, + } - translate: function ( offset ) { + }; - this.center.add( offset ); + this.getCompressedTextureFormats = function () { - return this; + if ( compressedTextureFormats === null ) { - }, + compressedTextureFormats = []; - equals: function ( sphere ) { + if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || + extensions.get( 'WEBGL_compressed_texture_s3tc' ) || + extensions.get( 'WEBGL_compressed_texture_etc1' ) ) { - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS ); - } + for ( var i = 0; i < formats.length; i ++ ) { -}; + compressedTextureFormats.push( formats[ i ] ); -// File:src/math/Frustum.js + } -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / http://clara.io - */ + } -THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) { + } - this.planes = [ + return compressedTextureFormats; - ( p0 !== undefined ) ? p0 : new THREE.Plane(), - ( p1 !== undefined ) ? p1 : new THREE.Plane(), - ( p2 !== undefined ) ? p2 : new THREE.Plane(), - ( p3 !== undefined ) ? p3 : new THREE.Plane(), - ( p4 !== undefined ) ? p4 : new THREE.Plane(), - ( p5 !== undefined ) ? p5 : new THREE.Plane() + }; - ]; + this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { -}; + if ( blending !== NoBlending ) { -THREE.Frustum.prototype = { + this.enable( gl.BLEND ); - constructor: THREE.Frustum, + } else { - set: function ( p0, p1, p2, p3, p4, p5 ) { + this.disable( gl.BLEND ); + currentBlending = blending; // no blending, that is + return; - var planes = this.planes; + } - planes[ 0 ].copy( p0 ); - planes[ 1 ].copy( p1 ); - planes[ 2 ].copy( p2 ); - planes[ 3 ].copy( p3 ); - planes[ 4 ].copy( p4 ); - planes[ 5 ].copy( p5 ); + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { - return this; + if ( blending === AdditiveBlending ) { - }, + if ( premultipliedAlpha ) { - clone: function () { + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); - return new this.constructor().copy( this ); + } else { - }, + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); - copy: function ( frustum ) { + } - var planes = this.planes; + } else if ( blending === SubtractiveBlending ) { - for ( var i = 0; i < 6; i ++ ) { + if ( premultipliedAlpha ) { - planes[ i ].copy( frustum.planes[ i ] ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); - } + } else { - return this; + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); - }, + } - setFromMatrix: function ( m ) { + } else if ( blending === MultiplyBlending ) { - var planes = this.planes; - var me = m.elements; - var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; - var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; - var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; - var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; + if ( premultipliedAlpha ) { - planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); - planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); - planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); - planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); - planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); - planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); - return this; + } else { - }, + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); - intersectsObject: function () { + } - var sphere = new THREE.Sphere(); + } else { - return function intersectsObject( object ) { + if ( premultipliedAlpha ) { - var geometry = object.geometry; + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); - if ( geometry.boundingSphere === null ) - geometry.computeBoundingSphere(); + } else { - sphere.copy( geometry.boundingSphere ) - .applyMatrix4( object.matrixWorld ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); - return this.intersectsSphere( sphere ); + } - }; + } - }(), + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; - intersectsSprite: function () { + } - var sphere = new THREE.Sphere(); + if ( blending === CustomBlending ) { - return function intersectsSprite( sprite ) { + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; - sphere.center.set( 0, 0, 0 ); - sphere.radius = 0.7071067811865476; - sphere.applyMatrix4( sprite.matrixWorld ); + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { - return this.intersectsSphere( sphere ); + gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); - }; + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; - }(), + } - intersectsSphere: function ( sphere ) { + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { - var planes = this.planes; - var center = sphere.center; - var negRadius = - sphere.radius; + gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); - for ( var i = 0; i < 6; i ++ ) { + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; - var distance = planes[ i ].distanceToPoint( center ); + } - if ( distance < negRadius ) { + } else { - return false; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; - } + } - } + }; - return true; + // TODO Deprecate - }, + this.setColorWrite = function ( colorWrite ) { - intersectsBox: function () { + this.buffers.color.setMask( colorWrite ); - var p1 = new THREE.Vector3(), - p2 = new THREE.Vector3(); + }; - return function intersectsBox( box ) { + this.setDepthTest = function ( depthTest ) { - var planes = this.planes; + this.buffers.depth.setTest( depthTest ); - for ( var i = 0; i < 6 ; i ++ ) { + }; - var plane = planes[ i ]; + this.setDepthWrite = function ( depthWrite ) { - p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; - p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; - p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; - p2.y = plane.normal.y > 0 ? box.max.y : box.min.y; - p1.z = plane.normal.z > 0 ? box.min.z : box.max.z; - p2.z = plane.normal.z > 0 ? box.max.z : box.min.z; + this.buffers.depth.setMask( depthWrite ); - var d1 = plane.distanceToPoint( p1 ); - var d2 = plane.distanceToPoint( p2 ); + }; - // if both outside plane, no intersection + this.setDepthFunc = function ( depthFunc ) { - if ( d1 < 0 && d2 < 0 ) { + this.buffers.depth.setFunc( depthFunc ); - return false; + }; - } + this.setStencilTest = function ( stencilTest ) { - } + this.buffers.stencil.setTest( stencilTest ); - return true; + }; - }; + this.setStencilWrite = function ( stencilWrite ) { - }(), + this.buffers.stencil.setMask( stencilWrite ); + }; - containsPoint: function ( point ) { + this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) { - var planes = this.planes; + this.buffers.stencil.setFunc( stencilFunc, stencilRef, stencilMask ); - for ( var i = 0; i < 6; i ++ ) { + }; - if ( planes[ i ].distanceToPoint( point ) < 0 ) { + this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) { - return false; + this.buffers.stencil.setOp( stencilFail, stencilZFail, stencilZPass ); - } + }; - } + // - return true; + this.setFlipSided = function ( flipSided ) { - } + if ( currentFlipSided !== flipSided ) { -}; + if ( flipSided ) { -// File:src/math/Plane.js + gl.frontFace( gl.CW ); -/** - * @author bhouston / http://clara.io - */ + } else { -THREE.Plane = function ( normal, constant ) { + gl.frontFace( gl.CCW ); - this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 ); - this.constant = ( constant !== undefined ) ? constant : 0; + } -}; + currentFlipSided = flipSided; -THREE.Plane.prototype = { + } - constructor: THREE.Plane, + }; - set: function ( normal, constant ) { + this.setCullFace = function ( cullFace ) { - this.normal.copy( normal ); - this.constant = constant; + if ( cullFace !== CullFaceNone ) { - return this; + this.enable( gl.CULL_FACE ); - }, + if ( cullFace !== currentCullFace ) { - setComponents: function ( x, y, z, w ) { + if ( cullFace === CullFaceBack ) { - this.normal.set( x, y, z ); - this.constant = w; + gl.cullFace( gl.BACK ); - return this; + } else if ( cullFace === CullFaceFront ) { - }, + gl.cullFace( gl.FRONT ); - setFromNormalAndCoplanarPoint: function ( normal, point ) { + } else { - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized + gl.cullFace( gl.FRONT_AND_BACK ); - return this; + } - }, + } - setFromCoplanarPoints: function () { + } else { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + this.disable( gl.CULL_FACE ); - return function setFromCoplanarPoints( a, b, c ) { + } - var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); + currentCullFace = cullFace; - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + }; - this.setFromNormalAndCoplanarPoint( normal, a ); + this.setLineWidth = function ( width ) { - return this; + if ( width !== currentLineWidth ) { - }; + gl.lineWidth( width ); - }(), + currentLineWidth = width; - clone: function () { + } - return new this.constructor().copy( this ); + }; - }, + this.setPolygonOffset = function ( polygonOffset, factor, units ) { - copy: function ( plane ) { + if ( polygonOffset ) { - this.normal.copy( plane.normal ); - this.constant = plane.constant; + this.enable( gl.POLYGON_OFFSET_FILL ); - return this; + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { - }, + gl.polygonOffset( factor, units ); - normalize: function () { + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; - // Note: will lead to a divide by zero if the plane is invalid. + } - var inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; + } else { - return this; + this.disable( gl.POLYGON_OFFSET_FILL ); - }, + } - negate: function () { + }; - this.constant *= - 1; - this.normal.negate(); + this.getScissorTest = function () { - return this; + return currentScissorTest; - }, + }; - distanceToPoint: function ( point ) { + this.setScissorTest = function ( scissorTest ) { - return this.normal.dot( point ) + this.constant; + currentScissorTest = scissorTest; - }, + if ( scissorTest ) { - distanceToSphere: function ( sphere ) { + this.enable( gl.SCISSOR_TEST ); - return this.distanceToPoint( sphere.center ) - sphere.radius; + } else { - }, + this.disable( gl.SCISSOR_TEST ); - projectPoint: function ( point, optionalTarget ) { + } - return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); + }; - }, + // texture - orthoPoint: function ( point, optionalTarget ) { + this.activeTexture = function ( webglSlot ) { - var perpendicularMagnitude = this.distanceToPoint( point ); + if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; - var result = optionalTarget || new THREE.Vector3(); - return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); + if ( currentTextureSlot !== webglSlot ) { - }, + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; - intersectLine: function () { + } - var v1 = new THREE.Vector3(); + }; - return function intersectLine( line, optionalTarget ) { + this.bindTexture = function ( webglType, webglTexture ) { - var result = optionalTarget || new THREE.Vector3(); + if ( currentTextureSlot === null ) { - var direction = line.delta( v1 ); + _this.activeTexture(); - var denominator = this.normal.dot( direction ); + } - if ( denominator === 0 ) { + var boundTexture = currentBoundTextures[ currentTextureSlot ]; - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { + if ( boundTexture === undefined ) { - return result.copy( line.start ); + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ currentTextureSlot ] = boundTexture; - } + } - // Unsure if this is the correct method to handle this case. - return undefined; + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { - } + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); - var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + boundTexture.type = webglType; + boundTexture.texture = webglTexture; - if ( t < 0 || t > 1 ) { + } - return undefined; + }; - } + this.compressedTexImage2D = function () { - return result.copy( direction ).multiplyScalar( t ).add( line.start ); + try { - }; + gl.compressedTexImage2D.apply( gl, arguments ); - }(), + } catch ( error ) { - intersectsLine: function ( line ) { + console.error( error ); - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + } - var startSign = this.distanceToPoint( line.start ); - var endSign = this.distanceToPoint( line.end ); + }; - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + this.texImage2D = function () { - }, + try { - intersectsBox: function ( box ) { + gl.texImage2D.apply( gl, arguments ); - return box.intersectsPlane( this ); + } catch ( error ) { - }, + console.error( error ); - intersectsSphere: function ( sphere ) { + } - return sphere.intersectsPlane( this ); + }; - }, + // TODO Deprecate - coplanarPoint: function ( optionalTarget ) { + this.clearColor = function ( r, g, b, a ) { - var result = optionalTarget || new THREE.Vector3(); - return result.copy( this.normal ).multiplyScalar( - this.constant ); + this.buffers.color.setClear( r, g, b, a ); - }, + }; - applyMatrix4: function () { + this.clearDepth = function ( depth ) { - var v1 = new THREE.Vector3(); - var m1 = new THREE.Matrix3(); + this.buffers.depth.setClear( depth ); - return function applyMatrix4( matrix, optionalNormalMatrix ) { + }; - var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); + this.clearStencil = function ( stencil ) { - // transform normal based on theory here: - // http://www.songho.ca/opengl/gl_normaltransform.html - var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); - var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + this.buffers.stencil.setClear( stencil ); - // recalculate constant (like in setFromNormalAndCoplanarPoint) - this.constant = - referencePoint.dot( normal ); + }; - return this; + // - }; + this.scissor = function ( scissor ) { - }(), + if ( currentScissor.equals( scissor ) === false ) { - translate: function ( offset ) { + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); - this.constant = this.constant - offset.dot( this.normal ); + } - return this; + }; - }, + this.viewport = function ( viewport ) { - equals: function ( plane ) { + if ( currentViewport.equals( viewport ) === false ) { - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); - } + } -}; + }; -// File:src/math/Spherical.js + // -/** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - * - * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system - * - * The poles (phi) are at the positive and negative y axis. - * The equator starts at positive z. - */ + this.reset = function () { -THREE.Spherical = function ( radius, phi, theta ) { + for ( var i = 0; i < enabledAttributes.length; i ++ ) { - this.radius = ( radius !== undefined ) ? radius : 1.0; - this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole - this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere + if ( enabledAttributes[ i ] === 1 ) { - return this; + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; -}; + } -THREE.Spherical.prototype = { + } - constructor: THREE.Spherical, + capabilities = {}; - set: function ( radius, phi, theta ) { + compressedTextureFormats = null; - this.radius = radius; - this.phi = phi; - this.theta = theta; + currentTextureSlot = null; + currentBoundTextures = {}; - return this; + currentBlending = null; - }, + currentFlipSided = null; + currentCullFace = null; - clone: function () { + this.buffers.color.reset(); + this.buffers.depth.reset(); + this.buffers.stencil.reset(); - return new this.constructor().copy( this ); + }; - }, + }; - copy: function ( other ) { + function WebGLColorBuffer ( gl, state ) { + this.isWebGLColorBuffer = true; - this.radius.copy( other.radius ); - this.phi.copy( other.phi ); - this.theta.copy( other.theta ); + var locked = false; - return this; + var color = new Vector4(); + var currentColorMask = null; + var currentColorClear = new Vector4(); - }, + this.setMask = function ( colorMask ) { - // restrict phi to be betwee EPS and PI-EPS - makeSafe: function() { + if ( currentColorMask !== colorMask && ! locked ) { - var EPS = 0.000001; - this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; - return this; + } - }, + }; - setFromVector3: function( vec3 ) { + this.setLocked = function ( lock ) { - this.radius = vec3.length(); + locked = lock; - if ( this.radius === 0 ) { + }; - this.theta = 0; - this.phi = 0; + this.setClear = function ( r, g, b, a ) { - } else { + color.set( r, g, b, a ); - this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis - this.phi = Math.acos( THREE.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle + if ( currentColorClear.equals( color ) === false ) { - } + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); - return this; + } - }, + }; -}; + this.reset = function () { -// File:src/math/Math.js + locked = false; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + currentColorMask = null; + currentColorClear = new Vector4(); -THREE.Math = { + }; - DEG2RAD: Math.PI / 180, - RAD2DEG: 180 / Math.PI, + }; - generateUUID: function () { + function WebGLDepthBuffer( gl, state ) { + this.isWebGLDepthBuffer = true; - // http://www.broofa.com/Tools/Math.uuid.htm + var locked = false; - var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); - var uuid = new Array( 36 ); - var rnd = 0, r; + var currentDepthMask = null; + var currentDepthFunc = null; + var currentDepthClear = null; - return function generateUUID() { + this.setTest = function ( depthTest ) { - for ( var i = 0; i < 36; i ++ ) { + if ( depthTest ) { - if ( i === 8 || i === 13 || i === 18 || i === 23 ) { + state.enable( gl.DEPTH_TEST ); - uuid[ i ] = '-'; + } else { - } else if ( i === 14 ) { + state.disable( gl.DEPTH_TEST ); - uuid[ i ] = '4'; + } - } else { + }; - if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; - r = rnd & 0xf; - rnd = rnd >> 4; - uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]; + this.setMask = function( depthMask ){ - } + if ( currentDepthMask !== depthMask && ! locked ) { - } + gl.depthMask( depthMask ); + currentDepthMask = depthMask; - return uuid.join( '' ); + } - }; + }; - }(), + this.setFunc = function ( depthFunc ) { - clamp: function ( value, min, max ) { + if ( currentDepthFunc !== depthFunc ) { - return Math.max( min, Math.min( max, value ) ); + if ( depthFunc ) { - }, + switch ( depthFunc ) { - // compute euclidian modulo of m % n - // https://en.wikipedia.org/wiki/Modulo_operation + case NeverDepth: - euclideanModulo: function ( n, m ) { + gl.depthFunc( gl.NEVER ); + break; - return ( ( n % m ) + m ) % m; + case AlwaysDepth: - }, + gl.depthFunc( gl.ALWAYS ); + break; - // Linear mapping from range to range + case LessDepth: - mapLinear: function ( x, a1, a2, b1, b2 ) { + gl.depthFunc( gl.LESS ); + break; - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + case LessEqualDepth: - }, + gl.depthFunc( gl.LEQUAL ); + break; - // http://en.wikipedia.org/wiki/Smoothstep + case EqualDepth: - smoothstep: function ( x, min, max ) { + gl.depthFunc( gl.EQUAL ); + break; - if ( x <= min ) return 0; - if ( x >= max ) return 1; + case GreaterEqualDepth: - x = ( x - min ) / ( max - min ); + gl.depthFunc( gl.GEQUAL ); + break; - return x * x * ( 3 - 2 * x ); + case GreaterDepth: - }, + gl.depthFunc( gl.GREATER ); + break; - smootherstep: function ( x, min, max ) { + case NotEqualDepth: - if ( x <= min ) return 0; - if ( x >= max ) return 1; + gl.depthFunc( gl.NOTEQUAL ); + break; - x = ( x - min ) / ( max - min ); + default: - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + gl.depthFunc( gl.LEQUAL ); - }, + } - random16: function () { + } else { - console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' ); - return Math.random(); + gl.depthFunc( gl.LEQUAL ); - }, + } - // Random integer from interval + currentDepthFunc = depthFunc; - randInt: function ( low, high ) { + } - return low + Math.floor( Math.random() * ( high - low + 1 ) ); + }; - }, + this.setLocked = function ( lock ) { - // Random float from interval + locked = lock; - randFloat: function ( low, high ) { + }; - return low + Math.random() * ( high - low ); + this.setClear = function ( depth ) { - }, + if ( currentDepthClear !== depth ) { - // Random float from <-range/2, range/2> interval + gl.clearDepth( depth ); + currentDepthClear = depth; - randFloatSpread: function ( range ) { + } - return range * ( 0.5 - Math.random() ); + }; - }, + this.reset = function () { - degToRad: function ( degrees ) { + locked = false; - return degrees * THREE.Math.DEG2RAD; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; - }, + }; - radToDeg: function ( radians ) { + }; - return radians * THREE.Math.RAD2DEG; + function WebGLStencilBuffer ( gl, state ) { + this.isWebGLStencilBuffer = true; - }, + var locked = false; - isPowerOfTwo: function ( value ) { + var currentStencilMask = null; + var currentStencilFunc = null; + var currentStencilRef = null; + var currentStencilFuncMask = null; + var currentStencilFail = null; + var currentStencilZFail = null; + var currentStencilZPass = null; + var currentStencilClear = null; - return ( value & ( value - 1 ) ) === 0 && value !== 0; + this.setTest = function ( stencilTest ) { - }, + if ( stencilTest ) { - nearestPowerOfTwo: function ( value ) { + state.enable( gl.STENCIL_TEST ); - return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); + } else { - }, + state.disable( gl.STENCIL_TEST ); - nextPowerOfTwo: function ( value ) { + } - value --; - value |= value >> 1; - value |= value >> 2; - value |= value >> 4; - value |= value >> 8; - value |= value >> 16; - value ++; + }; - return value; + this.setMask = function ( stencilMask ) { - } + if ( currentStencilMask !== stencilMask && ! locked ) { -}; + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; -// File:src/math/Spline.js + } -/** - * Spline from Tween.js, slightly optimized (and trashed) - * http://sole.github.com/tween.js/examples/05_spline.html - * - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + }; -THREE.Spline = function ( points ) { + this.setFunc = function ( stencilFunc, stencilRef, stencilMask ) { - this.points = points; + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { - var c = [], v3 = { x: 0, y: 0, z: 0 }, - point, intPoint, weight, w2, w3, - pa, pb, pc, pd; + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); - this.initFromArray = function ( a ) { + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; - this.points = []; + } - for ( var i = 0; i < a.length; i ++ ) { + }; - this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; + this.setOp = function ( stencilFail, stencilZFail, stencilZPass ) { - } + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { - }; + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); - this.getPoint = function ( k ) { + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; - point = ( this.points.length - 1 ) * k; - intPoint = Math.floor( point ); - weight = point - intPoint; + } - c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1; - c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2; + }; - pa = this.points[ c[ 0 ] ]; - pb = this.points[ c[ 1 ] ]; - pc = this.points[ c[ 2 ] ]; - pd = this.points[ c[ 3 ] ]; + this.setLocked = function ( lock ) { - w2 = weight * weight; - w3 = weight * w2; + locked = lock; - v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 ); - v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 ); - v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 ); + }; - return v3; + this.setClear = function ( stencil ) { - }; + if ( currentStencilClear !== stencil ) { - this.getControlPointsArray = function () { + gl.clearStencil( stencil ); + currentStencilClear = stencil; - var i, p, l = this.points.length, - coords = []; + } - for ( i = 0; i < l; i ++ ) { + }; - p = this.points[ i ]; - coords[ i ] = [ p.x, p.y, p.z ]; + this.reset = function () { - } + locked = false; - return coords; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; - }; + }; - // approximate length by summing linear segments + }; - this.getLength = function ( nSubDivisions ) { + /** + * @author szimek / https://github.com/szimek/ + * @author alteredq / http://alteredqualia.com/ + * @author Marius Kintel / https://github.com/kintel + */ - var i, index, nSamples, position, - point = 0, intPoint = 0, oldIntPoint = 0, - oldPosition = new THREE.Vector3(), - tmpVec = new THREE.Vector3(), - chunkLengths = [], - totalLength = 0; + /* + In options, we can specify: + * Texture parameters for an auto-generated target texture + * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers + */ + function WebGLRenderTarget ( width, height, options ) { + this.isWebGLRenderTarget = true; - // first point has 0 length + this.uuid = exports.Math.generateUUID(); - chunkLengths[ 0 ] = 0; + this.width = width; + this.height = height; - if ( ! nSubDivisions ) nSubDivisions = 100; + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; - nSamples = this.points.length * nSubDivisions; + this.viewport = new Vector4( 0, 0, width, height ); - oldPosition.copy( this.points[ 0 ] ); + options = options || {}; - for ( i = 1; i < nSamples; i ++ ) { + if ( options.minFilter === undefined ) options.minFilter = LinearFilter; - index = i / nSamples; + this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); - position = this.getPoint( index ); - tmpVec.copy( position ); + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; + this.depthTexture = null; - totalLength += tmpVec.distanceTo( oldPosition ); + }; - oldPosition.copy( position ); + Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, { - point = ( this.points.length - 1 ) * index; - intPoint = Math.floor( point ); + setSize: function ( width, height ) { - if ( intPoint !== oldIntPoint ) { + if ( this.width !== width || this.height !== height ) { - chunkLengths[ intPoint ] = totalLength; - oldIntPoint = intPoint; + this.width = width; + this.height = height; - } + this.dispose(); - } + } - // last point ends with total length + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); - chunkLengths[ chunkLengths.length ] = totalLength; + }, - return { chunks: chunkLengths, total: totalLength }; + clone: function () { - }; + return new this.constructor().copy( this ); - this.reparametrizeByArcLength = function ( samplingCoef ) { + }, - var i, j, - index, indexCurrent, indexNext, - realDistance, - sampling, position, - newpoints = [], - tmpVec = new THREE.Vector3(), - sl = this.getLength(); + copy: function ( source ) { - newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); + this.width = source.width; + this.height = source.height; - for ( i = 1; i < this.points.length; i ++ ) { + this.viewport.copy( source.viewport ); - //tmpVec.copy( this.points[ i - 1 ] ); - //linearDistance = tmpVec.distanceTo( this.points[ i ] ); + this.texture = source.texture.clone(); - realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ]; + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.depthTexture = source.depthTexture; - sampling = Math.ceil( samplingCoef * realDistance / sl.total ); + return this; - indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); - indexNext = i / ( this.points.length - 1 ); + }, - for ( j = 1; j < sampling - 1; j ++ ) { + dispose: function () { - index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); + this.dispatchEvent( { type: 'dispose' } ); - position = this.getPoint( index ); - newpoints.push( tmpVec.copy( position ).clone() ); + } - } + } ); - newpoints.push( tmpVec.copy( this.points[ i ] ).clone() ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - } + function Material () { + this.isMaterial = true; - this.points = newpoints; + Object.defineProperty( this, 'id', { value: MaterialIdCount() } ); - }; + this.uuid = exports.Math.generateUUID(); - // Catmull-Rom + this.name = ''; + this.type = 'Material'; - function interpolate( p0, p1, p2, p3, t, t2, t3 ) { + this.fog = true; + this.lights = true; - var v0 = ( p2 - p0 ) * 0.5, - v1 = ( p3 - p1 ) * 0.5; + this.blending = NormalBlending; + this.side = FrontSide; + this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading + this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors - return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; + this.opacity = 1; + this.transparent = false; - } + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; -}; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; -// File:src/math/Triangle.js + this.clippingPlanes = null; + this.clipShadows = false; -/** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + this.colorWrite = true; -THREE.Triangle = function ( a, b, c ) { + this.precision = null; // override the renderer's default precision for this material - this.a = ( a !== undefined ) ? a : new THREE.Vector3(); - this.b = ( b !== undefined ) ? b : new THREE.Vector3(); - this.c = ( c !== undefined ) ? c : new THREE.Vector3(); + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; -}; + this.alphaTest = 0; + this.premultipliedAlpha = false; -THREE.Triangle.normal = function () { + this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer - var v0 = new THREE.Vector3(); + this.visible = true; - return function normal( a, b, c, optionalTarget ) { + this._needsUpdate = true; - var result = optionalTarget || new THREE.Vector3(); + }; - result.subVectors( c, b ); - v0.subVectors( a, b ); - result.cross( v0 ); + Material.prototype = { - var resultLengthSq = result.lengthSq(); - if ( resultLengthSq > 0 ) { + constructor: Material, - return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); + get needsUpdate() { - } + return this._needsUpdate; - return result.set( 0, 0, 0 ); + }, - }; + set needsUpdate( value ) { -}(); + if ( value === true ) this.update(); + this._needsUpdate = value; -// static/instance method to calculate barycentric coordinates -// based on: http://www.blackpawn.com/texts/pointinpoly/default.html -THREE.Triangle.barycoordFromPoint = function () { + }, - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + setValues: function ( values ) { - return function barycoordFromPoint( point, a, b, c, optionalTarget ) { + if ( values === undefined ) return; - v0.subVectors( c, a ); - v1.subVectors( b, a ); - v2.subVectors( point, a ); + for ( var key in values ) { - var dot00 = v0.dot( v0 ); - var dot01 = v0.dot( v1 ); - var dot02 = v0.dot( v2 ); - var dot11 = v1.dot( v1 ); - var dot12 = v1.dot( v2 ); + var newValue = values[ key ]; - var denom = ( dot00 * dot11 - dot01 * dot01 ); + if ( newValue === undefined ) { - var result = optionalTarget || new THREE.Vector3(); + console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); + continue; - // collinear or singular triangle - if ( denom === 0 ) { + } - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return result.set( - 2, - 1, - 1 ); + var currentValue = this[ key ]; - } + if ( currentValue === undefined ) { - var invDenom = 1 / denom; - var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); + continue; - // barycentric coordinates must always sum to 1 - return result.set( 1 - u - v, v, u ); + } - }; + if ( (currentValue && currentValue.isColor) ) { -}(); + currentValue.set( newValue ); -THREE.Triangle.containsPoint = function () { + } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) { - var v1 = new THREE.Vector3(); + currentValue.copy( newValue ); - return function containsPoint( point, a, b, c ) { + } else if ( key === 'overdraw' ) { - var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 ); + // ensure overdraw is backwards-compatible with legacy boolean type + this[ key ] = Number( newValue ); - return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); + } else { - }; + this[ key ] = newValue; -}(); + } -THREE.Triangle.prototype = { + } - constructor: THREE.Triangle, + }, - set: function ( a, b, c ) { + toJSON: function ( meta ) { - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); + var isRoot = meta === undefined; - return this; + if ( isRoot ) { - }, + meta = { + textures: {}, + images: {} + }; - setFromPointsAndIndices: function ( points, i0, i1, i2 ) { + } - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); + var data = { + metadata: { + version: 4.4, + type: 'Material', + generator: 'Material.toJSON' + } + }; - return this; + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; - }, + if ( this.name !== '' ) data.name = this.name; - clone: function () { + if ( (this.color && this.color.isColor) ) data.color = this.color.getHex(); - return new this.constructor().copy( this ); + if ( this.roughness !== undefined ) data.roughness = this.roughness; + if ( this.metalness !== undefined ) data.metalness = this.metalness; - }, + if ( (this.emissive && this.emissive.isColor) ) data.emissive = this.emissive.getHex(); + if ( (this.specular && this.specular.isColor) ) data.specular = this.specular.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; - copy: function ( triangle ) { + if ( (this.map && this.map.isTexture) ) data.map = this.map.toJSON( meta ).uuid; + if ( (this.alphaMap && this.alphaMap.isTexture) ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + if ( (this.lightMap && this.lightMap.isTexture) ) data.lightMap = this.lightMap.toJSON( meta ).uuid; + if ( (this.bumpMap && this.bumpMap.isTexture) ) { - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; - return this; + } + if ( (this.normalMap && this.normalMap.isTexture) ) { - }, + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalScale = this.normalScale.toArray(); - area: function () { + } + if ( (this.displacementMap && this.displacementMap.isTexture) ) { - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; - return function area() { + } + if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; + if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; - v0.subVectors( this.c, this.b ); - v1.subVectors( this.a, this.b ); + if ( (this.emissiveMap && this.emissiveMap.isTexture) ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; + if ( (this.specularMap && this.specularMap.isTexture) ) data.specularMap = this.specularMap.toJSON( meta ).uuid; - return v0.cross( v1 ).length() * 0.5; + if ( (this.envMap && this.envMap.isTexture) ) { - }; + data.envMap = this.envMap.toJSON( meta ).uuid; + data.reflectivity = this.reflectivity; // Scale behind envMap - }(), + } - midpoint: function ( optionalTarget ) { + if ( this.size !== undefined ) data.size = this.size; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.shading !== SmoothShading ) data.shading = this.shading; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors; - }, + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; - normal: function ( optionalTarget ) { + // TODO: Copied from Object3D.toJSON - return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget ); + function extractFromCache ( cache ) { - }, + var values = []; - plane: function ( optionalTarget ) { + for ( var key in cache ) { - var result = optionalTarget || new THREE.Plane(); + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - return result.setFromCoplanarPoints( this.a, this.b, this.c ); + } - }, + return values; - barycoordFromPoint: function ( point, optionalTarget ) { + } - return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); + if ( isRoot ) { - }, + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - containsPoint: function ( point ) { + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; - return THREE.Triangle.containsPoint( point, this.a, this.b, this.c ); + } - }, + return data; - closestPointToPoint: function () { + }, - var plane, edgeList, projectedPoint, closestPoint; + clone: function () { - return function closestPointToPoint( point, optionalTarget ) { + return new this.constructor().copy( this ); - if ( plane === undefined ) { + }, - plane = new THREE.Plane(); - edgeList = [ new THREE.Line3(), new THREE.Line3(), new THREE.Line3() ]; - projectedPoint = new THREE.Vector3(); - closestPoint = new THREE.Vector3(); + copy: function ( source ) { - } + this.name = source.name; - var result = optionalTarget || new THREE.Vector3(); - var minDistance = Infinity; + this.fog = source.fog; + this.lights = source.lights; - // project the point onto the plane of the triangle + this.blending = source.blending; + this.side = source.side; + this.shading = source.shading; + this.vertexColors = source.vertexColors; - plane.setFromCoplanarPoints( this.a, this.b, this.c ); - plane.projectPoint( point, projectedPoint ); + this.opacity = source.opacity; + this.transparent = source.transparent; - // check if the projection lies within the triangle + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; - if( this.containsPoint( projectedPoint ) === true ) { + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; - // if so, this is the closest point + this.colorWrite = source.colorWrite; - result.copy( projectedPoint ); + this.precision = source.precision; - } else { + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; - // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices + this.alphaTest = source.alphaTest; - edgeList[ 0 ].set( this.a, this.b ); - edgeList[ 1 ].set( this.b, this.c ); - edgeList[ 2 ].set( this.c, this.a ); + this.premultipliedAlpha = source.premultipliedAlpha; - for( var i = 0; i < edgeList.length; i ++ ) { + this.overdraw = source.overdraw; - edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); + this.visible = source.visible; + this.clipShadows = source.clipShadows; - var distance = projectedPoint.distanceToSquared( closestPoint ); + var srcPlanes = source.clippingPlanes, + dstPlanes = null; - if( distance < minDistance ) { + if ( srcPlanes !== null ) { - minDistance = distance; + var n = srcPlanes.length; + dstPlanes = new Array( n ); - result.copy( closestPoint ); + for ( var i = 0; i !== n; ++ i ) + dstPlanes[ i ] = srcPlanes[ i ].clone(); - } + } - } + this.clippingPlanes = dstPlanes; - } + return this; - return result; + }, - }; + update: function () { - }(), + this.dispatchEvent( { type: 'update' } ); - equals: function ( triangle ) { + }, - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + dispose: function () { - } + this.dispatchEvent( { type: 'dispose' } ); -}; + } -// File:src/math/Interpolant.js + }; -/** - * Abstract base class of interpolants over parametric samples. - * - * The parameter domain is one dimensional, typically the time or a path - * along a curve defined by the data. - * - * The sample values can have any dimensionality and derived classes may - * apply special interpretations to the data. - * - * This class provides the interval seek in a Template Method, deferring - * the actual interpolation to derived classes. - * - * Time complexity is O(1) for linear access crossing at most two points - * and O(log N) for random access, where N is the number of positions. - * - * References: - * - * http://www.oodesign.com/template-method-pattern.html - * - * @author tschw - */ + Object.assign( Material.prototype, EventDispatcher.prototype ); -THREE.Interpolant = function( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + var count$1 = 0; + function MaterialIdCount () { return count$1++; }; - this.parameterPositions = parameterPositions; - this._cachedIndex = 0; + /** + * Uniform Utilities + */ - this.resultBuffer = resultBuffer !== undefined ? - resultBuffer : new sampleValues.constructor( sampleSize ); - this.sampleValues = sampleValues; - this.valueSize = sampleSize; + exports.UniformsUtils = { -}; + merge: function ( uniforms ) { -THREE.Interpolant.prototype = { + var merged = {}; - constructor: THREE.Interpolant, + for ( var u = 0; u < uniforms.length; u ++ ) { - evaluate: function( t ) { + var tmp = this.clone( uniforms[ u ] ); - var pp = this.parameterPositions, - i1 = this._cachedIndex, + for ( var p in tmp ) { - t1 = pp[ i1 ], - t0 = pp[ i1 - 1 ]; + merged[ p ] = tmp[ p ]; - validate_interval: { + } - seek: { + } - var right; + return merged; - linear_scan: { -//- See http://jsperf.com/comparison-to-undefined/3 -//- slower code: -//- -//- if ( t >= t1 || t1 === undefined ) { - forward_scan: if ( ! ( t < t1 ) ) { + }, - for ( var giveUpAt = i1 + 2; ;) { + clone: function ( uniforms_src ) { - if ( t1 === undefined ) { + var uniforms_dst = {}; - if ( t < t0 ) break forward_scan; + for ( var u in uniforms_src ) { - // after end + uniforms_dst[ u ] = {}; - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); + for ( var p in uniforms_src[ u ] ) { - } + var parameter_src = uniforms_src[ u ][ p ]; - if ( i1 === giveUpAt ) break; // this loop + if ( (parameter_src && parameter_src.isColor) || + (parameter_src && parameter_src.isVector2) || + (parameter_src && parameter_src.isVector3) || + (parameter_src && parameter_src.isVector4) || + (parameter_src && parameter_src.isMatrix3) || + (parameter_src && parameter_src.isMatrix4) || + (parameter_src && parameter_src.isTexture) ) { - t0 = t1; - t1 = pp[ ++ i1 ]; + uniforms_dst[ u ][ p ] = parameter_src.clone(); - if ( t < t1 ) { + } else if ( Array.isArray( parameter_src ) ) { - // we have arrived at the sought interval - break seek; + uniforms_dst[ u ][ p ] = parameter_src.slice(); - } + } else { - } + uniforms_dst[ u ][ p ] = parameter_src; - // prepare binary search on the right side of the index - right = pp.length; - break linear_scan; + } - } + } -//- slower code: -//- if ( t < t0 || t0 === undefined ) { - if ( ! ( t >= t0 ) ) { + } - // looping? + return uniforms_dst; - var t1global = pp[ 1 ]; + } - if ( t < t1global ) { + }; - i1 = 2; // + 1, using the scan for the details - t0 = t1global; + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * defines: { "label" : "value" }, + * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, + * + * fragmentShader: , + * vertexShader: , + * + * wireframe: , + * wireframeLinewidth: , + * + * lights: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - } + function ShaderMaterial ( parameters ) { + this.isShaderMaterial = this.isMaterial = true; - // linear reverse scan + Material.call( this ); - for ( var giveUpAt = i1 - 2; ;) { + this.type = 'ShaderMaterial'; - if ( t0 === undefined ) { + this.defines = {}; + this.uniforms = {}; - // before start + this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; + this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + this.linewidth = 1; - } + this.wireframe = false; + this.wireframeLinewidth = 1; - if ( i1 === giveUpAt ) break; // this loop + this.fog = false; // set to use scene fog + this.lights = false; // set to use scene lights + this.clipping = false; // set to use user-defined clipping planes - t1 = t0; - t0 = pp[ -- i1 - 1 ]; + this.skinning = false; // set to use skinning attribute streams + this.morphTargets = false; // set to use morph targets + this.morphNormals = false; // set to use morph normals - if ( t >= t0 ) { + this.extensions = { + derivatives: false, // set to use derivatives + fragDepth: false, // set to use fragment depth values + drawBuffers: false, // set to use draw buffers + shaderTextureLOD: false // set to use shader texture LOD + }; - // we have arrived at the sought interval - break seek; + // When rendered geometry doesn't include these attributes but the material does, + // use these default values in WebGL. This avoids errors when buffer data is missing. + this.defaultAttributeValues = { + 'color': [ 1, 1, 1 ], + 'uv': [ 0, 0 ], + 'uv2': [ 0, 0 ] + }; - } + this.index0AttributeName = undefined; - } + if ( parameters !== undefined ) { - // prepare binary search on the left side of the index - right = i1; - i1 = 0; - break linear_scan; + if ( parameters.attributes !== undefined ) { - } + console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); - // the interval is valid + } - break validate_interval; + this.setValues( parameters ); - } // linear scan + } - // binary search + }; - while ( i1 < right ) { + ShaderMaterial.prototype = Object.create( Material.prototype ); + ShaderMaterial.prototype.constructor = ShaderMaterial; + + ShaderMaterial.prototype.copy = function ( source ) { + + Material.prototype.copy.call( this, source ); + + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + + this.uniforms = exports.UniformsUtils.clone( source.uniforms ); + + this.defines = source.defines; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.lights = source.lights; + this.clipping = source.clipping; + + this.skinning = source.skinning; + + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; + + this.extensions = source.extensions; + + return this; + + }; + + ShaderMaterial.prototype.toJSON = function ( meta ) { + + var data = Material.prototype.toJSON.call( this, meta ); + + data.uniforms = this.uniforms; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; + + return data; + + }; + + exports.ShaderChunk = {}; + + exports.ShaderChunk["alphamap_fragment"] = "#ifdef USE_ALPHAMAP\n\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n"; + exports.ShaderChunk["alphamap_pars_fragment"] = "#ifdef USE_ALPHAMAP\n\n\tuniform sampler2D alphaMap;\n\n#endif\n"; + exports.ShaderChunk["alphatest_fragment"] = "#ifdef ALPHATEST\n\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n"; + exports.ShaderChunk["ambient_pars"] = "uniform vec3 ambientLightColor;\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n"; + exports.ShaderChunk["aomap_fragment"] = "#ifdef USE_AOMAP\n\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["aomap_pars_fragment"] = "#ifdef USE_AOMAP\n\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n\n#endif"; + exports.ShaderChunk["begin_vertex"] = "\nvec3 transformed = vec3( position );\n"; + exports.ShaderChunk["beginnormal_vertex"] = "\nvec3 objectNormal = vec3( normal );\n"; + exports.ShaderChunk["bsdfs"] = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n\n}\n\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\n\t\tif( decayExponent > 0.0 ) {\n\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\n\t\t\t// based upon Frostbite 3 Moving to Physically-based Rendering\n\t\t\t// page 32, equation 26: E[window1]\n\t\t\t// http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\n\t\t\t// this is intended to be used on spot and point lights who are represented as luminous intensity\n\t\t\t// but who must be converted to luminous irradiance for surface lighting calculation\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n\n#else\n\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\n#endif\n\n\t\t}\n\n\t\treturn 1.0;\n}\n\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\n\treturn RECIPROCAL_PI * diffuseColor;\n\n} // validated\n\n\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\n\t// Original approximation by Christophe Schlick '94\n\t//;float fresnel = pow( 1.0 - dotLH, 5.0 );\n\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n\n} // validated\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (34)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\t// geometry term = G(l)⋅G(v) / 4(n⋅l)(n⋅v)\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\n\treturn 1.0 / ( gl * gv );\n\n} // validated\n\n// from page 12, listing 2 of http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\tfloat a2 = pow2( alpha );\n\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\n\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\n\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n\n}\n\n\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat alpha = pow2( roughness ); // UE4's roughness\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\n\tfloat D = D_GGX( alpha, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\n\tvec4 r = roughness * c0 + c1;\n\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\n\treturn specularColor * AB.x + AB.y;\n\n} // validated\n\n\nfloat G_BlinnPhong_Implicit( /* const in float dotNL, const in float dotNV */ ) {\n\n\t// geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v)\n\treturn 0.25;\n\n}\n\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n\n}\n\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\t//float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\t//float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\n\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; + exports.ShaderChunk["bumpmap_pars_fragment"] = "#ifdef USE_BUMPMAP\n\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\n\t// Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n\t// http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n\t// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n\tvec2 dHdxy_fwd() {\n\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n\t\treturn vec2( dBx, dBy );\n\n\t}\n\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\t\t// normalized\n\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\n\t}\n\n#endif\n"; + exports.ShaderChunk["clipping_planes_fragment"] = "#if NUM_CLIPPING_PLANES > 0\n\n\tfor ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\n\t}\n\n#endif\n"; + exports.ShaderChunk["clipping_planes_pars_fragment"] = "#if NUM_CLIPPING_PLANES > 0\n\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n\n#endif\n"; + exports.ShaderChunk["clipping_planes_pars_vertex"] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; + exports.ShaderChunk["clipping_planes_vertex"] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n\n"; + exports.ShaderChunk["color_fragment"] = "#ifdef USE_COLOR\n\n\tdiffuseColor.rgb *= vColor;\n\n#endif"; + exports.ShaderChunk["color_pars_fragment"] = "#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif\n"; + exports.ShaderChunk["color_pars_vertex"] = "#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif"; + exports.ShaderChunk["color_vertex"] = "#ifdef USE_COLOR\n\n\tvColor.xyz = color.xyz;\n\n#endif"; + exports.ShaderChunk["common"] = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\n\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\n// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range.\n// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\n\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\n\n\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n}\n\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n\n}\n\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\n\treturn - distance * planeNormal + point;\n\n}\n\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n\n}\n\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n\n}\n"; + exports.ShaderChunk["cube_uv_reflection_fragment"] = "#ifdef ENVMAP_TYPE_CUBE_UV\n\n#define cubeUV_textureSize (1024.0)\n\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\n\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\t// Clamp the value to the max mip level counts. hard coded to 6 mips\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\n\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\t// float powScale = exp2(roughnessLevel + mipLevel);\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\t// float scale = 1.0 / exp2(roughnessLevel + 2.0 + mipLevel);\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\t// float mipOffset = 0.75*(1.0 - 1.0/exp2(mipLevel))/exp2(roughnessLevel);\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\n\tfloat rcpPowScale = 1.0 / powScale;\n\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\n\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\n\t// round to nearest mipmap if we are not interpolating.\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\n\t// Tri linear interpolation.\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\n\tvec4 result = mix(color10, color20, t);\n\n\treturn vec4(result.rgb, 1.0);\n}\n\n#endif\n"; + exports.ShaderChunk["defaultnormal_vertex"] = "#ifdef FLIP_SIDED\n\n\tobjectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; + exports.ShaderChunk["displacementmap_pars_vertex"] = "#ifdef USE_DISPLACEMENTMAP\n\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n\n#endif\n"; + exports.ShaderChunk["displacementmap_vertex"] = "#ifdef USE_DISPLACEMENTMAP\n\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n\n#endif\n"; + exports.ShaderChunk["emissivemap_fragment"] = "#ifdef USE_EMISSIVEMAP\n\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n\n#endif\n"; + exports.ShaderChunk["emissivemap_pars_fragment"] = "#ifdef USE_EMISSIVEMAP\n\n\tuniform sampler2D emissiveMap;\n\n#endif\n"; + exports.ShaderChunk["encodings_fragment"] = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; + exports.ShaderChunk["encodings_pars_fragment"] = "// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/\n\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\n\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\n\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\n\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\n\n// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html\n\n// M matrix, for encoding\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\n\n// Inverse M matrix, for decoding\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n"; + exports.ShaderChunk["envmap_fragment"] = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n\t\t// Transforming Normal Vectors with the Inverse Transformation\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#else\n\n\t\tvec3 reflectVec = vReflect;\n\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\n\t#endif\n\n\tenvColor = envMapTexelToLinear( envColor );\n\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["envmap_pars_fragment"] = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n\n#ifdef USE_ENVMAP\n\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["envmap_pars_vertex"] = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\n\t#else\n\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["envmap_vertex"] = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\tvWorldPosition = worldPosition.xyz;\n\n\t#else\n\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["fog_fragment"] = "#ifdef USE_FOG\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n\t#else\n\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\n\t#endif\n\n\t#ifdef FOG_EXP2\n\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\n\t#else\n\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\n\t#endif\n\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\n#endif\n"; + exports.ShaderChunk["fog_pars_fragment"] = "#ifdef USE_FOG\n\n\tuniform vec3 fogColor;\n\n\t#ifdef FOG_EXP2\n\n\t\tuniform float fogDensity;\n\n\t#else\n\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n\n#endif"; + exports.ShaderChunk["lightmap_fragment"] = "#ifdef USE_LIGHTMAP\n\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\n\n#endif\n"; + exports.ShaderChunk["lightmap_pars_fragment"] = "#ifdef USE_LIGHTMAP\n\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n\n#endif"; + exports.ShaderChunk["lights_lambert_vertex"] = "vec3 diffuse = vec3( 1.0 );\n\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\n\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\n\nvLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\n\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n\n#if NUM_POINT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\n#endif\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\t}\n\n#endif\n\n#if NUM_DIR_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\n#endif\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\n\t\t#endif\n\n\t}\n\n#endif\n"; + exports.ShaderChunk["lights_pars"] = "uniform vec3 ambientLightColor;\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n\n#if NUM_DIR_LIGHTS > 0\n\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\n\t}\n\n#endif\n\n\n#if NUM_POINT_LIGHTS > 0\n\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\n\t}\n\n#endif\n\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\n\t}\n\n#endif\n\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tirradiance *= PI;\n\n\t\t#endif\n\n\t\treturn irradiance;\n\n\t}\n\n#endif\n\n\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\n\tvec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) {\n\n\t\t#include \n\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\n\t\t\t// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\n\t\t\t// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#else\n\n\t\t\t\t// force the bias high to get the last LOD level as it is the most blurred.\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\n\t\t#else\n\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\n\t\t#endif\n\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\n\t}\n\n\t// taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\n\t\t//float envMapWidth = pow( 2.0, maxMIPLevelScalar );\n\t\t//float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\n\t\t// clamp to allowable LOD ranges.\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\n\t}\n\n\tvec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\n\t\t#endif\n\n\t\t#include \n\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\n\t\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#endif\n\n\t\treturn envMapColor.rgb * envMapIntensity;\n\n\t}\n\n#endif\n"; + exports.ShaderChunk["lights_phong_fragment"] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; + exports.ShaderChunk["lights_phong_pars_fragment"] = "varying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n\nstruct BlinnPhongMaterial {\n\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n\n};\n\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n\n}\n\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n\n#define Material_LightProbeLOD( material )\t(0)\n"; + exports.ShaderChunk["lights_physical_fragment"] = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat ); // Burley clearcoat model\n\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; + exports.ShaderChunk["lights_physical_pars_fragment"] = "struct PhysicalMaterial {\n\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n\n};\n\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\n\n// Clear coat directional hemishperical reflectance (this approximation should be improved)\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n\n}\n\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n\t#ifndef STANDARD\n\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\n\t#endif\n\n}\n\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\n\t#ifndef STANDARD\n\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\n\t#endif\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\n\n// ref: http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n\n}\n"; + exports.ShaderChunk["lights_template"] = "//\n// This is a template that can be used to light a material, it uses pluggable RenderEquations (RE)\n// for specific lighting scenarios.\n//\n// Instructions for use:\n// - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined\n// - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ???\n// - Create a material parameter that is to be passed as the third parameter to your lighting functions.\n//\n// TODO:\n// - Add area light support.\n// - Add sphere light support.\n// - Add diffuse light probe (irradiance cubemap) support.\n//\n\nGeometricContext geometry;\n\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n\nIncidentLight directLight;\n\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tPointLight pointLight;\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tSpotLight spotLight;\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tDirectionalLight directionalLight;\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if defined( RE_IndirectDiffuse )\n\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n\t#ifdef USE_LIGHTMAP\n\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tlightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage\n\n\t\t#endif\n\n\t\tirradiance += lightMapIrradiance;\n\n\t#endif\n\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t}\n\n\t#endif\n\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t// TODO, replace 8 with the real maxMIPLevel\n\t \tirradiance += getLightProbeIndirectIrradiance( /*lightProbe,*/ geometry, 8 );\n\n\t#endif\n\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n\n#endif\n\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\n\t// TODO, replace 8 with the real maxMIPLevel\n\tvec3 radiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_BlinnShininessExponent( material ), 8 );\n\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n\n#endif\n"; + exports.ShaderChunk["logdepthbuf_fragment"] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif"; + exports.ShaderChunk["logdepthbuf_pars_fragment"] = "#ifdef USE_LOGDEPTHBUF\n\n\tuniform float logDepthBufFC;\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["logdepthbuf_pars_vertex"] = "#ifdef USE_LOGDEPTHBUF\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\n\t#endif\n\n\tuniform float logDepthBufFC;\n\n#endif"; + exports.ShaderChunk["logdepthbuf_vertex"] = "#ifdef USE_LOGDEPTHBUF\n\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\n\t#else\n\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["map_fragment"] = "#ifdef USE_MAP\n\n\tvec4 texelColor = texture2D( map, vUv );\n\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n\n#endif\n"; + exports.ShaderChunk["map_pars_fragment"] = "#ifdef USE_MAP\n\n\tuniform sampler2D map;\n\n#endif\n"; + exports.ShaderChunk["map_particle_fragment"] = "#ifdef USE_MAP\n\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n\n#endif\n"; + exports.ShaderChunk["map_particle_pars_fragment"] = "#ifdef USE_MAP\n\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n\n#endif\n"; + exports.ShaderChunk["metalnessmap_fragment"] = "float metalnessFactor = metalness;\n\n#ifdef USE_METALNESSMAP\n\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n\n#endif\n"; + exports.ShaderChunk["metalnessmap_pars_fragment"] = "#ifdef USE_METALNESSMAP\n\n\tuniform sampler2D metalnessMap;\n\n#endif"; + exports.ShaderChunk["morphnormal_vertex"] = "#ifdef USE_MORPHNORMALS\n\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n#endif\n"; + exports.ShaderChunk["morphtarget_pars_vertex"] = "#ifdef USE_MORPHTARGETS\n\n\t#ifndef USE_MORPHNORMALS\n\n\tuniform float morphTargetInfluences[ 8 ];\n\n\t#else\n\n\tuniform float morphTargetInfluences[ 4 ];\n\n\t#endif\n\n#endif"; + exports.ShaderChunk["morphtarget_vertex"] = "#ifdef USE_MORPHTARGETS\n\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n\t#ifndef USE_MORPHNORMALS\n\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["normal_flip"] = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n"; + exports.ShaderChunk["normal_fragment"] = "#ifdef FLAT_SHADED\n\n\t// Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ...\n\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n\n#else\n\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n\n#endif\n\n#ifdef USE_NORMALMAP\n\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n"; + exports.ShaderChunk["normalmap_pars_fragment"] = "#ifdef USE_NORMALMAP\n\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\n\t// Per-Pixel Tangent Space Normal Mapping\n\t// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\n\t}\n\n#endif\n"; + exports.ShaderChunk["packing"] = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\n\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\n\nconst float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1)\nconst float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1)\n\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\n\nconst float ShiftRight8 = 1. / 256.;\n\nvec4 packDepthToRGBA( const in float v ) {\n\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\n\treturn r * PackUpscale;\n\n}\n\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\n\treturn dot( v, UnpackFactors );\n\n}\n\n// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions\n\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\n\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; + exports.ShaderChunk["premultiplied_alpha_fragment"] = "#ifdef PREMULTIPLIED_ALPHA\n\n\t// Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation.\n\tgl_FragColor.rgb *= gl_FragColor.a;\n\n#endif\n"; + exports.ShaderChunk["project_vertex"] = "#ifdef USE_SKINNING\n\n\tvec4 mvPosition = modelViewMatrix * skinned;\n\n#else\n\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n"; + exports.ShaderChunk["roughnessmap_fragment"] = "float roughnessFactor = roughness;\n\n#ifdef USE_ROUGHNESSMAP\n\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n\n#endif\n"; + exports.ShaderChunk["roughnessmap_pars_fragment"] = "#ifdef USE_ROUGHNESSMAP\n\n\tuniform sampler2D roughnessMap;\n\n#endif"; + exports.ShaderChunk["shadowmap_pars_fragment"] = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\n\t#endif\n\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\n\t}\n\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\n\t\tvec2 f = fract( uv * size + 0.5 );\n\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\n\t\treturn c;\n\n\t}\n\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\n\t\t// if ( something && something ) breaks ATI OpenGL shader compiler\n\t\t// if ( all( something, something ) ) using this instead\n\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n\t\tbool frustumTest = all( frustumTestVec );\n\n\t\tif ( frustumTest ) {\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering:\n\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\n\t\t#endif\n\n\t\t}\n\n\t\treturn 1.0;\n\n\t}\n\n\t// cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D\n\t// vector suitable for 2D texture mapping. This code uses the following layout for the\n\t// 2D texture:\n\t//\n\t// xzXZ\n\t// y Y\n\t//\n\t// Y - Positive y direction\n\t// y - Negative y direction\n\t// X - Positive x direction\n\t// x - Negative x direction\n\t// Z - Positive z direction\n\t// z - Negative z direction\n\t//\n\t// Source and test bed:\n\t// https://gist.github.com/tschw/da10c43c467ce8afd0c4\n\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\n\t\t// Number of texels to avoid at the edge of each square\n\n\t\tvec3 absV = abs( v );\n\n\t\t// Intersect unit cube\n\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\n\t\t// Apply scale to avoid seams\n\n\t\t// two texels less per square (one texel will do for NEAREST)\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\n\t\t// Unwrap\n\n\t\t// space: -1 ... 1 range for each square\n\t\t//\n\t\t// #X##\t\tdim := ( 4 , 2 )\n\t\t// # #\t\tcenter := ( 1 , 1 )\n\n\t\tvec2 planar = v.xy;\n\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\n\t\tif ( absV.z >= almostOne ) {\n\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\n\t\t} else if ( absV.x >= almostOne ) {\n\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\n\t\t} else if ( absV.y >= almostOne ) {\n\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\n\t\t}\n\n\t\t// Transform to UV space\n\n\t\t// scale := 0.5 / dim\n\t\t// translate := ( center + 0.5 ) / dim\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\n\t}\n\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\n\t\t// for point lights, the uniform @vShadowCoord is re-purposed to hold\n\t\t// the distance from the light to the world-space position of the fragment.\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\n\t\t// bd3D = base direction 3D\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t// dp = distance from light to fragment position\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering\n\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\n\t\t#endif\n\n\t}\n\n#endif\n"; + exports.ShaderChunk["shadowmap_pars_vertex"] = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["shadowmap_vertex"] = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["shadowmask_pars_fragment"] = "float getShadowMask() {\n\n\tfloat shadow = 1.0;\n\n\t#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\tDirectionalLight directionalLight;\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\tSpotLight spotLight;\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\tPointLight pointLight;\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#endif\n\n\treturn shadow;\n\n}\n"; + exports.ShaderChunk["skinbase_vertex"] = "#ifdef USE_SKINNING\n\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif"; + exports.ShaderChunk["skinning_pars_vertex"] = "#ifdef USE_SKINNING\n\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\n\t#ifdef BONE_TEXTURE\n\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\n\t\t\ty = dy * ( y + 0.5 );\n\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\n\t\t\treturn bone;\n\n\t\t}\n\n\t#else\n\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\n\t\t}\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["skinning_vertex"] = "#ifdef USE_SKINNING\n\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n\n#endif\n"; + exports.ShaderChunk["skinnormal_vertex"] = "#ifdef USE_SKINNING\n\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\n#endif\n"; + exports.ShaderChunk["specularmap_fragment"] = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n\n#else\n\n\tspecularStrength = 1.0;\n\n#endif"; + exports.ShaderChunk["specularmap_pars_fragment"] = "#ifdef USE_SPECULARMAP\n\n\tuniform sampler2D specularMap;\n\n#endif"; + exports.ShaderChunk["tonemapping_fragment"] = "#if defined( TONE_MAPPING )\n\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n\n#endif\n"; + exports.ShaderChunk["tonemapping_pars_fragment"] = "#define saturate(a) clamp( a, 0.0, 1.0 )\n\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\n\n// exposure only\nvec3 LinearToneMapping( vec3 color ) {\n\n return toneMappingExposure * color;\n\n}\n\n// source: https://www.cs.utah.edu/~reinhard/cdrom/\nvec3 ReinhardToneMapping( vec3 color ) {\n\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n\n}\n\n// source: http://filmicgames.com/archives/75\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\n // John Hable's filmic operator from Uncharted 2 video game\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n\n}\n\n// source: http://filmicgames.com/archives/75\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n\n}\n"; + exports.ShaderChunk["uv2_pars_fragment"] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvarying vec2 vUv2;\n\n#endif"; + exports.ShaderChunk["uv2_pars_vertex"] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\n#endif"; + exports.ShaderChunk["uv2_vertex"] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvUv2 = uv2;\n\n#endif"; + exports.ShaderChunk["uv_pars_fragment"] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvarying vec2 vUv;\n\n#endif"; + exports.ShaderChunk["uv_pars_vertex"] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n\n#endif\n"; + exports.ShaderChunk["uv_vertex"] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif"; + exports.ShaderChunk["worldpos_vertex"] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n\t#ifdef USE_SKINNING\n\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\n\t#else\n\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\n\t#endif\n\n#endif\n"; + exports.ShaderChunk["cube_frag"] = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\n\nvarying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n\n}\n"; + exports.ShaderChunk["cube_vert"] = "varying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["depth_frag"] = "#if DEPTH_PACKING == 3200\n\n\tuniform float opacity;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( 1.0 );\n\n\t#if DEPTH_PACKING == 3200\n\n\t\tdiffuseColor.a = opacity;\n\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\n\t#if DEPTH_PACKING == 3200\n\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\n\t#elif DEPTH_PACKING == 3201\n\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\n\t#endif\n\n}\n"; + exports.ShaderChunk["depth_vert"] = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["distanceRGBA_frag"] = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n\n#include \n#include \n#include \n\nvoid main () {\n\n\t#include \n\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n\n}\n"; + exports.ShaderChunk["distanceRGBA_vert"] = "varying vec4 vWorldPosition;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvWorldPosition = worldPosition;\n\n}\n"; + exports.ShaderChunk["equirect_frag"] = "uniform sampler2D tEquirect;\nuniform float tFlip;\n\nvarying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\t// \tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n}\n"; + exports.ShaderChunk["equirect_vert"] = "varying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["linedashed_frag"] = "uniform vec3 diffuse;\nuniform float opacity;\n\nuniform float dashSize;\nuniform float totalSize;\n\nvarying float vLineDistance;\n\n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\n\t\tdiscard;\n\n\t}\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\n\toutgoingLight = diffuseColor.rgb; // simple shader\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["linedashed_vert"] = "uniform float scale;\nattribute float lineDistance;\n\nvarying float vLineDistance;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvLineDistance = scale * lineDistance;\n\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["meshbasic_frag"] = "uniform vec3 diffuse;\nuniform float opacity;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n\t#include \n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["meshbasic_vert"] = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#ifdef USE_ENVMAP\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["meshlambert_frag"] = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n\nvarying vec3 vLightFront;\n\n#ifdef DOUBLE_SIDED\n\n\tvarying vec3 vLightBack;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\n\t#include \n\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\n\t#ifdef DOUBLE_SIDED\n\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\n\t#else\n\n\t\treflectedLight.directDiffuse = vLightFront;\n\n\t#endif\n\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\t#include \n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["meshlambert_vert"] = "#define LAMBERT\n\nvarying vec3 vLightFront;\n\n#ifdef DOUBLE_SIDED\n\n\tvarying vec3 vLightBack;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["meshphong_frag"] = "#define PHONG\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["meshphong_vert"] = "#define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["meshphysical_frag"] = "#define PHYSICAL\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\n\nuniform float envMapIntensity; // temporary\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["meshphysical_vert"] = "#define PHYSICAL\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["normal_frag"] = "uniform float opacity;\nvarying vec3 vNormal;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\n\t#include \n\n}\n"; + exports.ShaderChunk["normal_vert"] = "varying vec3 vNormal;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\tvNormal = normalize( normalMatrix * normal );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["points_frag"] = "uniform vec3 diffuse;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\toutgoingLight = diffuseColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["points_vert"] = "uniform float size;\nuniform float scale;\n\n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + exports.ShaderChunk["shadow_frag"] = "uniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n\n}\n"; + exports.ShaderChunk["shadow_vert"] = "#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function Color ( r, g, b ) { + this.isColor = true; + + if ( g === undefined && b === undefined ) { + + // r is THREE.Color, hex or string + return this.set( r ); + + } + + return this.setRGB( r, g, b ); + + }; + + Color.prototype = { - var mid = ( i1 + right ) >>> 1; + constructor: Color, - if ( t < pp[ mid ] ) { + r: 1, g: 1, b: 1, - right = mid; + set: function ( value ) { - } else { + if ( (value && value.isColor) ) { - i1 = mid + 1; + this.copy( value ); - } + } else if ( typeof value === 'number' ) { - } + this.setHex( value ); - t1 = pp[ i1 ]; - t0 = pp[ i1 - 1 ]; + } else if ( typeof value === 'string' ) { - // check boundary cases, again + this.setStyle( value ); - if ( t0 === undefined ) { + } - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + return this; - } + }, - if ( t1 === undefined ) { + setScalar: function ( scalar ) { - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); + this.r = scalar; + this.g = scalar; + this.b = scalar; - } + }, - } // seek + setHex: function ( hex ) { - this._cachedIndex = i1; + hex = Math.floor( hex ); - this.intervalChanged_( i1, t0, t1 ); + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; - } // validate_interval + return this; - return this.interpolate_( i1, t0, t, t1 ); + }, - }, + setRGB: function ( r, g, b ) { - settings: null, // optional, subclass-specific settings structure - // Note: The indirection allows central control of many interpolants. + this.r = r; + this.g = g; + this.b = b; - // --- Protected interface + return this; - DefaultSettings_: {}, + }, - getSettings_: function() { + setHSL: function () { - return this.settings || this.DefaultSettings_; + function hue2rgb( p, q, t ) { - }, + if ( t < 0 ) t += 1; + if ( t > 1 ) t -= 1; + if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; + if ( t < 1 / 2 ) return q; + if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); + return p; - copySampleValue_: function( index ) { + } - // copies a sample value to the result buffer + return function setHSL( h, s, l ) { - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = index * stride; + // h,s,l ranges are in 0.0 - 1.0 + h = exports.Math.euclideanModulo( h, 1 ); + s = exports.Math.clamp( s, 0, 1 ); + l = exports.Math.clamp( l, 0, 1 ); - for ( var i = 0; i !== stride; ++ i ) { + if ( s === 0 ) { - result[ i ] = values[ offset + i ]; + this.r = this.g = this.b = l; - } + } else { - return result; + var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + var q = ( 2 * l ) - p; - }, + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); - // Template methods for derived classes: + } - interpolate_: function( i1, t0, t, t1 ) { + return this; - throw new Error( "call to abstract method" ); - // implementations shall return this.resultBuffer + }; - }, + }(), - intervalChanged_: function( i1, t0, t1 ) { + setStyle: function ( style ) { - // empty + function handleAlpha( string ) { - } + if ( string === undefined ) return; -}; + if ( parseFloat( string ) < 1 ) { -Object.assign( THREE.Interpolant.prototype, { + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - beforeStart_: //( 0, t, t0 ), returns this.resultBuffer - THREE.Interpolant.prototype.copySampleValue_, + } - afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer - THREE.Interpolant.prototype.copySampleValue_ + } -} ); -// File:src/math/interpolants/CubicInterpolant.js + var m; -/** - * Fast and simple cubic spline interpolant. - * - * It was derived from a Hermitian construction setting the first derivative - * at each sample position to the linear slope between neighboring positions - * over their parameter interval. - * - * @author tschw - */ + if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { -THREE.CubicInterpolant = function( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + // rgb / hsl - THREE.Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + var color; + var name = m[ 1 ]; + var components = m[ 2 ]; - this._weightPrev = -0; - this._offsetPrev = -0; - this._weightNext = -0; - this._offsetNext = -0; + switch ( name ) { -}; + case 'rgb': + case 'rgba': -THREE.CubicInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { + if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - constructor: THREE.CubicInterpolant, + // rgb(255,0,0) rgba(255,0,0,0.5) + this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; + this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; + this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; - DefaultSettings_: { + handleAlpha( color[ 5 ] ); - endingStart: THREE.ZeroCurvatureEnding, - endingEnd: THREE.ZeroCurvatureEnding + return this; - }, + } - intervalChanged_: function( i1, t0, t1 ) { + if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - var pp = this.parameterPositions, - iPrev = i1 - 2, - iNext = i1 + 1, + // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) + this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; + this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; + this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; - tPrev = pp[ iPrev ], - tNext = pp[ iNext ]; + handleAlpha( color[ 5 ] ); - if ( tPrev === undefined ) { + return this; - switch ( this.getSettings_().endingStart ) { + } - case THREE.ZeroSlopeEnding: + break; - // f'(t0) = 0 - iPrev = i1; - tPrev = 2 * t0 - t1; + case 'hsl': + case 'hsla': - break; + if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - case THREE.WrapAroundEnding: + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + var h = parseFloat( color[ 1 ] ) / 360; + var s = parseInt( color[ 2 ], 10 ) / 100; + var l = parseInt( color[ 3 ], 10 ) / 100; - // use the other end of the curve - iPrev = pp.length - 2; - tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + handleAlpha( color[ 5 ] ); - break; + return this.setHSL( h, s, l ); - default: // ZeroCurvatureEnding + } - // f''(t0) = 0 a.k.a. Natural Spline - iPrev = i1; - tPrev = t1; + break; - } + } - } + } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { - if ( tNext === undefined ) { + // hex color - switch ( this.getSettings_().endingEnd ) { + var hex = m[ 1 ]; + var size = hex.length; - case THREE.ZeroSlopeEnding: + if ( size === 3 ) { - // f'(tN) = 0 - iNext = i1; - tNext = 2 * t1 - t0; + // #ff0 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; - break; + return this; - case THREE.WrapAroundEnding: + } else if ( size === 6 ) { - // use the other end of the curve - iNext = 1; - tNext = t1 + pp[ 1 ] - pp[ 0 ]; + // #ff0000 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; - break; + return this; - default: // ZeroCurvatureEnding + } - // f''(tN) = 0, a.k.a. Natural Spline - iNext = i1 - 1; - tNext = t0; + } - } + if ( style && style.length > 0 ) { - } + // color keywords + var hex = exports.ColorKeywords[ style ]; - var halfDt = ( t1 - t0 ) * 0.5, - stride = this.valueSize; + if ( hex !== undefined ) { - this._weightPrev = halfDt / ( t0 - tPrev ); - this._weightNext = halfDt / ( tNext - t1 ); - this._offsetPrev = iPrev * stride; - this._offsetNext = iNext * stride; + // red + this.setHex( hex ); - }, + } else { - interpolate_: function( i1, t0, t, t1 ) { + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + } - o1 = i1 * stride, o0 = o1 - stride, - oP = this._offsetPrev, oN = this._offsetNext, - wP = this._weightPrev, wN = this._weightNext, + } - p = ( t - t0 ) / ( t1 - t0 ), - pp = p * p, - ppp = pp * p; + return this; - // evaluate polynomials + }, - var sP = - wP * ppp + 2 * wP * pp - wP * p; - var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1; - var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; - var sN = wN * ppp - wN * pp; + clone: function () { - // combine data linearly + return new this.constructor( this.r, this.g, this.b ); - for ( var i = 0; i !== stride; ++ i ) { + }, - result[ i ] = - sP * values[ oP + i ] + - s0 * values[ o0 + i ] + - s1 * values[ o1 + i ] + - sN * values[ oN + i ]; + copy: function ( color ) { - } + this.r = color.r; + this.g = color.g; + this.b = color.b; - return result; + return this; - } + }, -} ); + copyGammaToLinear: function ( color, gammaFactor ) { -// File:src/math/interpolants/DiscreteInterpolant.js + if ( gammaFactor === undefined ) gammaFactor = 2.0; -/** - * - * Interpolant that evaluates to the sample value at the position preceeding - * the parameter. - * - * @author tschw - */ + this.r = Math.pow( color.r, gammaFactor ); + this.g = Math.pow( color.g, gammaFactor ); + this.b = Math.pow( color.b, gammaFactor ); -THREE.DiscreteInterpolant = function( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + return this; - THREE.Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + }, -}; + copyLinearToGamma: function ( color, gammaFactor ) { -THREE.DiscreteInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { + if ( gammaFactor === undefined ) gammaFactor = 2.0; - constructor: THREE.DiscreteInterpolant, + var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - interpolate_: function( i1, t0, t, t1 ) { + this.r = Math.pow( color.r, safeInverse ); + this.g = Math.pow( color.g, safeInverse ); + this.b = Math.pow( color.b, safeInverse ); - return this.copySampleValue_( i1 - 1 ); + return this; - } + }, -} ); + convertGammaToLinear: function () { -// File:src/math/interpolants/LinearInterpolant.js + var r = this.r, g = this.g, b = this.b; -/** - * @author tschw - */ + this.r = r * r; + this.g = g * g; + this.b = b * b; -THREE.LinearInterpolant = function( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + return this; - THREE.Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + }, -}; + convertLinearToGamma: function () { -THREE.LinearInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { + this.r = Math.sqrt( this.r ); + this.g = Math.sqrt( this.g ); + this.b = Math.sqrt( this.b ); - constructor: THREE.LinearInterpolant, + return this; - interpolate_: function( i1, t0, t, t1 ) { + }, - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + getHex: function () { - offset1 = i1 * stride, - offset0 = offset1 - stride, + return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - weight1 = ( t - t0 ) / ( t1 - t0 ), - weight0 = 1 - weight1; + }, - for ( var i = 0; i !== stride; ++ i ) { + getHexString: function () { - result[ i ] = - values[ offset0 + i ] * weight0 + - values[ offset1 + i ] * weight1; + return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - } + }, - return result; + getHSL: function ( optionalTarget ) { - } + // h,s,l ranges are in 0.0 - 1.0 -} ); + var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; -// File:src/math/interpolants/QuaternionLinearInterpolant.js + var r = this.r, g = this.g, b = this.b; -/** - * Spherical linear unit quaternion interpolant. - * - * @author tschw - */ + var max = Math.max( r, g, b ); + var min = Math.min( r, g, b ); -THREE.QuaternionLinearInterpolant = function( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + var hue, saturation; + var lightness = ( min + max ) / 2.0; - THREE.Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + if ( min === max ) { -}; + hue = 0; + saturation = 0; -THREE.QuaternionLinearInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { + } else { - constructor: THREE.QuaternionLinearInterpolant, + var delta = max - min; - interpolate_: function( i1, t0, t, t1 ) { + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + switch ( max ) { - offset = i1 * stride, + case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; + case g: hue = ( b - r ) / delta + 2; break; + case b: hue = ( r - g ) / delta + 4; break; - alpha = ( t - t0 ) / ( t1 - t0 ); + } - for ( var end = offset + stride; offset !== end; offset += 4 ) { + hue /= 6; - THREE.Quaternion.slerpFlat( result, 0, - values, offset - stride, values, offset, alpha ); + } - } + hsl.h = hue; + hsl.s = saturation; + hsl.l = lightness; - return result; + return hsl; - } + }, -} ); + getStyle: function () { -// File:src/core/Clock.js + return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; -/** - * @author alteredq / http://alteredqualia.com/ - */ + }, -THREE.Clock = function ( autoStart ) { + offsetHSL: function ( h, s, l ) { - this.autoStart = ( autoStart !== undefined ) ? autoStart : true; + var hsl = this.getHSL(); - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; + hsl.h += h; hsl.s += s; hsl.l += l; - this.running = false; + this.setHSL( hsl.h, hsl.s, hsl.l ); -}; + return this; -THREE.Clock.prototype = { + }, - constructor: THREE.Clock, + add: function ( color ) { - start: function () { + this.r += color.r; + this.g += color.g; + this.b += color.b; - this.startTime = ( performance || Date ).now(); + return this; - this.oldTime = this.startTime; - this.running = true; + }, - }, + addColors: function ( color1, color2 ) { - stop: function () { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; - this.getElapsedTime(); - this.running = false; + return this; - }, + }, - getElapsedTime: function () { + addScalar: function ( s ) { - this.getDelta(); - return this.elapsedTime; + this.r += s; + this.g += s; + this.b += s; - }, + return this; - getDelta: function () { + }, - var diff = 0; + sub: function( color ) { - if ( this.autoStart && ! this.running ) { + this.r = Math.max( 0, this.r - color.r ); + this.g = Math.max( 0, this.g - color.g ); + this.b = Math.max( 0, this.b - color.b ); - this.start(); + return this; - } + }, - if ( this.running ) { + multiply: function ( color ) { - var newTime = ( performance || Date ).now(); + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; - diff = ( newTime - this.oldTime ) / 1000; - this.oldTime = newTime; + return this; - this.elapsedTime += diff; + }, - } + multiplyScalar: function ( s ) { - return diff; + this.r *= s; + this.g *= s; + this.b *= s; - } + return this; -}; + }, -// File:src/core/EventDispatcher.js + lerp: function ( color, alpha ) { -/** - * https://github.com/mrdoob/eventdispatcher.js/ - */ + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; -THREE.EventDispatcher = function () {}; + return this; -Object.assign( THREE.EventDispatcher.prototype, { + }, - addEventListener: function ( type, listener ) { + equals: function ( c ) { - if ( this._listeners === undefined ) this._listeners = {}; + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - var listeners = this._listeners; + }, - if ( listeners[ type ] === undefined ) { + fromArray: function ( array, offset ) { - listeners[ type ] = []; + if ( offset === undefined ) offset = 0; - } + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; - if ( listeners[ type ].indexOf( listener ) === - 1 ) { + return this; - listeners[ type ].push( listener ); + }, - } + toArray: function ( array, offset ) { - }, + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - hasEventListener: function ( type, listener ) { + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; - if ( this._listeners === undefined ) return false; + return array; - var listeners = this._listeners; + } - if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + }; - return true; + exports.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, + 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, + 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, + 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, + 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, + 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, + 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, + 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, + 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, + 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, + 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, + 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, + 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, + 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, + 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, + 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, + 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, + 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, + 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, + 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, + 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, + 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, + 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, + 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; - } + /** + * Uniforms library for shared webgl shaders + */ - return false; + exports.UniformsLib = { - }, + common: { - removeEventListener: function ( type, listener ) { + "diffuse": { value: new Color( 0xeeeeee ) }, + "opacity": { value: 1.0 }, - if ( this._listeners === undefined ) return; + "map": { value: null }, + "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) }, - var listeners = this._listeners; - var listenerArray = listeners[ type ]; + "specularMap": { value: null }, + "alphaMap": { value: null }, - if ( listenerArray !== undefined ) { + "envMap": { value: null }, + "flipEnvMap": { value: - 1 }, + "reflectivity": { value: 1.0 }, + "refractionRatio": { value: 0.98 } - var index = listenerArray.indexOf( listener ); + }, - if ( index !== - 1 ) { + aomap: { - listenerArray.splice( index, 1 ); + "aoMap": { value: null }, + "aoMapIntensity": { value: 1 } - } + }, - } + lightmap: { - }, + "lightMap": { value: null }, + "lightMapIntensity": { value: 1 } - dispatchEvent: function ( event ) { + }, - if ( this._listeners === undefined ) return; + emissivemap: { - var listeners = this._listeners; - var listenerArray = listeners[ event.type ]; + "emissiveMap": { value: null } - if ( listenerArray !== undefined ) { + }, - event.target = this; + bumpmap: { - var array = [], i = 0; - var length = listenerArray.length; + "bumpMap": { value: null }, + "bumpScale": { value: 1 } - for ( i = 0; i < length; i ++ ) { + }, - array[ i ] = listenerArray[ i ]; + normalmap: { - } + "normalMap": { value: null }, + "normalScale": { value: new Vector2( 1, 1 ) } - for ( i = 0; i < length; i ++ ) { + }, - array[ i ].call( this, event ); + displacementmap: { - } + "displacementMap": { value: null }, + "displacementScale": { value: 1 }, + "displacementBias": { value: 0 } - } + }, - } + roughnessmap: { -} ); + "roughnessMap": { value: null } -// File:src/core/Layers.js + }, -/** - * @author mrdoob / http://mrdoob.com/ - */ + metalnessmap: { -THREE.Layers = function () { + "metalnessMap": { value: null } - this.mask = 1; + }, -}; + fog: { -THREE.Layers.prototype = { + "fogDensity": { value: 0.00025 }, + "fogNear": { value: 1 }, + "fogFar": { value: 2000 }, + "fogColor": { value: new Color( 0xffffff ) } - constructor: THREE.Layers, + }, - set: function ( channel ) { + lights: { - this.mask = 1 << channel; + "ambientLightColor": { value: [] }, - }, + "directionalLights": { value: [], properties: { + "direction": {}, + "color": {}, - enable: function ( channel ) { + "shadow": {}, + "shadowBias": {}, + "shadowRadius": {}, + "shadowMapSize": {} + } }, - this.mask |= 1 << channel; + "directionalShadowMap": { value: [] }, + "directionalShadowMatrix": { value: [] }, - }, + "spotLights": { value: [], properties: { + "color": {}, + "position": {}, + "direction": {}, + "distance": {}, + "coneCos": {}, + "penumbraCos": {}, + "decay": {}, - toggle: function ( channel ) { + "shadow": {}, + "shadowBias": {}, + "shadowRadius": {}, + "shadowMapSize": {} + } }, - this.mask ^= 1 << channel; + "spotShadowMap": { value: [] }, + "spotShadowMatrix": { value: [] }, - }, + "pointLights": { value: [], properties: { + "color": {}, + "position": {}, + "decay": {}, + "distance": {}, - disable: function ( channel ) { + "shadow": {}, + "shadowBias": {}, + "shadowRadius": {}, + "shadowMapSize": {} + } }, - this.mask &= ~ ( 1 << channel ); + "pointShadowMap": { value: [] }, + "pointShadowMatrix": { value: [] }, - }, + "hemisphereLights": { value: [], properties: { + "direction": {}, + "skyColor": {}, + "groundColor": {} + } } - test: function ( layers ) { + }, - return ( this.mask & layers.mask ) !== 0; + points: { - } + "diffuse": { value: new Color( 0xeeeeee ) }, + "opacity": { value: 1.0 }, + "size": { value: 1.0 }, + "scale": { value: 1.0 }, + "map": { value: null }, + "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) } -}; + } -// File:src/core/Raycaster.js + }; -/** - * @author mrdoob / http://mrdoob.com/ - * @author bhouston / http://clara.io/ - * @author stephomi / http://stephaneginier.com/ - */ + /** + * Webgl Shader Library for three.js + * + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + */ -( function ( THREE ) { - THREE.Raycaster = function ( origin, direction, near, far ) { + exports.ShaderLib = { - this.ray = new THREE.Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) + 'basic': { - this.near = near || 0; - this.far = far || Infinity; + uniforms: exports.UniformsUtils.merge( [ - this.params = { - Mesh: {}, - Line: {}, - LOD: {}, - Points: { threshold: 1 }, - Sprite: {} - }; + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'fog' ] - Object.defineProperties( this.params, { - PointCloud: { - get: function () { - console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); - return this.Points; - } - } - } ); + ] ), - }; + vertexShader: exports.ShaderChunk[ 'meshbasic_vert' ], + fragmentShader: exports.ShaderChunk[ 'meshbasic_frag' ] - function ascSort( a, b ) { + }, - return a.distance - b.distance; + 'lambert': { - } + uniforms: exports.UniformsUtils.merge( [ - function intersectObject( object, raycaster, intersects, recursive ) { + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'lightmap' ], + exports.UniformsLib[ 'emissivemap' ], + exports.UniformsLib[ 'fog' ], + exports.UniformsLib[ 'lights' ], - if ( object.visible === false ) return; + { + "emissive" : { value: new Color( 0x000000 ) } + } - object.raycast( raycaster, intersects ); + ] ), - if ( recursive === true ) { + vertexShader: exports.ShaderChunk[ 'meshlambert_vert' ], + fragmentShader: exports.ShaderChunk[ 'meshlambert_frag' ] - var children = object.children; + }, - for ( var i = 0, l = children.length; i < l; i ++ ) { + 'phong': { - intersectObject( children[ i ], raycaster, intersects, true ); + uniforms: exports.UniformsUtils.merge( [ - } + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'lightmap' ], + exports.UniformsLib[ 'emissivemap' ], + exports.UniformsLib[ 'bumpmap' ], + exports.UniformsLib[ 'normalmap' ], + exports.UniformsLib[ 'displacementmap' ], + exports.UniformsLib[ 'fog' ], + exports.UniformsLib[ 'lights' ], - } + { + "emissive" : { value: new Color( 0x000000 ) }, + "specular" : { value: new Color( 0x111111 ) }, + "shininess": { value: 30 } + } - } + ] ), - // + vertexShader: exports.ShaderChunk[ 'meshphong_vert' ], + fragmentShader: exports.ShaderChunk[ 'meshphong_frag' ] - THREE.Raycaster.prototype = { + }, - constructor: THREE.Raycaster, + 'standard': { - linePrecision: 1, + uniforms: exports.UniformsUtils.merge( [ - set: function ( origin, direction ) { + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'lightmap' ], + exports.UniformsLib[ 'emissivemap' ], + exports.UniformsLib[ 'bumpmap' ], + exports.UniformsLib[ 'normalmap' ], + exports.UniformsLib[ 'displacementmap' ], + exports.UniformsLib[ 'roughnessmap' ], + exports.UniformsLib[ 'metalnessmap' ], + exports.UniformsLib[ 'fog' ], + exports.UniformsLib[ 'lights' ], - // direction is assumed to be normalized (for accurate distance calculations) + { + "emissive" : { value: new Color( 0x000000 ) }, + "roughness": { value: 0.5 }, + "metalness": { value: 0 }, + "envMapIntensity" : { value: 1 }, // temporary + } - this.ray.set( origin, direction ); + ] ), - }, + vertexShader: exports.ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: exports.ShaderChunk[ 'meshphysical_frag' ] - setFromCamera: function ( coords, camera ) { + }, - if ( camera instanceof THREE.PerspectiveCamera ) { + 'points': { - this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); - this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + uniforms: exports.UniformsUtils.merge( [ - } else if ( camera instanceof THREE.OrthographicCamera ) { + exports.UniformsLib[ 'points' ], + exports.UniformsLib[ 'fog' ] - this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera - this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); + ] ), - } else { + vertexShader: exports.ShaderChunk[ 'points_vert' ], + fragmentShader: exports.ShaderChunk[ 'points_frag' ] - console.error( 'THREE.Raycaster: Unsupported camera type.' ); + }, - } + 'dashed': { - }, + uniforms: exports.UniformsUtils.merge( [ - intersectObject: function ( object, recursive ) { + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'fog' ], - var intersects = []; + { + "scale" : { value: 1 }, + "dashSize" : { value: 1 }, + "totalSize": { value: 2 } + } - intersectObject( object, this, intersects, recursive ); + ] ), - intersects.sort( ascSort ); + vertexShader: exports.ShaderChunk[ 'linedashed_vert' ], + fragmentShader: exports.ShaderChunk[ 'linedashed_frag' ] - return intersects; + }, - }, + 'depth': { - intersectObjects: function ( objects, recursive ) { + uniforms: exports.UniformsUtils.merge( [ - var intersects = []; + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'displacementmap' ] - if ( Array.isArray( objects ) === false ) { + ] ), - console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); - return intersects; + vertexShader: exports.ShaderChunk[ 'depth_vert' ], + fragmentShader: exports.ShaderChunk[ 'depth_frag' ] - } + }, - for ( var i = 0, l = objects.length; i < l; i ++ ) { + 'normal': { - intersectObject( objects[ i ], this, intersects, recursive ); + uniforms: { - } + "opacity" : { value: 1.0 } - intersects.sort( ascSort ); + }, - return intersects; + vertexShader: exports.ShaderChunk[ 'normal_vert' ], + fragmentShader: exports.ShaderChunk[ 'normal_frag' ] - } + }, - }; + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ -}( THREE ) ); + 'cube': { -// File:src/core/Object3D.js + uniforms: { + "tCube": { value: null }, + "tFlip": { value: - 1 }, + "opacity": { value: 1.0 } + }, -/** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author elephantatwork / www.elephantatwork.ch - */ + vertexShader: exports.ShaderChunk[ 'cube_vert' ], + fragmentShader: exports.ShaderChunk[ 'cube_frag' ] -THREE.Object3D = function () { + }, - Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } ); + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - this.uuid = THREE.Math.generateUUID(); + 'equirect': { - this.name = ''; - this.type = 'Object3D'; + uniforms: { + "tEquirect": { value: null }, + "tFlip": { value: - 1 } + }, - this.parent = null; - this.children = []; + vertexShader: exports.ShaderChunk[ 'equirect_vert' ], + fragmentShader: exports.ShaderChunk[ 'equirect_frag' ] - this.up = THREE.Object3D.DefaultUp.clone(); + }, - var position = new THREE.Vector3(); - var rotation = new THREE.Euler(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3( 1, 1, 1 ); + 'distanceRGBA': { - function onRotationChange() { + uniforms: { - quaternion.setFromEuler( rotation, false ); + "lightPos": { value: new Vector3() } - } + }, - function onQuaternionChange() { + vertexShader: exports.ShaderChunk[ 'distanceRGBA_vert' ], + fragmentShader: exports.ShaderChunk[ 'distanceRGBA_frag' ] - rotation.setFromQuaternion( quaternion, undefined, false ); + } - } + }; - rotation.onChange( onRotationChange ); - quaternion.onChange( onQuaternionChange ); + exports.ShaderLib[ 'physical' ] = { - Object.defineProperties( this, { - position: { - enumerable: true, - value: position - }, - rotation: { - enumerable: true, - value: rotation - }, - quaternion: { - enumerable: true, - value: quaternion - }, - scale: { - enumerable: true, - value: scale - }, - modelViewMatrix: { - value: new THREE.Matrix4() - }, - normalMatrix: { - value: new THREE.Matrix3() - } - } ); + uniforms: exports.UniformsUtils.merge( [ - this.matrix = new THREE.Matrix4(); - this.matrixWorld = new THREE.Matrix4(); + exports.ShaderLib[ 'standard' ].uniforms, - this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate; - this.matrixWorldNeedsUpdate = false; + { + "clearCoat": { value: 0 }, + "clearCoatRoughness": { value: 0 } + } - this.layers = new THREE.Layers(); - this.visible = true; + ] ), - this.castShadow = false; - this.receiveShadow = false; + vertexShader: exports.ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: exports.ShaderChunk[ 'meshphysical_frag' ] - this.frustumCulled = true; - this.renderOrder = 0; + }; - this.userData = {}; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / https://clara.io + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * + * opacity: , + * + * map: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * wireframe: , + * wireframeLinewidth: + * } + */ -}; + function MeshDepthMaterial ( parameters ) { + this.isMeshDepthMaterial = this.isMaterial = true; -THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 ); -THREE.Object3D.DefaultMatrixAutoUpdate = true; + Material.call( this ); -Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { + this.type = 'MeshDepthMaterial'; - applyMatrix: function ( matrix ) { + this.depthPacking = BasicDepthPacking; - this.matrix.multiplyMatrices( matrix, this.matrix ); + this.skinning = false; + this.morphTargets = false; - this.matrix.decompose( this.position, this.quaternion, this.scale ); + this.map = null; - }, + this.alphaMap = null; - setRotationFromAxisAngle: function ( axis, angle ) { + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - // assumes axis is normalized + this.wireframe = false; + this.wireframeLinewidth = 1; - this.quaternion.setFromAxisAngle( axis, angle ); + this.fog = false; + this.lights = false; - }, + this.setValues( parameters ); - setRotationFromEuler: function ( euler ) { + }; - this.quaternion.setFromEuler( euler, true ); + MeshDepthMaterial.prototype = Object.create( Material.prototype ); + MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; - }, + MeshDepthMaterial.prototype.copy = function ( source ) { - setRotationFromMatrix: function ( m ) { + Material.prototype.copy.call( this, source ); - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + this.depthPacking = source.depthPacking; - this.quaternion.setFromRotationMatrix( m ); + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - }, + this.map = source.map; - setRotationFromQuaternion: function ( q ) { + this.alphaMap = source.alphaMap; - // assumes q is normalized + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - this.quaternion.copy( q ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - }, + return this; - rotateOnAxis: function () { + }; - // rotate object on axis in object space - // axis is assumed to be normalized + /** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - var q1 = new THREE.Quaternion(); + function Box3 ( min, max ) { + this.isBox3 = true; - return function rotateOnAxis( axis, angle ) { + this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); - q1.setFromAxisAngle( axis, angle ); + }; - this.quaternion.multiply( q1 ); + Box3.prototype = { - return this; + constructor: Box3, - }; + set: function ( min, max ) { - }(), + this.min.copy( min ); + this.max.copy( max ); - rotateX: function () { + return this; - var v1 = new THREE.Vector3( 1, 0, 0 ); + }, - return function rotateX( angle ) { + setFromArray: function ( array ) { - return this.rotateOnAxis( v1, angle ); + var minX = + Infinity; + var minY = + Infinity; + var minZ = + Infinity; - }; + var maxX = - Infinity; + var maxY = - Infinity; + var maxZ = - Infinity; - }(), + for ( var i = 0, l = array.length; i < l; i += 3 ) { - rotateY: function () { + var x = array[ i ]; + var y = array[ i + 1 ]; + var z = array[ i + 2 ]; - var v1 = new THREE.Vector3( 0, 1, 0 ); + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - return function rotateY( angle ) { + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; - return this.rotateOnAxis( v1, angle ); + } - }; + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - }(), + }, - rotateZ: function () { + setFromPoints: function ( points ) { - var v1 = new THREE.Vector3( 0, 0, 1 ); + this.makeEmpty(); - return function rotateZ( angle ) { + for ( var i = 0, il = points.length; i < il; i ++ ) { - return this.rotateOnAxis( v1, angle ); + this.expandByPoint( points[ i ] ); - }; + } - }(), + return this; - translateOnAxis: function () { + }, - // translate object by distance along axis in object space - // axis is assumed to be normalized + setFromCenterAndSize: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); - return function translateOnAxis( axis, distance ) { + return function setFromCenterAndSize( center, size ) { - v1.copy( axis ).applyQuaternion( this.quaternion ); + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - this.position.add( v1.multiplyScalar( distance ) ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - return this; + return this; - }; + }; - }(), + }(), - translateX: function () { + setFromObject: function () { - var v1 = new THREE.Vector3( 1, 0, 0 ); + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms - return function translateX( distance ) { + var v1 = new Vector3(); - return this.translateOnAxis( v1, distance ); + return function setFromObject( object ) { - }; + var scope = this; - }(), + object.updateMatrixWorld( true ); - translateY: function () { + this.makeEmpty(); - var v1 = new THREE.Vector3( 0, 1, 0 ); + object.traverse( function ( node ) { - return function translateY( distance ) { + var geometry = node.geometry; - return this.translateOnAxis( v1, distance ); + if ( geometry !== undefined ) { - }; + if ( (geometry && geometry.isGeometry) ) { - }(), + var vertices = geometry.vertices; - translateZ: function () { + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - var v1 = new THREE.Vector3( 0, 0, 1 ); + v1.copy( vertices[ i ] ); + v1.applyMatrix4( node.matrixWorld ); - return function translateZ( distance ) { + scope.expandByPoint( v1 ); - return this.translateOnAxis( v1, distance ); + } - }; + } else if ( (geometry && geometry.isBufferGeometry) ) { - }(), + var attribute = geometry.attributes.position; - localToWorld: function ( vector ) { + if ( attribute !== undefined ) { - return vector.applyMatrix4( this.matrixWorld ); + var array, offset, stride; - }, + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - worldToLocal: function () { + array = attribute.data.array; + offset = attribute.offset; + stride = attribute.data.stride; - var m1 = new THREE.Matrix4(); + } else { - return function worldToLocal( vector ) { + array = attribute.array; + offset = 0; + stride = 3; - return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); + } - }; + for ( var i = offset, il = array.length; i < il; i += stride ) { - }(), + v1.fromArray( array, i ); + v1.applyMatrix4( node.matrixWorld ); - lookAt: function () { + scope.expandByPoint( v1 ); - // This routine does not support objects with rotated and/or translated parent(s) + } - var m1 = new THREE.Matrix4(); + } - return function lookAt( vector ) { + } - m1.lookAt( vector, this.position, this.up ); + } - this.quaternion.setFromRotationMatrix( m1 ); + } ); - }; + return this; - }(), + }; - add: function ( object ) { + }(), - if ( arguments.length > 1 ) { + clone: function () { - for ( var i = 0; i < arguments.length; i ++ ) { + return new this.constructor().copy( this ); - this.add( arguments[ i ] ); + }, - } + copy: function ( box ) { - return this; + this.min.copy( box.min ); + this.max.copy( box.max ); - } + return this; - if ( object === this ) { + }, - console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); - return this; + makeEmpty: function () { - } + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; - if ( object instanceof THREE.Object3D ) { + return this; - if ( object.parent !== null ) { + }, - object.parent.remove( object ); + isEmpty: function () { - } + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - object.parent = this; - object.dispatchEvent( { type: 'added' } ); + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - this.children.push( object ); + }, - } else { + center: function ( optionalTarget ) { - console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); + var result = optionalTarget || new Vector3(); + return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - } + }, - return this; + size: function ( optionalTarget ) { - }, + var result = optionalTarget || new Vector3(); + return result.subVectors( this.max, this.min ); - remove: function ( object ) { + }, - if ( arguments.length > 1 ) { + expandByPoint: function ( point ) { - for ( var i = 0; i < arguments.length; i ++ ) { + this.min.min( point ); + this.max.max( point ); - this.remove( arguments[ i ] ); + return this; - } + }, - } + expandByVector: function ( vector ) { - var index = this.children.indexOf( object ); + this.min.sub( vector ); + this.max.add( vector ); - if ( index !== - 1 ) { + return this; - object.parent = null; + }, - object.dispatchEvent( { type: 'removed' } ); + expandByScalar: function ( scalar ) { - this.children.splice( index, 1 ); + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - } + return this; - }, + }, - getObjectById: function ( id ) { + containsPoint: function ( point ) { - return this.getObjectByProperty( 'id', id ); + if ( point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y || + point.z < this.min.z || point.z > this.max.z ) { - }, + return false; - getObjectByName: function ( name ) { + } - return this.getObjectByProperty( 'name', name ); + return true; - }, + }, - getObjectByProperty: function ( name, value ) { + containsBox: function ( box ) { - if ( this[ name ] === value ) return this; + if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && + ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) && + ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) { - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + return true; - var child = this.children[ i ]; - var object = child.getObjectByProperty( name, value ); + } - if ( object !== undefined ) { + return false; - return object; + }, - } + getParameter: function ( point, optionalTarget ) { - } + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - return undefined; + var result = optionalTarget || new Vector3(); - }, + return result.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ), + ( point.z - this.min.z ) / ( this.max.z - this.min.z ) + ); - getWorldPosition: function ( optionalTarget ) { + }, - var result = optionalTarget || new THREE.Vector3(); + intersectsBox: function ( box ) { - this.updateMatrixWorld( true ); + // using 6 splitting planes to rule out intersections. - return result.setFromMatrixPosition( this.matrixWorld ); + if ( box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y || + box.max.z < this.min.z || box.min.z > this.max.z ) { - }, + return false; - getWorldQuaternion: function () { + } - var position = new THREE.Vector3(); - var scale = new THREE.Vector3(); + return true; - return function getWorldQuaternion( optionalTarget ) { + }, - var result = optionalTarget || new THREE.Quaternion(); + intersectsSphere: ( function () { - this.updateMatrixWorld( true ); + var closestPoint; - this.matrixWorld.decompose( position, result, scale ); + return function intersectsSphere( sphere ) { - return result; + if ( closestPoint === undefined ) closestPoint = new Vector3(); - }; + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, closestPoint ); - }(), + // If that point is inside the sphere, the AABB and sphere intersect. + return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); - getWorldRotation: function () { + }; - var quaternion = new THREE.Quaternion(); + } )(), - return function getWorldRotation( optionalTarget ) { + intersectsPlane: function ( plane ) { - var result = optionalTarget || new THREE.Euler(); + // We compute the minimum and maximum dot product values. If those values + // are on the same side (back or front) of the plane, then there is no intersection. - this.getWorldQuaternion( quaternion ); + var min, max; - return result.setFromQuaternion( quaternion, this.rotation.order, false ); + if ( plane.normal.x > 0 ) { - }; + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; - }(), + } else { - getWorldScale: function () { + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); + } - return function getWorldScale( optionalTarget ) { + if ( plane.normal.y > 0 ) { - var result = optionalTarget || new THREE.Vector3(); + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; - this.updateMatrixWorld( true ); + } else { - this.matrixWorld.decompose( position, quaternion, result ); + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; - return result; + } - }; + if ( plane.normal.z > 0 ) { - }(), + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; - getWorldDirection: function () { + } else { - var quaternion = new THREE.Quaternion(); + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; - return function getWorldDirection( optionalTarget ) { + } - var result = optionalTarget || new THREE.Vector3(); + return ( min <= plane.constant && max >= plane.constant ); - this.getWorldQuaternion( quaternion ); + }, - return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); + clampPoint: function ( point, optionalTarget ) { - }; + var result = optionalTarget || new Vector3(); + return result.copy( point ).clamp( this.min, this.max ); - }(), + }, - raycast: function () {}, + distanceToPoint: function () { - traverse: function ( callback ) { + var v1 = new Vector3(); - callback( this ); + return function distanceToPoint( point ) { - var children = this.children; + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - for ( var i = 0, l = children.length; i < l; i ++ ) { + }; - children[ i ].traverse( callback ); + }(), - } + getBoundingSphere: function () { - }, + var v1 = new Vector3(); - traverseVisible: function ( callback ) { + return function getBoundingSphere( optionalTarget ) { - if ( this.visible === false ) return; + var result = optionalTarget || new Sphere(); - callback( this ); + result.center = this.center(); + result.radius = this.size( v1 ).length() * 0.5; - var children = this.children; + return result; - for ( var i = 0, l = children.length; i < l; i ++ ) { + }; - children[ i ].traverseVisible( callback ); + }(), - } + intersect: function ( box ) { - }, + this.min.max( box.min ); + this.max.min( box.max ); - traverseAncestors: function ( callback ) { + // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. + if( this.isEmpty() ) this.makeEmpty(); - var parent = this.parent; + return this; - if ( parent !== null ) { + }, - callback( parent ); + union: function ( box ) { - parent.traverseAncestors( callback ); + this.min.min( box.min ); + this.max.max( box.max ); - } + return this; - }, + }, - updateMatrix: function () { + applyMatrix4: function () { - this.matrix.compose( this.position, this.quaternion, this.scale ); + var points = [ + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() + ]; - this.matrixWorldNeedsUpdate = true; + return function applyMatrix4( matrix ) { - }, + // transform of empty box is an empty box. + if( this.isEmpty() ) return this; - updateMatrixWorld: function ( force ) { + // NOTE: I am using a binary pattern to specify all 2^3 combinations below + points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 + points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 + points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 + points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 + points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 + points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 + points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 + points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 - if ( this.matrixAutoUpdate === true ) this.updateMatrix(); + this.setFromPoints( points ); - if ( this.matrixWorldNeedsUpdate === true || force === true ) { + return this; - if ( this.parent === null ) { + }; - this.matrixWorld.copy( this.matrix ); + }(), - } else { + translate: function ( offset ) { - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + this.min.add( offset ); + this.max.add( offset ); - } + return this; - this.matrixWorldNeedsUpdate = false; + }, - force = true; + equals: function ( box ) { - } + return box.min.equals( this.min ) && box.max.equals( this.max ); - // update children + } - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + }; - this.children[ i ].updateMatrixWorld( force ); + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - } + function Sphere ( center, radius ) { + this.isSphere = true; - }, + this.center = ( center !== undefined ) ? center : new Vector3(); + this.radius = ( radius !== undefined ) ? radius : 0; - toJSON: function ( meta ) { + }; - // meta is '' when called from JSON.stringify - var isRootObject = ( meta === undefined || meta === '' ); + Sphere.prototype = { - var output = {}; + constructor: Sphere, - // meta is a hash used to collect geometries, materials. - // not providing it implies that this is the root object - // being serialized. - if ( isRootObject ) { + set: function ( center, radius ) { - // initialize meta obj - meta = { - geometries: {}, - materials: {}, - textures: {}, - images: {} - }; + this.center.copy( center ); + this.radius = radius; - output.metadata = { - version: 4.4, - type: 'Object', - generator: 'Object3D.toJSON' - }; + return this; - } + }, - // standard Object3D serialization + setFromPoints: function () { - var object = {}; + var box = new Box3(); - object.uuid = this.uuid; - object.type = this.type; + return function setFromPoints( points, optionalCenter ) { - if ( this.name !== '' ) object.name = this.name; - if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; - if ( this.castShadow === true ) object.castShadow = true; - if ( this.receiveShadow === true ) object.receiveShadow = true; - if ( this.visible === false ) object.visible = false; + var center = this.center; - object.matrix = this.matrix.toArray(); + if ( optionalCenter !== undefined ) { - // + center.copy( optionalCenter ); - if ( this.geometry !== undefined ) { + } else { - if ( meta.geometries[ this.geometry.uuid ] === undefined ) { + box.setFromPoints( points ).center( center ); - meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta ); + } - } + var maxRadiusSq = 0; - object.geometry = this.geometry.uuid; + for ( var i = 0, il = points.length; i < il; i ++ ) { - } + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - if ( this.material !== undefined ) { + } - if ( meta.materials[ this.material.uuid ] === undefined ) { + this.radius = Math.sqrt( maxRadiusSq ); - meta.materials[ this.material.uuid ] = this.material.toJSON( meta ); + return this; - } + }; - object.material = this.material.uuid; + }(), - } + clone: function () { - // + return new this.constructor().copy( this ); - if ( this.children.length > 0 ) { + }, - object.children = []; + copy: function ( sphere ) { - for ( var i = 0; i < this.children.length; i ++ ) { + this.center.copy( sphere.center ); + this.radius = sphere.radius; - object.children.push( this.children[ i ].toJSON( meta ).object ); + return this; - } + }, - } + empty: function () { - if ( isRootObject ) { + return ( this.radius <= 0 ); - var geometries = extractFromCache( meta.geometries ); - var materials = extractFromCache( meta.materials ); - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + }, - if ( geometries.length > 0 ) output.geometries = geometries; - if ( materials.length > 0 ) output.materials = materials; - if ( textures.length > 0 ) output.textures = textures; - if ( images.length > 0 ) output.images = images; + containsPoint: function ( point ) { - } + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - output.object = object; + }, - return output; + distanceToPoint: function ( point ) { - // extract data from the cache hash - // remove metadata on each item - // and return as array - function extractFromCache ( cache ) { + return ( point.distanceTo( this.center ) - this.radius ); - var values = []; - for ( var key in cache ) { + }, - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + intersectsSphere: function ( sphere ) { - } - return values; + var radiusSum = this.radius + sphere.radius; - } + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - }, + }, - clone: function ( recursive ) { + intersectsBox: function ( box ) { - return new this.constructor().copy( this, recursive ); + return box.intersectsSphere( this ); - }, + }, - copy: function ( source, recursive ) { + intersectsPlane: function ( plane ) { - if ( recursive === undefined ) recursive = true; + // We use the following equation to compute the signed distance from + // the center of the sphere to the plane. + // + // distance = q * n - d + // + // If this distance is greater than the radius of the sphere, + // then there is no intersection. - this.name = source.name; + return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; - this.up.copy( source.up ); + }, - this.position.copy( source.position ); - this.quaternion.copy( source.quaternion ); - this.scale.copy( source.scale ); + clampPoint: function ( point, optionalTarget ) { - this.matrix.copy( source.matrix ); - this.matrixWorld.copy( source.matrixWorld ); + var deltaLengthSq = this.center.distanceToSquared( point ); - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + var result = optionalTarget || new Vector3(); - this.visible = source.visible; + result.copy( point ); - this.castShadow = source.castShadow; - this.receiveShadow = source.receiveShadow; + if ( deltaLengthSq > ( this.radius * this.radius ) ) { - this.frustumCulled = source.frustumCulled; - this.renderOrder = source.renderOrder; + result.sub( this.center ).normalize(); + result.multiplyScalar( this.radius ).add( this.center ); - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + } - if ( recursive === true ) { + return result; - for ( var i = 0; i < source.children.length; i ++ ) { + }, - var child = source.children[ i ]; - this.add( child.clone() ); + getBoundingBox: function ( optionalTarget ) { - } + var box = optionalTarget || new Box3(); - } + box.set( this.center, this.center ); + box.expandByScalar( this.radius ); - return this; + return box; - } + }, -} ); + applyMatrix4: function ( matrix ) { -THREE.Object3DIdCount = 0; + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); -// File:src/core/Face3.js + return this; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + }, -THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) { + translate: function ( offset ) { - this.a = a; - this.b = b; - this.c = c; + this.center.add( offset ); - this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3(); - this.vertexNormals = Array.isArray( normal ) ? normal : []; + return this; - this.color = color instanceof THREE.Color ? color : new THREE.Color(); - this.vertexColors = Array.isArray( color ) ? color : []; + }, - this.materialIndex = materialIndex !== undefined ? materialIndex : 0; + equals: function ( sphere ) { -}; + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); -THREE.Face3.prototype = { + } - constructor: THREE.Face3, + }; - clone: function () { + /** + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + * @author tschw + */ - return new this.constructor().copy( this ); + function Matrix3 () { + this.isMatrix3 = true; - }, + this.elements = new Float32Array( [ - copy: function ( source ) { + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - this.a = source.a; - this.b = source.b; - this.c = source.c; + ] ); - this.normal.copy( source.normal ); - this.color.copy( source.color ); + if ( arguments.length > 0 ) { - this.materialIndex = source.materialIndex; + console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { + } - this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); + }; - } + Matrix3.prototype = { - for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { + constructor: Matrix3, - this.vertexColors[ i ] = source.vertexColors[ i ].clone(); + set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { - } + var te = this.elements; - return this; + te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; + te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; + te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; - } + return this; -}; + }, -// File:src/core/BufferAttribute.js + identity: function () { -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.set( -THREE.BufferAttribute = function ( array, itemSize, normalized ) { + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - this.uuid = THREE.Math.generateUUID(); + ); - this.array = array; - this.itemSize = itemSize; + return this; - this.dynamic = false; - this.updateRange = { offset: 0, count: - 1 }; + }, - this.version = 0; - this.normalized = normalized === true; + clone: function () { -}; + return new this.constructor().fromArray( this.elements ); -THREE.BufferAttribute.prototype = { + }, - constructor: THREE.BufferAttribute, + copy: function ( m ) { - get count() { + var me = m.elements; - return this.array.length / this.itemSize; + this.set( - }, + me[ 0 ], me[ 3 ], me[ 6 ], + me[ 1 ], me[ 4 ], me[ 7 ], + me[ 2 ], me[ 5 ], me[ 8 ] - set needsUpdate( value ) { + ); - if ( value === true ) this.version ++; + return this; - }, + }, - setDynamic: function ( value ) { + setFromMatrix4: function( m ) { - this.dynamic = value; + var me = m.elements; - return this; + this.set( - }, + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] - copy: function ( source ) { + ); - this.array = new source.array.constructor( source.array ); - this.itemSize = source.itemSize; + return this; - this.dynamic = source.dynamic; + }, - return this; + applyToVector3Array: function () { - }, + var v1; - copyAt: function ( index1, attribute, index2 ) { + return function applyToVector3Array( array, offset, length ) { - index1 *= this.itemSize; - index2 *= attribute.itemSize; + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - for ( var i = 0, l = this.itemSize; i < l; i ++ ) { + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + v1.fromArray( array, j ); + v1.applyMatrix3( this ); + v1.toArray( array, j ); - } + } - return this; + return array; - }, + }; - copyArray: function ( array ) { + }(), - this.array.set( array ); + applyToBuffer: function () { - return this; + var v1; - }, + return function applyToBuffer( buffer, offset, length ) { - copyColorsArray: function ( colors ) { + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = buffer.length / buffer.itemSize; - var array = this.array, offset = 0; + for ( var i = 0, j = offset; i < length; i ++, j ++ ) { - for ( var i = 0, l = colors.length; i < l; i ++ ) { + v1.x = buffer.getX( j ); + v1.y = buffer.getY( j ); + v1.z = buffer.getZ( j ); - var color = colors[ i ]; + v1.applyMatrix3( this ); - if ( color === undefined ) { + buffer.setXYZ( v1.x, v1.y, v1.z ); - console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new THREE.Color(); + } - } + return buffer; - array[ offset ++ ] = color.r; - array[ offset ++ ] = color.g; - array[ offset ++ ] = color.b; + }; - } + }(), - return this; + multiplyScalar: function ( s ) { - }, + var te = this.elements; - copyIndicesArray: function ( indices ) { + te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; + te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; + te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; - var array = this.array, offset = 0; + return this; - for ( var i = 0, l = indices.length; i < l; i ++ ) { + }, - var index = indices[ i ]; + determinant: function () { - array[ offset ++ ] = index.a; - array[ offset ++ ] = index.b; - array[ offset ++ ] = index.c; + var te = this.elements; - } + var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], + d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], + g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; - return this; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; - }, + }, - copyVector2sArray: function ( vectors ) { + getInverse: function ( matrix, throwOnDegenerate ) { - var array = this.array, offset = 0; + if ( (matrix && matrix.isMatrix4) ) { - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); - var vector = vectors[ i ]; + } - if ( vector === undefined ) { + var me = matrix.elements, + te = this.elements, - console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new THREE.Vector2(); + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], + n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], + n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], - } + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; + det = n11 * t11 + n21 * t12 + n31 * t13; - } + if ( det === 0 ) { - return this; + var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; - }, + if ( throwOnDegenerate || false ) {} else { - copyVector3sArray: function ( vectors ) { + console.warn( msg ); - var array = this.array, offset = 0; + } - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + return this.identity(); + } + + var detInv = 1 / det; - var vector = vectors[ i ]; + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; - if ( vector === undefined ) { + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; - console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new THREE.Vector3(); + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; - } + return this; - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; + }, - } + transpose: function () { - return this; + var tmp, m = this.elements; - }, + tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; + tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; + tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; - copyVector4sArray: function ( vectors ) { + return this; - var array = this.array, offset = 0; + }, - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + flattenToArrayOffset: function ( array, offset ) { - var vector = vectors[ i ]; + console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + + "- just use .toArray instead." ); - if ( vector === undefined ) { + return this.toArray( array, offset ); - console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new THREE.Vector4(); + }, - } + getNormalMatrix: function ( matrix4 ) { - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; - array[ offset ++ ] = vector.w; + return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); - } + }, - return this; + transposeIntoArray: function ( r ) { - }, + var m = this.elements; - set: function ( value, offset ) { + r[ 0 ] = m[ 0 ]; + r[ 1 ] = m[ 3 ]; + r[ 2 ] = m[ 6 ]; + r[ 3 ] = m[ 1 ]; + r[ 4 ] = m[ 4 ]; + r[ 5 ] = m[ 7 ]; + r[ 6 ] = m[ 2 ]; + r[ 7 ] = m[ 5 ]; + r[ 8 ] = m[ 8 ]; - if ( offset === undefined ) offset = 0; + return this; - this.array.set( value, offset ); + }, - return this; + fromArray: function ( array ) { - }, + this.elements.set( array ); - getX: function ( index ) { + return this; - return this.array[ index * this.itemSize ]; + }, - }, + toArray: function ( array, offset ) { - setX: function ( index, x ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - this.array[ index * this.itemSize ] = x; + var te = this.elements; - return this; + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; - }, + array[ offset + 3 ] = te[ 3 ]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; - getY: function ( index ) { + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; - return this.array[ index * this.itemSize + 1 ]; + return array; - }, + } - setY: function ( index, y ) { + }; - this.array[ index * this.itemSize + 1 ] = y; + /** + * @author bhouston / http://clara.io + */ - return this; + function Plane ( normal, constant ) { + this.isPlane = true; - }, + this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); + this.constant = ( constant !== undefined ) ? constant : 0; - getZ: function ( index ) { + }; - return this.array[ index * this.itemSize + 2 ]; + Plane.prototype = { - }, + constructor: Plane, - setZ: function ( index, z ) { + set: function ( normal, constant ) { - this.array[ index * this.itemSize + 2 ] = z; + this.normal.copy( normal ); + this.constant = constant; - return this; + return this; - }, + }, - getW: function ( index ) { + setComponents: function ( x, y, z, w ) { - return this.array[ index * this.itemSize + 3 ]; + this.normal.set( x, y, z ); + this.constant = w; - }, + return this; - setW: function ( index, w ) { + }, - this.array[ index * this.itemSize + 3 ] = w; + setFromNormalAndCoplanarPoint: function ( normal, point ) { - return this; + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized - }, + return this; - setXY: function ( index, x, y ) { + }, - index *= this.itemSize; + setFromCoplanarPoints: function () { - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; + var v1 = new Vector3(); + var v2 = new Vector3(); - return this; + return function setFromCoplanarPoints( a, b, c ) { - }, + var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); - setXYZ: function ( index, x, y, z ) { + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - index *= this.itemSize; + this.setFromNormalAndCoplanarPoint( normal, a ); - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; + return this; - return this; + }; - }, + }(), - setXYZW: function ( index, x, y, z, w ) { + clone: function () { - index *= this.itemSize; + return new this.constructor().copy( this ); - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; - this.array[ index + 3 ] = w; + }, - return this; + copy: function ( plane ) { - }, + this.normal.copy( plane.normal ); + this.constant = plane.constant; - clone: function () { + return this; - return new this.constructor().copy( this ); + }, - } + normalize: function () { -}; + // Note: will lead to a divide by zero if the plane is invalid. -// + var inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; -THREE.Int8Attribute = function ( array, itemSize ) { + return this; - return new THREE.BufferAttribute( new Int8Array( array ), itemSize ); + }, -}; + negate: function () { -THREE.Uint8Attribute = function ( array, itemSize ) { + this.constant *= - 1; + this.normal.negate(); - return new THREE.BufferAttribute( new Uint8Array( array ), itemSize ); + return this; -}; + }, -THREE.Uint8ClampedAttribute = function ( array, itemSize ) { + distanceToPoint: function ( point ) { - return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize ); + return this.normal.dot( point ) + this.constant; -}; + }, -THREE.Int16Attribute = function ( array, itemSize ) { + distanceToSphere: function ( sphere ) { - return new THREE.BufferAttribute( new Int16Array( array ), itemSize ); + return this.distanceToPoint( sphere.center ) - sphere.radius; -}; + }, -THREE.Uint16Attribute = function ( array, itemSize ) { + projectPoint: function ( point, optionalTarget ) { - return new THREE.BufferAttribute( new Uint16Array( array ), itemSize ); + return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); -}; + }, -THREE.Int32Attribute = function ( array, itemSize ) { + orthoPoint: function ( point, optionalTarget ) { - return new THREE.BufferAttribute( new Int32Array( array ), itemSize ); + var perpendicularMagnitude = this.distanceToPoint( point ); -}; + var result = optionalTarget || new Vector3(); + return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); -THREE.Uint32Attribute = function ( array, itemSize ) { + }, - return new THREE.BufferAttribute( new Uint32Array( array ), itemSize ); + intersectLine: function () { -}; + var v1 = new Vector3(); -THREE.Float32Attribute = function ( array, itemSize ) { + return function intersectLine( line, optionalTarget ) { - return new THREE.BufferAttribute( new Float32Array( array ), itemSize ); + var result = optionalTarget || new Vector3(); -}; + var direction = line.delta( v1 ); -THREE.Float64Attribute = function ( array, itemSize ) { + var denominator = this.normal.dot( direction ); - return new THREE.BufferAttribute( new Float64Array( array ), itemSize ); + if ( denominator === 0 ) { -}; + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { + return result.copy( line.start ); -// Deprecated + } -THREE.DynamicBufferAttribute = function ( array, itemSize ) { + // Unsure if this is the correct method to handle this case. + return undefined; - console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); - return new THREE.BufferAttribute( array, itemSize ).setDynamic( true ); + } -}; + var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; -// File:src/core/InstancedBufferAttribute.js + if ( t < 0 || t > 1 ) { -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + return undefined; -THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) { + } - THREE.BufferAttribute.call( this, array, itemSize ); + return result.copy( direction ).multiplyScalar( t ).add( line.start ); - this.meshPerAttribute = meshPerAttribute || 1; + }; -}; + }(), -THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype ); -THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute; + intersectsLine: function ( line ) { -THREE.InstancedBufferAttribute.prototype.copy = function ( source ) { + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - THREE.BufferAttribute.prototype.copy.call( this, source ); + var startSign = this.distanceToPoint( line.start ); + var endSign = this.distanceToPoint( line.end ); - this.meshPerAttribute = source.meshPerAttribute; + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - return this; + }, -}; + intersectsBox: function ( box ) { -// File:src/core/InterleavedBuffer.js + return box.intersectsPlane( this ); -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + }, -THREE.InterleavedBuffer = function ( array, stride ) { + intersectsSphere: function ( sphere ) { - this.uuid = THREE.Math.generateUUID(); + return sphere.intersectsPlane( this ); - this.array = array; - this.stride = stride; + }, - this.dynamic = false; - this.updateRange = { offset: 0, count: - 1 }; + coplanarPoint: function ( optionalTarget ) { - this.version = 0; + var result = optionalTarget || new Vector3(); + return result.copy( this.normal ).multiplyScalar( - this.constant ); -}; + }, -THREE.InterleavedBuffer.prototype = { + applyMatrix4: function () { - constructor: THREE.InterleavedBuffer, + var v1 = new Vector3(); + var m1 = new Matrix3(); - get length () { + return function applyMatrix4( matrix, optionalNormalMatrix ) { - return this.array.length; + var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); - }, + // transform normal based on theory here: + // http://www.songho.ca/opengl/gl_normaltransform.html + var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); + var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); - get count () { + // recalculate constant (like in setFromNormalAndCoplanarPoint) + this.constant = - referencePoint.dot( normal ); - return this.array.length / this.stride; + return this; - }, + }; - set needsUpdate( value ) { + }(), - if ( value === true ) this.version ++; + translate: function ( offset ) { - }, + this.constant = this.constant - offset.dot( this.normal ); - setDynamic: function ( value ) { + return this; - this.dynamic = value; + }, - return this; + equals: function ( plane ) { - }, + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); - copy: function ( source ) { + } - this.array = new source.array.constructor( source.array ); - this.stride = source.stride; - this.dynamic = source.dynamic; + }; - return this; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / http://clara.io + */ - }, + function Frustum ( p0, p1, p2, p3, p4, p5 ) { + this.isFrustum = true; - copyAt: function ( index1, attribute, index2 ) { + this.planes = [ - index1 *= this.stride; - index2 *= attribute.stride; + ( p0 !== undefined ) ? p0 : new Plane(), + ( p1 !== undefined ) ? p1 : new Plane(), + ( p2 !== undefined ) ? p2 : new Plane(), + ( p3 !== undefined ) ? p3 : new Plane(), + ( p4 !== undefined ) ? p4 : new Plane(), + ( p5 !== undefined ) ? p5 : new Plane() - for ( var i = 0, l = this.stride; i < l; i ++ ) { + ]; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + }; - } + Frustum.prototype = { - return this; + constructor: Frustum, - }, + set: function ( p0, p1, p2, p3, p4, p5 ) { - set: function ( value, offset ) { + var planes = this.planes; - if ( offset === undefined ) offset = 0; + planes[ 0 ].copy( p0 ); + planes[ 1 ].copy( p1 ); + planes[ 2 ].copy( p2 ); + planes[ 3 ].copy( p3 ); + planes[ 4 ].copy( p4 ); + planes[ 5 ].copy( p5 ); - this.array.set( value, offset ); + return this; - return this; + }, - }, + clone: function () { - clone: function () { + return new this.constructor().copy( this ); - return new this.constructor().copy( this ); + }, - } + copy: function ( frustum ) { -}; + var planes = this.planes; -// File:src/core/InstancedInterleavedBuffer.js + for ( var i = 0; i < 6; i ++ ) { -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + planes[ i ].copy( frustum.planes[ i ] ); -THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) { + } - THREE.InterleavedBuffer.call( this, array, stride ); + return this; - this.meshPerAttribute = meshPerAttribute || 1; + }, -}; + setFromMatrix: function ( m ) { -THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype ); -THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer; + var planes = this.planes; + var me = m.elements; + var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; + var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; -THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) { + planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); + planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); + planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); + planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); + planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); + planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); - THREE.InterleavedBuffer.prototype.copy.call( this, source ); + return this; - this.meshPerAttribute = source.meshPerAttribute; + }, - return this; + intersectsObject: function () { -}; + var sphere = new Sphere(); -// File:src/core/InterleavedBufferAttribute.js + return function intersectsObject( object ) { -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + var geometry = object.geometry; -THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset, normalized ) { + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); - this.uuid = THREE.Math.generateUUID(); + sphere.copy( geometry.boundingSphere ) + .applyMatrix4( object.matrixWorld ); - this.data = interleavedBuffer; - this.itemSize = itemSize; - this.offset = offset; + return this.intersectsSphere( sphere ); - this.normalized = normalized === true; + }; -}; + }(), + intersectsSprite: function () { -THREE.InterleavedBufferAttribute.prototype = { + var sphere = new Sphere(); - constructor: THREE.InterleavedBufferAttribute, + return function intersectsSprite( sprite ) { - get length() { + sphere.center.set( 0, 0, 0 ); + sphere.radius = 0.7071067811865476; + sphere.applyMatrix4( sprite.matrixWorld ); - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); - return this.array.length; + return this.intersectsSphere( sphere ); - }, + }; - get count() { + }(), - return this.data.count; + intersectsSphere: function ( sphere ) { - }, + var planes = this.planes; + var center = sphere.center; + var negRadius = - sphere.radius; - get array() { + for ( var i = 0; i < 6; i ++ ) { - return this.data.array; + var distance = planes[ i ].distanceToPoint( center ); - }, + if ( distance < negRadius ) { - setX: function ( index, x ) { + return false; - this.data.array[ index * this.data.stride + this.offset ] = x; + } - return this; + } - }, + return true; - setY: function ( index, y ) { + }, - this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + intersectsBox: function () { - return this; + var p1 = new Vector3(), + p2 = new Vector3(); - }, + return function intersectsBox( box ) { - setZ: function ( index, z ) { + var planes = this.planes; - this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + for ( var i = 0; i < 6 ; i ++ ) { - return this; + var plane = planes[ i ]; - }, + p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; + p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; + p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; + p2.y = plane.normal.y > 0 ? box.max.y : box.min.y; + p1.z = plane.normal.z > 0 ? box.min.z : box.max.z; + p2.z = plane.normal.z > 0 ? box.max.z : box.min.z; - setW: function ( index, w ) { + var d1 = plane.distanceToPoint( p1 ); + var d2 = plane.distanceToPoint( p2 ); - this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + // if both outside plane, no intersection - return this; + if ( d1 < 0 && d2 < 0 ) { - }, + return false; - getX: function ( index ) { + } - return this.data.array[ index * this.data.stride + this.offset ]; + } - }, + return true; - getY: function ( index ) { + }; - return this.data.array[ index * this.data.stride + this.offset + 1 ]; + }(), - }, - getZ: function ( index ) { + containsPoint: function ( point ) { - return this.data.array[ index * this.data.stride + this.offset + 2 ]; + var planes = this.planes; - }, + for ( var i = 0; i < 6; i ++ ) { - getW: function ( index ) { + if ( planes[ i ].distanceToPoint( point ) < 0 ) { - return this.data.array[ index * this.data.stride + this.offset + 3 ]; + return false; - }, + } - setXY: function ( index, x, y ) { + } - index = index * this.data.stride + this.offset; + return true; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; + } - return this; + }; - }, + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - setXYZ: function ( index, x, y, z ) { + function WebGLShadowMap ( _renderer, _lights, _objects, capabilities ) { + this.isWebGLShadowMap = true; - index = index * this.data.stride + this.offset; + var _gl = _renderer.context, + _state = _renderer.state, + _frustum = new Frustum(), + _projScreenMatrix = new Matrix4(), - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; + _lightShadows = _lights.shadows, - return this; + _shadowMapSize = new Vector2(), + _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), - }, + _lookTarget = new Vector3(), + _lightPositionWorld = new Vector3(), - setXYZW: function ( index, x, y, z, w ) { + _renderList = [], - index = index * this.data.stride + this.offset; + _MorphingFlag = 1, + _SkinningFlag = 2, - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; - this.data.array[ index + 3 ] = w; + _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, - return this; + _depthMaterials = new Array( _NumberOfMaterialVariants ), + _distanceMaterials = new Array( _NumberOfMaterialVariants ), - } + _materialCache = {}; -}; + var cubeDirections = [ + new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), + new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) + ]; -// File:src/core/Geometry.js + var cubeUps = [ + new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), + new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) + ]; -/** - * @author mrdoob / http://mrdoob.com/ - * @author kile / http://kile.stravaganza.org/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author bhouston / http://clara.io - */ + var cube2DViewPorts = [ + new Vector4(), new Vector4(), new Vector4(), + new Vector4(), new Vector4(), new Vector4() + ]; -THREE.Geometry = function () { + // init - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + var depthMaterialTemplate = new MeshDepthMaterial(); + depthMaterialTemplate.depthPacking = RGBADepthPacking; + depthMaterialTemplate.clipping = true; - this.uuid = THREE.Math.generateUUID(); + var distanceShader = exports.ShaderLib[ "distanceRGBA" ]; + var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms ); - this.name = ''; - this.type = 'Geometry'; + for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [ [] ]; + var useMorphing = ( i & _MorphingFlag ) !== 0; + var useSkinning = ( i & _SkinningFlag ) !== 0; - this.morphTargets = []; - this.morphNormals = []; + var depthMaterial = depthMaterialTemplate.clone(); + depthMaterial.morphTargets = useMorphing; + depthMaterial.skinning = useSkinning; - this.skinWeights = []; - this.skinIndices = []; + _depthMaterials[ i ] = depthMaterial; - this.lineDistances = []; + var distanceMaterial = new ShaderMaterial( { + defines: { + 'USE_SHADOWMAP': '' + }, + uniforms: distanceUniforms, + vertexShader: distanceShader.vertexShader, + fragmentShader: distanceShader.fragmentShader, + morphTargets: useMorphing, + skinning: useSkinning, + clipping: true + } ); - this.boundingBox = null; - this.boundingSphere = null; + _distanceMaterials[ i ] = distanceMaterial; - // update flags + } - this.elementsNeedUpdate = false; - this.verticesNeedUpdate = false; - this.uvsNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; - this.groupsNeedUpdate = false; + // -}; + var scope = this; -Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { + this.enabled = false; - applyMatrix: function ( matrix ) { + this.autoUpdate = true; + this.needsUpdate = false; - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + this.type = PCFShadowMap; - for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { + this.renderReverseSided = true; + this.renderSingleSided = true; - var vertex = this.vertices[ i ]; - vertex.applyMatrix4( matrix ); + this.render = function ( scene, camera ) { - } + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; - for ( var i = 0, il = this.faces.length; i < il; i ++ ) { + if ( _lightShadows.length === 0 ) return; - var face = this.faces[ i ]; - face.normal.applyMatrix3( normalMatrix ).normalize(); + // Set GL state for depth map. + _state.clearColor( 1, 1, 1, 1 ); + _state.disable( _gl.BLEND ); + _state.setDepthTest( true ); + _state.setScissorTest( false ); - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + // render depth map - face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); + var faceCount, isPointLight; - } + for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) { - } + var light = _lightShadows[ i ]; + var shadow = light.shadow; - if ( this.boundingBox !== null ) { + if ( shadow === undefined ) { - this.computeBoundingBox(); + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; - } + } - if ( this.boundingSphere !== null ) { + var shadowCamera = shadow.camera; - this.computeBoundingSphere(); + _shadowMapSize.copy( shadow.mapSize ); + _shadowMapSize.min( _maxShadowMapSize ); - } + if ( (light && light.isPointLight) ) { - this.verticesNeedUpdate = true; - this.normalsNeedUpdate = true; + faceCount = 6; + isPointLight = true; - return this; + var vpWidth = _shadowMapSize.x; + var vpHeight = _shadowMapSize.y; - }, + // These viewports map a cube-map onto a 2D texture with the + // following orientation: + // + // xzXZ + // y Y + // + // X - Positive x direction + // x - Negative x direction + // Y - Positive y direction + // y - Negative y direction + // Z - Positive z direction + // z - Negative z direction - rotateX: function () { + // positive X + cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight ); + // negative X + cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight ); + // positive Z + cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight ); + // negative Z + cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight ); + // positive Y + cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight ); + // negative Y + cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight ); - // rotate geometry around world x-axis + _shadowMapSize.x *= 4.0; + _shadowMapSize.y *= 2.0; - var m1; + } else { - return function rotateX( angle ) { + faceCount = 1; + isPointLight = false; - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + } - m1.makeRotationX( angle ); + if ( shadow.map === null ) { - this.applyMatrix( m1 ); + var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; - return this; + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - }; + shadowCamera.updateProjectionMatrix(); - }(), + } - rotateY: function () { + if ( (shadow && shadow.isSpotLightShadow) ) { - // rotate geometry around world y-axis + shadow.update( light ); - var m1; + } - return function rotateY( angle ) { + var shadowMap = shadow.map; + var shadowMatrix = shadow.matrix; - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld ); - m1.makeRotationY( angle ); + _renderer.setRenderTarget( shadowMap ); + _renderer.clear(); - this.applyMatrix( m1 ); + // render shadow map for each cube face (if omni-directional) or + // run a single pass if not - return this; + for ( var face = 0; face < faceCount; face ++ ) { - }; + if ( isPointLight ) { - }(), + _lookTarget.copy( shadowCamera.position ); + _lookTarget.add( cubeDirections[ face ] ); + shadowCamera.up.copy( cubeUps[ face ] ); + shadowCamera.lookAt( _lookTarget ); - rotateZ: function () { + var vpDimensions = cube2DViewPorts[ face ]; + _state.viewport( vpDimensions ); - // rotate geometry around world z-axis + } else { - var m1; + _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget ); - return function rotateZ( angle ) { + } - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + shadowCamera.updateMatrixWorld(); + shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); - m1.makeRotationZ( angle ); + // compute shadow matrix - this.applyMatrix( m1 ); + shadowMatrix.set( + 0.5, 0.0, 0.0, 0.5, + 0.0, 0.5, 0.0, 0.5, + 0.0, 0.0, 0.5, 0.5, + 0.0, 0.0, 0.0, 1.0 + ); - return this; + shadowMatrix.multiply( shadowCamera.projectionMatrix ); + shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - }; + // update camera matrices and frustum - }(), + _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - translate: function () { + // set object matrices & frustum culling - // translate geometry + _renderList.length = 0; - var m1; + projectObject( scene, camera, shadowCamera ); - return function translate( x, y, z ) { + // render shadow map + // render regular objects - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) { - m1.makeTranslation( x, y, z ); + var object = _renderList[ j ]; + var geometry = _objects.update( object ); + var material = object.material; - this.applyMatrix( m1 ); + if ( (material && material.isMultiMaterial) ) { - return this; + var groups = geometry.groups; + var materials = material.materials; - }; + for ( var k = 0, kl = groups.length; k < kl; k ++ ) { - }(), + var group = groups[ k ]; + var groupMaterial = materials[ group.materialIndex ]; - scale: function () { + if ( groupMaterial.visible === true ) { - // scale geometry + var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); - var m1; + } - return function scale( x, y, z ) { + } - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + } else { - m1.makeScale( x, y, z ); + var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); - this.applyMatrix( m1 ); + } - return this; + } - }; + } - }(), + } - lookAt: function () { + // Restore GL state. + var clearColor = _renderer.getClearColor(), + clearAlpha = _renderer.getClearAlpha(); + _renderer.setClearColor( clearColor, clearAlpha ); - var obj; + scope.needsUpdate = false; - return function lookAt( vector ) { + }; - if ( obj === undefined ) obj = new THREE.Object3D(); + function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) { - obj.lookAt( vector ); + var geometry = object.geometry; - obj.updateMatrix(); + var result = null; - this.applyMatrix( obj.matrix ); + var materialVariants = _depthMaterials; + var customMaterial = object.customDepthMaterial; - }; + if ( isPointLight ) { - }(), + materialVariants = _distanceMaterials; + customMaterial = object.customDistanceMaterial; - fromBufferGeometry: function ( geometry ) { + } - var scope = this; + if ( ! customMaterial ) { - var indices = geometry.index !== null ? geometry.index.array : undefined; - var attributes = geometry.attributes; + var useMorphing = false; - var positions = attributes.position.array; - var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; - var colors = attributes.color !== undefined ? attributes.color.array : undefined; - var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; - var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; + if ( material.morphTargets ) { - if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; + if ( (geometry && geometry.isBufferGeometry) ) { - var tempNormals = []; - var tempUVs = []; - var tempUVs2 = []; + useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { + } else if ( (geometry && geometry.isGeometry) ) { - scope.vertices.push( new THREE.Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); + useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; - if ( normals !== undefined ) { + } - tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); + } - } + var useSkinning = (object && object.isSkinnedMesh) && material.skinning; - if ( colors !== undefined ) { + var variantIndex = 0; - scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + if ( useMorphing ) variantIndex |= _MorphingFlag; + if ( useSkinning ) variantIndex |= _SkinningFlag; - } + result = materialVariants[ variantIndex ]; - if ( uvs !== undefined ) { + } else { - tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) ); + result = customMaterial; - } + } - if ( uvs2 !== undefined ) { + if ( _renderer.localClippingEnabled && + material.clipShadows === true && + material.clippingPlanes.length !== 0 ) { - tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); + // in this case we need a unique material instance reflecting the + // appropriate state - } + var keyA = result.uuid, keyB = material.uuid; - } + var materialsForVariant = _materialCache[ keyA ]; - function addFace( a, b, c, materialIndex ) { + if ( materialsForVariant === undefined ) { - var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; - var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; - var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); + } - scope.faces.push( face ); + var cachedMaterial = materialsForVariant[ keyB ]; - if ( uvs !== undefined ) { + if ( cachedMaterial === undefined ) { - scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; - } + } - if ( uvs2 !== undefined ) { + result = cachedMaterial; - scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); + } - } + result.visible = material.visible; + result.wireframe = material.wireframe; - } + var side = material.side; - if ( indices !== undefined ) { + if ( scope.renderSingleSided && side == DoubleSide ) { - var groups = geometry.groups; + side = FrontSide; - if ( groups.length > 0 ) { + } - for ( var i = 0; i < groups.length; i ++ ) { + if ( scope.renderReverseSided ) { - var group = groups[ i ]; + if ( side === FrontSide ) side = BackSide; + else if ( side === BackSide ) side = FrontSide; - var start = group.start; - var count = group.count; + } - for ( var j = start, jl = start + count; j < jl; j += 3 ) { + result.side = side; - addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; - } + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; - } + if ( isPointLight && result.uniforms.lightPos !== undefined ) { - } else { + result.uniforms.lightPos.value.copy( lightPositionWorld ); - for ( var i = 0; i < indices.length; i += 3 ) { + } - addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); + return result; - } + } - } + function projectObject( object, camera, shadowCamera ) { - } else { + if ( object.visible === false ) return; - for ( var i = 0; i < positions.length / 3; i += 3 ) { + if ( object.layers.test( camera.layers ) && ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) ) { - addFace( i, i + 1, i + 2 ); + if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { - } + var material = object.material; - } + if ( material.visible === true ) { - this.computeFaceNormals(); + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + _renderList.push( object ); - if ( geometry.boundingBox !== null ) { + } - this.boundingBox = geometry.boundingBox.clone(); + } - } + } - if ( geometry.boundingSphere !== null ) { + var children = object.children; - this.boundingSphere = geometry.boundingSphere.clone(); + for ( var i = 0, l = children.length; i < l; i ++ ) { - } + projectObject( children[ i ], camera, shadowCamera ); - return this; + } - }, + } - center: function () { + }; - this.computeBoundingBox(); + exports.WebGLShader = ( function () { - var offset = this.boundingBox.center().negate(); + function addLineNumbers( string ) { - this.translate( offset.x, offset.y, offset.z ); + var lines = string.split( '\n' ); - return offset; + for ( var i = 0; i < lines.length; i ++ ) { - }, + lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; - normalize: function () { + } - this.computeBoundingSphere(); + return lines.join( '\n' ); - var center = this.boundingSphere.center; - var radius = this.boundingSphere.radius; + } - var s = radius === 0 ? 1 : 1.0 / radius; + return function WebGLShader( gl, type, string ) { - var matrix = new THREE.Matrix4(); - matrix.set( - s, 0, 0, - s * center.x, - 0, s, 0, - s * center.y, - 0, 0, s, - s * center.z, - 0, 0, 0, 1 - ); + var shader = gl.createShader( type ); - this.applyMatrix( matrix ); + gl.shaderSource( shader, string ); + gl.compileShader( shader ); - return this; + if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { - }, + console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); - computeFaceNormals: function () { + } - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); + if ( gl.getShaderInfoLog( shader ) !== '' ) { - for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { + console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); - var face = this.faces[ f ]; + } - var vA = this.vertices[ face.a ]; - var vB = this.vertices[ face.b ]; - var vC = this.vertices[ face.c ]; + // --enable-privileged-webgl-extension + // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + return shader; - cb.normalize(); + }; - face.normal.copy( cb ); + } )(); - } + /** + * @author fordacious / fordacious.github.io + */ - }, + function WebGLProperties () { + this.isWebGLProperties = true; - computeVertexNormals: function ( areaWeighted ) { + var properties = {}; - if ( areaWeighted === undefined ) areaWeighted = true; + this.get = function ( object ) { - var v, vl, f, fl, face, vertices; + var uuid = object.uuid; + var map = properties[ uuid ]; - vertices = new Array( this.vertices.length ); + if ( map === undefined ) { - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + map = {}; + properties[ uuid ] = map; - vertices[ v ] = new THREE.Vector3(); + } - } + return map; - if ( areaWeighted ) { + }; - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm + this.delete = function ( object ) { - var vA, vB, vC; - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); + delete properties[ object.uuid ]; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + }; - face = this.faces[ f ]; + this.clear = function () { - vA = this.vertices[ face.a ]; - vB = this.vertices[ face.b ]; - vC = this.vertices[ face.c ]; + properties = {}; - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + }; - vertices[ face.a ].add( cb ); - vertices[ face.b ].add( cb ); - vertices[ face.c ].add( cb ); + }; - } + exports.WebGLProgram = ( function () { - } else { + var programIdCount = 0; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + function getEncodingComponents( encoding ) { - face = this.faces[ f ]; + switch ( encoding ) { - vertices[ face.a ].add( face.normal ); - vertices[ face.b ].add( face.normal ); - vertices[ face.c ].add( face.normal ); + case LinearEncoding: + return [ 'Linear','( value )' ]; + case sRGBEncoding: + return [ 'sRGB','( value )' ]; + case RGBEEncoding: + return [ 'RGBE','( value )' ]; + case RGBM7Encoding: + return [ 'RGBM','( value, 7.0 )' ]; + case RGBM16Encoding: + return [ 'RGBM','( value, 16.0 )' ]; + case RGBDEncoding: + return [ 'RGBD','( value, 256.0 )' ]; + case GammaEncoding: + return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ]; + default: + throw new Error( 'unsupported encoding: ' + encoding ); - } + } - } + } - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + function getTexelDecodingFunction( functionName, encoding ) { - vertices[ v ].normalize(); + var components = getEncodingComponents( encoding ); + return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }"; - } + } - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + function getTexelEncodingFunction( functionName, encoding ) { - face = this.faces[ f ]; + var components = getEncodingComponents( encoding ); + return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }"; - var vertexNormals = face.vertexNormals; + } - if ( vertexNormals.length === 3 ) { + function getToneMappingFunction( functionName, toneMapping ) { - vertexNormals[ 0 ].copy( vertices[ face.a ] ); - vertexNormals[ 1 ].copy( vertices[ face.b ] ); - vertexNormals[ 2 ].copy( vertices[ face.c ] ); + var toneMappingName; - } else { + switch ( toneMapping ) { - vertexNormals[ 0 ] = vertices[ face.a ].clone(); - vertexNormals[ 1 ] = vertices[ face.b ].clone(); - vertexNormals[ 2 ] = vertices[ face.c ].clone(); + case LinearToneMapping: + toneMappingName = "Linear"; + break; - } + case ReinhardToneMapping: + toneMappingName = "Reinhard"; + break; - } + case Uncharted2ToneMapping: + toneMappingName = "Uncharted2"; + break; - if ( this.faces.length > 0 ) { + case CineonToneMapping: + toneMappingName = "OptimizedCineon"; + break; - this.normalsNeedUpdate = true; + default: + throw new Error( 'unsupported toneMapping: ' + toneMapping ); - } + } - }, + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; - computeMorphNormals: function () { + } - var i, il, f, fl, face; + function generateExtensions( extensions, parameters, rendererExtensions ) { - // save original normals - // - create temp variables on first access - // otherwise just copy (for faster repeated calls) + extensions = extensions || {}; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + var chunks = [ + ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '', + ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '', + ]; - face = this.faces[ f ]; + return chunks.filter( filterEmptyLine ).join( '\n' ); - if ( ! face.__originalFaceNormal ) { + } - face.__originalFaceNormal = face.normal.clone(); + function generateDefines( defines ) { - } else { + var chunks = []; - face.__originalFaceNormal.copy( face.normal ); + for ( var name in defines ) { - } + var value = defines[ name ]; - if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; + if ( value === false ) continue; - for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { + chunks.push( '#define ' + name + ' ' + value ); - if ( ! face.__originalVertexNormals[ i ] ) { + } - face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); + return chunks.join( '\n' ); - } else { + } - face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); + function fetchAttributeLocations( gl, program, identifiers ) { - } + var attributes = {}; - } + var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); - } + for ( var i = 0; i < n; i ++ ) { - // use temp geometry to compute face and vertex normals for each morph + var info = gl.getActiveAttrib( program, i ); + var name = info.name; - var tmpGeo = new THREE.Geometry(); - tmpGeo.faces = this.faces; + // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i ); - for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { + attributes[ name ] = gl.getAttribLocation( program, name ); - // create on first access + } - if ( ! this.morphNormals[ i ] ) { + return attributes; - this.morphNormals[ i ] = {}; - this.morphNormals[ i ].faceNormals = []; - this.morphNormals[ i ].vertexNormals = []; + } - var dstNormalsFace = this.morphNormals[ i ].faceNormals; - var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; + function filterEmptyLine( string ) { - var faceNormal, vertexNormals; + return string !== ''; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + } - faceNormal = new THREE.Vector3(); - vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() }; + function replaceLightNums( string, parameters ) { - dstNormalsFace.push( faceNormal ); - dstNormalsVertex.push( vertexNormals ); + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ); - } + } - } + function parseIncludes( string ) { - var morphNormals = this.morphNormals[ i ]; + var pattern = /#include +<([\w\d.]+)>/g; - // set vertices to morph target + function replace( match, include ) { - tmpGeo.vertices = this.morphTargets[ i ].vertices; + var replace = exports.ShaderChunk[ include ]; - // compute morph normals + if ( replace === undefined ) { - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); + throw new Error( 'Can not resolve #include <' + include + '>' ); - // store morph normals + } - var faceNormal, vertexNormals; + return parseIncludes( replace ); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + } - face = this.faces[ f ]; + return string.replace( pattern, replace ); - faceNormal = morphNormals.faceNormals[ f ]; - vertexNormals = morphNormals.vertexNormals[ f ]; + } - faceNormal.copy( face.normal ); + function unrollLoops( string ) { - vertexNormals.a.copy( face.vertexNormals[ 0 ] ); - vertexNormals.b.copy( face.vertexNormals[ 1 ] ); - vertexNormals.c.copy( face.vertexNormals[ 2 ] ); + var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; - } + function replace( match, start, end, snippet ) { - } + var unroll = ''; - // restore original normals + for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); - face = this.faces[ f ]; + } - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; + return unroll; - } + } - }, + return string.replace( pattern, replace ); - computeTangents: function () { + } - console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); + return function WebGLProgram( renderer, code, material, parameters ) { - }, + var gl = renderer.context; - computeLineDistances: function () { + var extensions = material.extensions; + var defines = material.defines; - var d = 0; - var vertices = this.vertices; + var vertexShader = material.__webglShader.vertexShader; + var fragmentShader = material.__webglShader.fragmentShader; - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - if ( i > 0 ) { + if ( parameters.shadowMapType === PCFShadowMap ) { - d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - } + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { - this.lineDistances[ i ] = d; + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; - } + } - }, + var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - computeBoundingBox: function () { + if ( parameters.envMap ) { - if ( this.boundingBox === null ) { + switch ( material.envMap.mapping ) { - this.boundingBox = new THREE.Box3(); + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; - } + case CubeUVReflectionMapping: + case CubeUVRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; - this.boundingBox.setFromPoints( this.vertices ); + case EquirectangularReflectionMapping: + case EquirectangularRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; + break; - }, + case SphericalReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; + break; - computeBoundingSphere: function () { + } - if ( this.boundingSphere === null ) { + switch ( material.envMap.mapping ) { - this.boundingSphere = new THREE.Sphere(); + case CubeRefractionMapping: + case EquirectangularRefractionMapping: + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; - } + } - this.boundingSphere.setFromPoints( this.vertices ); + switch ( material.combine ) { - }, + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; - merge: function ( geometry, matrix, materialIndexOffset ) { + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; - if ( geometry instanceof THREE.Geometry === false ) { + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; - console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); - return; + } - } + } - var normalMatrix, - vertexOffset = this.vertices.length, - vertices1 = this.vertices, - vertices2 = geometry.vertices, - faces1 = this.faces, - faces2 = geometry.faces, - uvs1 = this.faceVertexUvs[ 0 ], - uvs2 = geometry.faceVertexUvs[ 0 ]; + var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; - if ( materialIndexOffset === undefined ) materialIndexOffset = 0; + // console.log( 'building new program ' ); - if ( matrix !== undefined ) { + // - normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + var customExtensions = generateExtensions( extensions, parameters, renderer.extensions ); - } + var customDefines = generateDefines( defines ); - // vertices + // - for ( var i = 0, il = vertices2.length; i < il; i ++ ) { + var program = gl.createProgram(); - var vertex = vertices2[ i ]; + var prefixVertex, prefixFragment; - var vertexCopy = vertex.clone(); + if ( (material && material.isRawShaderMaterial) ) { - if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); + prefixVertex = [ - vertices1.push( vertexCopy ); + customDefines - } + ].filter( filterEmptyLine ).join( '\n' ); - // faces + prefixFragment = [ - for ( i = 0, il = faces2.length; i < il; i ++ ) { + customDefines - var face = faces2[ i ], faceCopy, normal, color, - faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; + ].filter( filterEmptyLine ).join( '\n' ); - faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); - faceCopy.normal.copy( face.normal ); + } else { - if ( normalMatrix !== undefined ) { + prefixVertex = [ - faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - } + '#define SHADER_NAME ' + material.__webglShader.name, - for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { + customDefines, - normal = faceVertexNormals[ j ].clone(); + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - if ( normalMatrix !== undefined ) { + '#define GAMMA_FACTOR ' + gammaFactorDefine, - normal.applyMatrix3( normalMatrix ).normalize(); + '#define MAX_BONES ' + parameters.maxBones, - } + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', - faceCopy.vertexNormals.push( normal ); + parameters.flatShading ? '#define FLAT_SHADED' : '', - } + parameters.skinning ? '#define USE_SKINNING' : '', + parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', - faceCopy.color.copy( face.color ); + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { + '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, - color = faceVertexColors[ j ]; - faceCopy.vertexColors.push( color.clone() ); + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - } + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - faces1.push( faceCopy ); + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', - } + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', - // uvs + '#ifdef USE_COLOR', - for ( i = 0, il = uvs2.length; i < il; i ++ ) { + ' attribute vec3 color;', - var uv = uvs2[ i ], uvCopy = []; + '#endif', - if ( uv === undefined ) { + '#ifdef USE_MORPHTARGETS', - continue; + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', - } + ' #ifdef USE_MORPHNORMALS', - for ( var j = 0, jl = uv.length; j < jl; j ++ ) { + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', - uvCopy.push( uv[ j ].clone() ); + ' #else', - } + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', - uvs1.push( uvCopy ); + ' #endif', - } + '#endif', - }, + '#ifdef USE_SKINNING', - mergeMesh: function ( mesh ) { + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', - if ( mesh instanceof THREE.Mesh === false ) { + '#endif', - console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); - return; + '\n' - } + ].filter( filterEmptyLine ).join( '\n' ); - mesh.matrixAutoUpdate && mesh.updateMatrix(); + prefixFragment = [ - this.merge( mesh.geometry, mesh.matrix ); + customExtensions, - }, + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ + '#define SHADER_NAME ' + material.__webglShader.name, - mergeVertices: function () { + customDefines, - var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) - var unique = [], changes = []; + parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '', - var v, key; - var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 - var precision = Math.pow( 10, precisionPoints ); - var i, il, face; - var indices, j, jl; + '#define GAMMA_FACTOR ' + gammaFactorDefine, - for ( i = 0, il = this.vertices.length; i < il; i ++ ) { + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', - v = this.vertices[ i ]; - key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', - if ( verticesMap[ key ] === undefined ) { + parameters.flatShading ? '#define FLAT_SHADED' : '', - verticesMap[ key ] = i; - unique.push( this.vertices[ i ] ); - changes[ i ] = unique.length - 1; + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - } else { + '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[ i ] = changes[ verticesMap[ key ] ]; + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - } + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '', - } + parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '', + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. - var faceIndicesToRemove = []; + parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '', - for ( i = 0, il = this.faces.length; i < il; i ++ ) { + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', - face = this.faces[ i ]; + ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '', + ( parameters.toneMapping !== NoToneMapping ) ? exports.ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', - face.a = changes[ face.a ]; - face.b = changes[ face.b ]; - face.c = changes[ face.c ]; + ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? exports.ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below + parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', + parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', + parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', + parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '', - indices = [ face.a, face.b, face.c ]; + parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '', - var dupIndex = - 1; + '\n' - // if any duplicate vertices are found in a Face3 - // we have to remove the face as nothing can be saved - for ( var n = 0; n < 3; n ++ ) { + ].filter( filterEmptyLine ).join( '\n' ); - if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { + } - dupIndex = n; - faceIndicesToRemove.push( i ); - break; + vertexShader = parseIncludes( vertexShader, parameters ); + vertexShader = replaceLightNums( vertexShader, parameters ); - } + fragmentShader = parseIncludes( fragmentShader, parameters ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); - } + if ( (material && material.isShaderMaterial) === false ) { - } + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); - for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { + } - var idx = faceIndicesToRemove[ i ]; + var vertexGlsl = prefixVertex + vertexShader; + var fragmentGlsl = prefixFragment + fragmentShader; - this.faces.splice( idx, 1 ); + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); - for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { + var glVertexShader = exports.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + var glFragmentShader = exports.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); - this.faceVertexUvs[ j ].splice( idx, 1 ); + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); - } + // Force a particular attribute to index 0. - } + if ( material.index0AttributeName !== undefined ) { - // Use unique set of vertices + gl.bindAttribLocation( program, 0, material.index0AttributeName ); - var diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; + } else if ( parameters.morphTargets === true ) { - }, + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); - sortFacesByMaterialIndex: function () { + } - var faces = this.faces; - var length = faces.length; + gl.linkProgram( program ); - // tag faces + var programLog = gl.getProgramInfoLog( program ); + var vertexLog = gl.getShaderInfoLog( glVertexShader ); + var fragmentLog = gl.getShaderInfoLog( glFragmentShader ); - for ( var i = 0; i < length; i ++ ) { + var runnable = true; + var haveDiagnostics = true; - faces[ i ]._id = i; + // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); + // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); - } + if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { - // sort faces + runnable = false; - function materialIndexSort( a, b ) { + console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog ); - return a.materialIndex - b.materialIndex; + } else if ( programLog !== '' ) { - } + console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); - faces.sort( materialIndexSort ); + } else if ( vertexLog === '' || fragmentLog === '' ) { - // sort uvs + haveDiagnostics = false; - var uvs1 = this.faceVertexUvs[ 0 ]; - var uvs2 = this.faceVertexUvs[ 1 ]; + } - var newUvs1, newUvs2; + if ( haveDiagnostics ) { - if ( uvs1 && uvs1.length === length ) newUvs1 = []; - if ( uvs2 && uvs2.length === length ) newUvs2 = []; + this.diagnostics = { - for ( var i = 0; i < length; i ++ ) { + runnable: runnable, + material: material, - var id = faces[ i ]._id; + programLog: programLog, - if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); - if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); + vertexShader: { - } + log: vertexLog, + prefix: prefixVertex - if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; - if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; + }, - }, + fragmentShader: { - toJSON: function () { + log: fragmentLog, + prefix: prefixFragment - var data = { - metadata: { - version: 4.4, - type: 'Geometry', - generator: 'Geometry.toJSON' - } - }; + } - // standard Geometry serialization + }; - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + } - if ( this.parameters !== undefined ) { + // clean up - var parameters = this.parameters; + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); - for ( var key in parameters ) { + // set up caching for uniform locations - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + var cachedUniforms; - } + this.getUniforms = function() { - return data; + if ( cachedUniforms === undefined ) { - } + cachedUniforms = + new exports.WebGLUniforms( gl, program, renderer ); - var vertices = []; + } - for ( var i = 0; i < this.vertices.length; i ++ ) { + return cachedUniforms; - var vertex = this.vertices[ i ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + }; - } + // set up caching for attribute locations - var faces = []; - var normals = []; - var normalsHash = {}; - var colors = []; - var colorsHash = {}; - var uvs = []; - var uvsHash = {}; + var cachedAttributes; - for ( var i = 0; i < this.faces.length; i ++ ) { + this.getAttributes = function() { - var face = this.faces[ i ]; + if ( cachedAttributes === undefined ) { - var hasMaterial = true; - var hasFaceUv = false; // deprecated - var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; - var hasFaceNormal = face.normal.length() > 0; - var hasFaceVertexNormal = face.vertexNormals.length > 0; - var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; - var hasFaceVertexColor = face.vertexColors.length > 0; + cachedAttributes = fetchAttributeLocations( gl, program ); - var faceType = 0; + } - faceType = setBit( faceType, 0, 0 ); // isQuad - faceType = setBit( faceType, 1, hasMaterial ); - faceType = setBit( faceType, 2, hasFaceUv ); - faceType = setBit( faceType, 3, hasFaceVertexUv ); - faceType = setBit( faceType, 4, hasFaceNormal ); - faceType = setBit( faceType, 5, hasFaceVertexNormal ); - faceType = setBit( faceType, 6, hasFaceColor ); - faceType = setBit( faceType, 7, hasFaceVertexColor ); + return cachedAttributes; - faces.push( faceType ); - faces.push( face.a, face.b, face.c ); - faces.push( face.materialIndex ); + }; - if ( hasFaceVertexUv ) { + // free resource - var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; + this.destroy = function() { - faces.push( - getUvIndex( faceVertexUvs[ 0 ] ), - getUvIndex( faceVertexUvs[ 1 ] ), - getUvIndex( faceVertexUvs[ 2 ] ) - ); + gl.deleteProgram( program ); + this.program = undefined; - } + }; - if ( hasFaceNormal ) { + // DEPRECATED - faces.push( getNormalIndex( face.normal ) ); + Object.defineProperties( this, { - } + uniforms: { + get: function() { - if ( hasFaceVertexNormal ) { + console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' ); + return this.getUniforms(); - var vertexNormals = face.vertexNormals; + } + }, - faces.push( - getNormalIndex( vertexNormals[ 0 ] ), - getNormalIndex( vertexNormals[ 1 ] ), - getNormalIndex( vertexNormals[ 2 ] ) - ); + attributes: { + get: function() { - } + console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' ); + return this.getAttributes(); - if ( hasFaceColor ) { + } + } - faces.push( getColorIndex( face.color ) ); + } ); - } - if ( hasFaceVertexColor ) { + // - var vertexColors = face.vertexColors; + this.id = programIdCount ++; + this.code = code; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; - faces.push( - getColorIndex( vertexColors[ 0 ] ), - getColorIndex( vertexColors[ 1 ] ), - getColorIndex( vertexColors[ 2 ] ) - ); + return this; - } + }; - } + } )(); - function setBit( value, position, enabled ) { + function WebGLPrograms ( renderer, capabilities ) { + this.isWebGLPrograms = true; - return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); + var programs = []; - } + var shaderIDs = { + MeshDepthMaterial: 'depth', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points' + }; - function getNormalIndex( normal ) { + var parameterNames = [ + "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding", + "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap", + "roughnessMap", "metalnessMap", + "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp", + "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", + "maxBones", "useVertexTexture", "morphTargets", "morphNormals", + "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", + "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", + "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', + "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking" + ]; - var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); - if ( normalsHash[ hash ] !== undefined ) { + function allocateBones ( object ) { - return normalsHash[ hash ]; + if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { - } + return 1024; - normalsHash[ hash ] = normals.length / 3; - normals.push( normal.x, normal.y, normal.z ); + } else { - return normalsHash[ hash ]; + // default for when object is not specified + // ( for example when prebuilding shader to be used with multiple objects ) + // + // - leave some extra space for other uniforms + // - limit here is ANGLE's 254 max uniform vectors + // (up to 54 should be safe) - } + var nVertexUniforms = capabilities.maxVertexUniforms; + var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - function getColorIndex( color ) { + var maxBones = nVertexMatrices; - var hash = color.r.toString() + color.g.toString() + color.b.toString(); + if ( object !== undefined && (object && object.isSkinnedMesh) ) { - if ( colorsHash[ hash ] !== undefined ) { + maxBones = Math.min( object.skeleton.bones.length, maxBones ); - return colorsHash[ hash ]; + if ( maxBones < object.skeleton.bones.length ) { - } + console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); - colorsHash[ hash ] = colors.length; - colors.push( color.getHex() ); + } - return colorsHash[ hash ]; + } - } + return maxBones; - function getUvIndex( uv ) { + } - var hash = uv.x.toString() + uv.y.toString(); + } - if ( uvsHash[ hash ] !== undefined ) { + function getTextureEncodingFromMap( map, gammaOverrideLinear ) { - return uvsHash[ hash ]; + var encoding; - } + if ( ! map ) { - uvsHash[ hash ] = uvs.length / 2; - uvs.push( uv.x, uv.y ); + encoding = LinearEncoding; - return uvsHash[ hash ]; + } else if ( (map && map.isTexture) ) { - } + encoding = map.encoding; - data.data = {}; + } else if ( (map && map.isWebGLRenderTarget) ) { - data.data.vertices = vertices; - data.data.normals = normals; - if ( colors.length > 0 ) data.data.colors = colors; - if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility - data.data.faces = faces; + console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); + encoding = map.texture.encoding; - return data; + } - }, + // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. + if ( encoding === LinearEncoding && gammaOverrideLinear ) { - clone: function () { + encoding = GammaEncoding; - /* - // Handle primitives + } - var parameters = this.parameters; + return encoding; - if ( parameters !== undefined ) { + } - var values = []; + this.getParameters = function ( material, lights, fog, nClipPlanes, object ) { - for ( var key in parameters ) { + var shaderID = shaderIDs[ material.type ]; - values.push( parameters[ key ] ); + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) - } + var maxBones = allocateBones( object ); + var precision = renderer.getPrecision(); - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + if ( material.precision !== null ) { - } + precision = capabilities.getMaxPrecision( material.precision ); - return new this.constructor().copy( this ); - */ + if ( precision !== material.precision ) { - return new THREE.Geometry().copy( this ); + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); - }, + } - copy: function ( source ) { + } - this.vertices = []; - this.faces = []; - this.faceVertexUvs = [ [] ]; + var currentRenderTarget = renderer.getCurrentRenderTarget(); - var vertices = source.vertices; + var parameters = { - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + shaderID: shaderID, - this.vertices.push( vertices[ i ].clone() ); + precision: precision, + supportsVertexTextures: capabilities.vertexTextures, + outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ), + map: !! material.map, + mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ), + envMap: !! material.envMap, + envMapMode: material.envMap && material.envMap.mapping, + envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ), + envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ), + lightMap: !! material.lightMap, + aoMap: !! material.aoMap, + emissiveMap: !! material.emissiveMap, + emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ), + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + displacementMap: !! material.displacementMap, + roughnessMap: !! material.roughnessMap, + metalnessMap: !! material.metalnessMap, + specularMap: !! material.specularMap, + alphaMap: !! material.alphaMap, - } + combine: material.combine, - var faces = source.faces; + vertexColors: material.vertexColors, - for ( var i = 0, il = faces.length; i < il; i ++ ) { + fog: !! fog, + useFog: material.fog, + fogExp: (fog && fog.isFogExp2), - this.faces.push( faces[ i ].clone() ); + flatShading: material.shading === FlatShading, - } + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, - for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { + skinning: material.skinning, + maxBones: maxBones, + useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture, - var faceVertexUvs = source.faceVertexUvs[ i ]; + morphTargets: material.morphTargets, + morphNormals: material.morphNormals, + maxMorphTargets: renderer.maxMorphTargets, + maxMorphNormals: renderer.maxMorphNormals, - if ( this.faceVertexUvs[ i ] === undefined ) { + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numHemiLights: lights.hemi.length, - this.faceVertexUvs[ i ] = []; + numClippingPlanes: nClipPlanes, - } + shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0, + shadowMapType: renderer.shadowMap.type, - for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { + toneMapping: renderer.toneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, - var uvs = faceVertexUvs[ j ], uvsCopy = []; + premultipliedAlpha: material.premultipliedAlpha, - for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { + alphaTest: material.alphaTest, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, - var uv = uvs[ k ]; + depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false - uvsCopy.push( uv.clone() ); + }; - } + return parameters; - this.faceVertexUvs[ i ].push( uvsCopy ); + }; - } + this.getProgramCode = function ( material, parameters ) { - } + var array = []; - return this; + if ( parameters.shaderID ) { - }, + array.push( parameters.shaderID ); - dispose: function () { + } else { - this.dispatchEvent( { type: 'dispose' } ); + array.push( material.fragmentShader ); + array.push( material.vertexShader ); - } + } -} ); + if ( material.defines !== undefined ) { -THREE.GeometryIdCount = 0; + for ( var name in material.defines ) { -// File:src/core/DirectGeometry.js + array.push( name ); + array.push( material.defines[ name ] ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.DirectGeometry = function () { + } - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + for ( var i = 0; i < parameterNames.length; i ++ ) { - this.uuid = THREE.Math.generateUUID(); + array.push( parameters[ parameterNames[ i ] ] ); - this.name = ''; - this.type = 'DirectGeometry'; + } - this.indices = []; - this.vertices = []; - this.normals = []; - this.colors = []; - this.uvs = []; - this.uvs2 = []; + return array.join(); - this.groups = []; + }; - this.morphTargets = {}; + this.acquireProgram = function ( material, parameters, code ) { - this.skinWeights = []; - this.skinIndices = []; + var program; - // this.lineDistances = []; + // Check if code has been already compiled + for ( var p = 0, pl = programs.length; p < pl; p ++ ) { - this.boundingBox = null; - this.boundingSphere = null; + var programInfo = programs[ p ]; - // update flags + if ( programInfo.code === code ) { - this.verticesNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.groupsNeedUpdate = false; + program = programInfo; + ++ program.usedTimes; -}; + break; -Object.assign( THREE.DirectGeometry.prototype, THREE.EventDispatcher.prototype, { + } - computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox, - computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere, + } - computeFaceNormals: function () { + if ( program === undefined ) { - console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' ); + program = new exports.WebGLProgram( renderer, code, material, parameters ); + programs.push( program ); - }, + } - computeVertexNormals: function () { + return program; - console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' ); + }; - }, + this.releaseProgram = function( program ) { - computeGroups: function ( geometry ) { + if ( -- program.usedTimes === 0 ) { - var group; - var groups = []; - var materialIndex; + // Remove from unordered set + var i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); - var faces = geometry.faces; + // Free WebGL resources + program.destroy(); - for ( var i = 0; i < faces.length; i ++ ) { + } - var face = faces[ i ]; + }; - // materials + // Exposed for resource monitoring & error feedback via renderer.info: + this.programs = programs; - if ( face.materialIndex !== materialIndex ) { + }; - materialIndex = face.materialIndex; + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( group !== undefined ) { + function BufferAttribute ( array, itemSize, normalized ) { + this.isBufferAttribute = true; - group.count = ( i * 3 ) - group.start; - groups.push( group ); + this.uuid = exports.Math.generateUUID(); - } + this.array = array; + this.itemSize = itemSize; - group = { - start: i * 3, - materialIndex: materialIndex - }; + this.dynamic = false; + this.updateRange = { offset: 0, count: - 1 }; - } + this.version = 0; + this.normalized = normalized === true; - } + }; - if ( group !== undefined ) { + BufferAttribute.prototype = { - group.count = ( i * 3 ) - group.start; - groups.push( group ); + constructor: BufferAttribute, - } + get count() { - this.groups = groups; + return this.array.length / this.itemSize; - }, + }, - fromGeometry: function ( geometry ) { + set needsUpdate( value ) { - var faces = geometry.faces; - var vertices = geometry.vertices; - var faceVertexUvs = geometry.faceVertexUvs; + if ( value === true ) this.version ++; - var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; - var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; + }, - // morphs + setDynamic: function ( value ) { - var morphTargets = geometry.morphTargets; - var morphTargetsLength = morphTargets.length; + this.dynamic = value; - var morphTargetsPosition; + return this; - if ( morphTargetsLength > 0 ) { + }, - morphTargetsPosition = []; + copy: function ( source ) { - for ( var i = 0; i < morphTargetsLength; i ++ ) { + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; - morphTargetsPosition[ i ] = []; + this.dynamic = source.dynamic; - } + return this; - this.morphTargets.position = morphTargetsPosition; + }, - } + copyAt: function ( index1, attribute, index2 ) { - var morphNormals = geometry.morphNormals; - var morphNormalsLength = morphNormals.length; + index1 *= this.itemSize; + index2 *= attribute.itemSize; - var morphTargetsNormal; + for ( var i = 0, l = this.itemSize; i < l; i ++ ) { - if ( morphNormalsLength > 0 ) { + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - morphTargetsNormal = []; + } - for ( var i = 0; i < morphNormalsLength; i ++ ) { + return this; - morphTargetsNormal[ i ] = []; + }, - } + copyArray: function ( array ) { - this.morphTargets.normal = morphTargetsNormal; + this.array.set( array ); - } + return this; - // skins + }, - var skinIndices = geometry.skinIndices; - var skinWeights = geometry.skinWeights; + copyColorsArray: function ( colors ) { - var hasSkinIndices = skinIndices.length === vertices.length; - var hasSkinWeights = skinWeights.length === vertices.length; + var array = this.array, offset = 0; - // + for ( var i = 0, l = colors.length; i < l; i ++ ) { - for ( var i = 0; i < faces.length; i ++ ) { + var color = colors[ i ]; - var face = faces[ i ]; + if ( color === undefined ) { - this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); + console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); + color = new Color(); - var vertexNormals = face.vertexNormals; + } - if ( vertexNormals.length === 3 ) { + array[ offset ++ ] = color.r; + array[ offset ++ ] = color.g; + array[ offset ++ ] = color.b; - this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); + } - } else { + return this; - var normal = face.normal; + }, - this.normals.push( normal, normal, normal ); + copyIndicesArray: function ( indices ) { - } + var array = this.array, offset = 0; - var vertexColors = face.vertexColors; + for ( var i = 0, l = indices.length; i < l; i ++ ) { - if ( vertexColors.length === 3 ) { + var index = indices[ i ]; - this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); + array[ offset ++ ] = index.a; + array[ offset ++ ] = index.b; + array[ offset ++ ] = index.c; - } else { + } - var color = face.color; + return this; - this.colors.push( color, color, color ); + }, - } + copyVector2sArray: function ( vectors ) { - if ( hasFaceVertexUv === true ) { + var array = this.array, offset = 0; - var vertexUvs = faceVertexUvs[ 0 ][ i ]; + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - if ( vertexUvs !== undefined ) { + var vector = vectors[ i ]; - this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + if ( vector === undefined ) { - } else { + console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); + vector = new Vector2(); - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); + } - this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ); + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; - } + } - } + return this; - if ( hasFaceVertexUv2 === true ) { + }, - var vertexUvs = faceVertexUvs[ 1 ][ i ]; + copyVector3sArray: function ( vectors ) { - if ( vertexUvs !== undefined ) { + var array = this.array, offset = 0; - this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - } else { + var vector = vectors[ i ]; - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); + if ( vector === undefined ) { - this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ); + console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); + vector = new Vector3(); - } + } - } + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; - // morphs + } - for ( var j = 0; j < morphTargetsLength; j ++ ) { + return this; - var morphTarget = morphTargets[ j ].vertices; + }, - morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); + copyVector4sArray: function ( vectors ) { - } + var array = this.array, offset = 0; - for ( var j = 0; j < morphNormalsLength; j ++ ) { + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - var morphNormal = morphNormals[ j ].vertexNormals[ i ]; + var vector = vectors[ i ]; - morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); + if ( vector === undefined ) { - } + console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); + vector = new Vector4(); - // skins + } - if ( hasSkinIndices ) { + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; + array[ offset ++ ] = vector.w; - this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); + } - } + return this; - if ( hasSkinWeights ) { + }, - this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); + set: function ( value, offset ) { - } + if ( offset === undefined ) offset = 0; - } + this.array.set( value, offset ); - this.computeGroups( geometry ); + return this; - this.verticesNeedUpdate = geometry.verticesNeedUpdate; - this.normalsNeedUpdate = geometry.normalsNeedUpdate; - this.colorsNeedUpdate = geometry.colorsNeedUpdate; - this.uvsNeedUpdate = geometry.uvsNeedUpdate; - this.groupsNeedUpdate = geometry.groupsNeedUpdate; + }, - return this; + getX: function ( index ) { - }, + return this.array[ index * this.itemSize ]; - dispose: function () { + }, - this.dispatchEvent( { type: 'dispose' } ); + setX: function ( index, x ) { - } + this.array[ index * this.itemSize ] = x; -} ); + return this; -// File:src/core/BufferGeometry.js + }, -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + getY: function ( index ) { -THREE.BufferGeometry = function () { + return this.array[ index * this.itemSize + 1 ]; - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + }, - this.uuid = THREE.Math.generateUUID(); + setY: function ( index, y ) { - this.name = ''; - this.type = 'BufferGeometry'; + this.array[ index * this.itemSize + 1 ] = y; - this.index = null; - this.attributes = {}; + return this; - this.morphAttributes = {}; + }, - this.groups = []; + getZ: function ( index ) { - this.boundingBox = null; - this.boundingSphere = null; + return this.array[ index * this.itemSize + 2 ]; - this.drawRange = { start: 0, count: Infinity }; + }, -}; + setZ: function ( index, z ) { -Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, { + this.array[ index * this.itemSize + 2 ] = z; - getIndex: function () { + return this; - return this.index; + }, - }, + getW: function ( index ) { - setIndex: function ( index ) { + return this.array[ index * this.itemSize + 3 ]; - this.index = index; + }, - }, + setW: function ( index, w ) { - addAttribute: function ( name, attribute ) { + this.array[ index * this.itemSize + 3 ] = w; - if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) { + return this; - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + }, - this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + setXY: function ( index, x, y ) { - return; + index *= this.itemSize; - } + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; - if ( name === 'index' ) { + return this; - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); + }, - return; + setXYZ: function ( index, x, y, z ) { - } + index *= this.itemSize; - this.attributes[ name ] = attribute; + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; - return this; + return this; - }, + }, - getAttribute: function ( name ) { + setXYZW: function ( index, x, y, z, w ) { - return this.attributes[ name ]; + index *= this.itemSize; - }, + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; - removeAttribute: function ( name ) { + return this; - delete this.attributes[ name ]; + }, - return this; + clone: function () { - }, + return new this.constructor().copy( this ); - addGroup: function ( start, count, materialIndex ) { + } - this.groups.push( { + }; - start: start, - count: count, - materialIndex: materialIndex !== undefined ? materialIndex : 0 + // - } ); + function Int8Attribute ( array, itemSize ) { + this.isInt8Attribute = true; - }, + return new BufferAttribute( new Int8Array( array ), itemSize ); - clearGroups: function () { + }; - this.groups = []; + function Uint8Attribute ( array, itemSize ) { + this.isUint8Attribute = true; - }, + return new BufferAttribute( new Uint8Array( array ), itemSize ); - setDrawRange: function ( start, count ) { + }; - this.drawRange.start = start; - this.drawRange.count = count; + function Uint8ClampedAttribute ( array, itemSize ) { + this.isUint8ClampedAttribute = true; - }, + return new BufferAttribute( new Uint8ClampedArray( array ), itemSize ); - applyMatrix: function ( matrix ) { + }; - var position = this.attributes.position; + function Int16Attribute ( array, itemSize ) { + this.isInt16Attribute = true; - if ( position !== undefined ) { + return new BufferAttribute( new Int16Array( array ), itemSize ); - matrix.applyToVector3Array( position.array ); - position.needsUpdate = true; + }; - } + function Uint16Attribute ( array, itemSize ) { + this.isUint16Attribute = true; - var normal = this.attributes.normal; + return new BufferAttribute( new Uint16Array( array ), itemSize ); - if ( normal !== undefined ) { + }; - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + function Int32Attribute ( array, itemSize ) { + this.isInt32Attribute = true; - normalMatrix.applyToVector3Array( normal.array ); - normal.needsUpdate = true; + return new BufferAttribute( new Int32Array( array ), itemSize ); - } + }; - if ( this.boundingBox !== null ) { + function Uint32Attribute ( array, itemSize ) { + this.isUint32Attribute = true; - this.computeBoundingBox(); + return new BufferAttribute( new Uint32Array( array ), itemSize ); - } + }; - if ( this.boundingSphere !== null ) { + function Float32Attribute ( array, itemSize ) { + this.isFloat32Attribute = true; - this.computeBoundingSphere(); + return new BufferAttribute( new Float32Array( array ), itemSize ); - } + }; - return this; + function Float64Attribute ( array, itemSize ) { + this.isFloat64Attribute = true; - }, + return new BufferAttribute( new Float64Array( array ), itemSize ); - rotateX: function () { + }; - // rotate geometry around world x-axis - var m1; + // Deprecated - return function rotateX( angle ) { + function DynamicBufferAttribute ( array, itemSize ) { + this.isDynamicBufferAttribute = true; - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); + return new BufferAttribute( array, itemSize ).setDynamic( true ); - m1.makeRotationX( angle ); + }; - this.applyMatrix( m1 ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - return this; + function Face3 ( a, b, c, normal, color, materialIndex ) { + this.isFace3 = true; - }; + this.a = a; + this.b = b; + this.c = c; - }(), + this.normal = (normal && normal.isVector3) ? normal : new Vector3(); + this.vertexNormals = Array.isArray( normal ) ? normal : []; - rotateY: function () { + this.color = (color && color.isColor) ? color : new Color(); + this.vertexColors = Array.isArray( color ) ? color : []; - // rotate geometry around world y-axis + this.materialIndex = materialIndex !== undefined ? materialIndex : 0; - var m1; + }; - return function rotateY( angle ) { + Face3.prototype = { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + constructor: Face3, - m1.makeRotationY( angle ); + clone: function () { - this.applyMatrix( m1 ); + return new this.constructor().copy( this ); - return this; + }, - }; + copy: function ( source ) { - }(), + this.a = source.a; + this.b = source.b; + this.c = source.c; - rotateZ: function () { + this.normal.copy( source.normal ); + this.color.copy( source.color ); - // rotate geometry around world z-axis + this.materialIndex = source.materialIndex; - var m1; + for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { - return function rotateZ( angle ) { + this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + } - m1.makeRotationZ( angle ); + for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { - this.applyMatrix( m1 ); + this.vertexColors[ i ] = source.vertexColors[ i ].clone(); - return this; + } - }; + return this; - }(), + } - translate: function () { + }; - // translate geometry + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - var m1; + function Euler ( x, y, z, order ) { + this.isEuler = true; - return function translate( x, y, z ) { + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._order = order || Euler.DefaultOrder; - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + }; - m1.makeTranslation( x, y, z ); + Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - this.applyMatrix( m1 ); + Euler.DefaultOrder = 'XYZ'; - return this; + Euler.prototype = { - }; + constructor: Euler, - }(), + get x () { - scale: function () { + return this._x; - // scale geometry + }, - var m1; + set x ( value ) { - return function scale( x, y, z ) { + this._x = value; + this.onChangeCallback(); - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + }, - m1.makeScale( x, y, z ); + get y () { - this.applyMatrix( m1 ); + return this._y; - return this; + }, - }; + set y ( value ) { - }(), + this._y = value; + this.onChangeCallback(); - lookAt: function () { + }, - var obj; + get z () { - return function lookAt( vector ) { + return this._z; - if ( obj === undefined ) obj = new THREE.Object3D(); + }, - obj.lookAt( vector ); + set z ( value ) { - obj.updateMatrix(); + this._z = value; + this.onChangeCallback(); - this.applyMatrix( obj.matrix ); + }, - }; + get order () { - }(), + return this._order; - center: function () { + }, - this.computeBoundingBox(); + set order ( value ) { - var offset = this.boundingBox.center().negate(); + this._order = value; + this.onChangeCallback(); - this.translate( offset.x, offset.y, offset.z ); + }, - return offset; + set: function ( x, y, z, order ) { - }, + this._x = x; + this._y = y; + this._z = z; + this._order = order || this._order; - setFromObject: function ( object ) { + this.onChangeCallback(); - // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); + return this; - var geometry = object.geometry; + }, - if ( object instanceof THREE.Points || object instanceof THREE.Line ) { + clone: function () { - var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 ); - var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 ); + return new this.constructor( this._x, this._y, this._z, this._order ); - this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); - this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); + }, - if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { + copy: function ( euler ) { - var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 ); + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; - this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); + this.onChangeCallback(); - } + return this; - if ( geometry.boundingSphere !== null ) { + }, - this.boundingSphere = geometry.boundingSphere.clone(); + setFromRotationMatrix: function ( m, order, update ) { - } + var clamp = exports.Math.clamp; - if ( geometry.boundingBox !== null ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - this.boundingBox = geometry.boundingBox.clone(); + var te = m.elements; + var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - } + order = order || this._order; - } else if ( object instanceof THREE.Mesh ) { + if ( order === 'XYZ' ) { - if ( geometry instanceof THREE.Geometry ) { + this._y = Math.asin( clamp( m13, - 1, 1 ) ); - this.fromGeometry( geometry ); + if ( Math.abs( m13 ) < 0.99999 ) { - } + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); - } + } else { - return this; + this._x = Math.atan2( m32, m22 ); + this._z = 0; - }, + } - updateFromObject: function ( object ) { + } else if ( order === 'YXZ' ) { - var geometry = object.geometry; + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - if ( object instanceof THREE.Mesh ) { + if ( Math.abs( m23 ) < 0.99999 ) { - var direct = geometry.__directGeometry; + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); - if ( direct === undefined || geometry.elementsNeedUpdate === true ) { + } else { - return this.fromGeometry( geometry ); + this._y = Math.atan2( - m31, m11 ); + this._z = 0; - } + } - direct.verticesNeedUpdate = geometry.verticesNeedUpdate || geometry.elementsNeedUpdate; - direct.normalsNeedUpdate = geometry.normalsNeedUpdate || geometry.elementsNeedUpdate; - direct.colorsNeedUpdate = geometry.colorsNeedUpdate || geometry.elementsNeedUpdate; - direct.uvsNeedUpdate = geometry.uvsNeedUpdate || geometry.elementsNeedUpdate; - direct.groupsNeedUpdate = geometry.groupsNeedUpdate || geometry.elementsNeedUpdate; + } else if ( order === 'ZXY' ) { - geometry.elementsNeedUpdate = false; - geometry.verticesNeedUpdate = false; - geometry.normalsNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.uvsNeedUpdate = false; - geometry.groupsNeedUpdate = false; + this._x = Math.asin( clamp( m32, - 1, 1 ) ); - geometry = direct; + if ( Math.abs( m32 ) < 0.99999 ) { - } + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); - var attribute; + } else { - if ( geometry.verticesNeedUpdate === true ) { + this._y = 0; + this._z = Math.atan2( m21, m11 ); - attribute = this.attributes.position; + } - if ( attribute !== undefined ) { + } else if ( order === 'ZYX' ) { - attribute.copyVector3sArray( geometry.vertices ); - attribute.needsUpdate = true; + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - } + if ( Math.abs( m31 ) < 0.99999 ) { - geometry.verticesNeedUpdate = false; + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); - } + } else { - if ( geometry.normalsNeedUpdate === true ) { + this._x = 0; + this._z = Math.atan2( - m12, m22 ); - attribute = this.attributes.normal; + } - if ( attribute !== undefined ) { + } else if ( order === 'YZX' ) { - attribute.copyVector3sArray( geometry.normals ); - attribute.needsUpdate = true; + this._z = Math.asin( clamp( m21, - 1, 1 ) ); - } + if ( Math.abs( m21 ) < 0.99999 ) { - geometry.normalsNeedUpdate = false; + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); - } + } else { - if ( geometry.colorsNeedUpdate === true ) { + this._x = 0; + this._y = Math.atan2( m13, m33 ); - attribute = this.attributes.color; + } - if ( attribute !== undefined ) { + } else if ( order === 'XZY' ) { - attribute.copyColorsArray( geometry.colors ); - attribute.needsUpdate = true; + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - } + if ( Math.abs( m12 ) < 0.99999 ) { - geometry.colorsNeedUpdate = false; + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); - } + } else { - if ( geometry.uvsNeedUpdate ) { + this._x = Math.atan2( - m23, m33 ); + this._y = 0; - attribute = this.attributes.uv; + } - if ( attribute !== undefined ) { + } else { - attribute.copyVector2sArray( geometry.uvs ); - attribute.needsUpdate = true; + console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); - } + } - geometry.uvsNeedUpdate = false; + this._order = order; - } + if ( update !== false ) this.onChangeCallback(); - if ( geometry.lineDistancesNeedUpdate ) { + return this; - attribute = this.attributes.lineDistance; + }, - if ( attribute !== undefined ) { + setFromQuaternion: function () { - attribute.copyArray( geometry.lineDistances ); - attribute.needsUpdate = true; + var matrix; - } + return function setFromQuaternion( q, order, update ) { - geometry.lineDistancesNeedUpdate = false; + if ( matrix === undefined ) matrix = new Matrix4(); - } + matrix.makeRotationFromQuaternion( q ); - if ( geometry.groupsNeedUpdate ) { + return this.setFromRotationMatrix( matrix, order, update ); - geometry.computeGroups( object.geometry ); - this.groups = geometry.groups; + }; - geometry.groupsNeedUpdate = false; + }(), - } + setFromVector3: function ( v, order ) { - return this; + return this.set( v.x, v.y, v.z, order || this._order ); - }, + }, - fromGeometry: function ( geometry ) { + reorder: function () { - geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry ); + // WARNING: this discards revolution information -bhouston - return this.fromDirectGeometry( geometry.__directGeometry ); + var q = new Quaternion(); - }, + return function reorder( newOrder ) { - fromDirectGeometry: function ( geometry ) { + q.setFromEuler( this ); + + return this.setFromQuaternion( q, newOrder ); - var positions = new Float32Array( geometry.vertices.length * 3 ); - this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); + }; - if ( geometry.normals.length > 0 ) { + }(), - var normals = new Float32Array( geometry.normals.length * 3 ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); + equals: function ( euler ) { - } + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - if ( geometry.colors.length > 0 ) { + }, - var colors = new Float32Array( geometry.colors.length * 3 ); - this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); + fromArray: function ( array ) { - } + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - if ( geometry.uvs.length > 0 ) { + this.onChangeCallback(); - var uvs = new Float32Array( geometry.uvs.length * 2 ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); + return this; - } + }, - if ( geometry.uvs2.length > 0 ) { + toArray: function ( array, offset ) { - var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); - this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - } + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; - if ( geometry.indices.length > 0 ) { + return array; - var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array; - var indices = new TypeArray( geometry.indices.length * 3 ); - this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); + }, - } + toVector3: function ( optionalResult ) { - // groups + if ( optionalResult ) { - this.groups = geometry.groups; + return optionalResult.set( this._x, this._y, this._z ); - // morphs + } else { - for ( var name in geometry.morphTargets ) { + return new Vector3( this._x, this._y, this._z ); - var array = []; - var morphTargets = geometry.morphTargets[ name ]; + } - for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { + }, - var morphTarget = morphTargets[ i ]; + onChange: function ( callback ) { - var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 ); + this.onChangeCallback = callback; - array.push( attribute.copyVector3sArray( morphTarget ) ); + return this; - } + }, - this.morphAttributes[ name ] = array; + onChangeCallback: function () {} - } + }; - // skinning + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( geometry.skinIndices.length > 0 ) { + function Layers () { + this.isLayers = true; - var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 ); - this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); + this.mask = 1; - } + }; - if ( geometry.skinWeights.length > 0 ) { + Layers.prototype = { - var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 ); - this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); + constructor: Layers, - } + set: function ( channel ) { - // + this.mask = 1 << channel; - if ( geometry.boundingSphere !== null ) { + }, - this.boundingSphere = geometry.boundingSphere.clone(); + enable: function ( channel ) { - } + this.mask |= 1 << channel; - if ( geometry.boundingBox !== null ) { + }, - this.boundingBox = geometry.boundingBox.clone(); + toggle: function ( channel ) { - } + this.mask ^= 1 << channel; - return this; + }, - }, + disable: function ( channel ) { - computeBoundingBox: function () { + this.mask &= ~ ( 1 << channel ); - if ( this.boundingBox === null ) { + }, - this.boundingBox = new THREE.Box3(); + test: function ( layers ) { - } + return ( this.mask & layers.mask ) !== 0; - var positions = this.attributes.position.array; + } - if ( positions !== undefined ) { + }; - this.boundingBox.setFromArray( positions ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author elephantatwork / www.elephantatwork.ch + */ - } else { + function Object3D () { + this.isObject3D = true; - this.boundingBox.makeEmpty(); + Object.defineProperty( this, 'id', { value: Object3DIdCount() } ); - } + this.uuid = exports.Math.generateUUID(); - if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { + this.name = ''; + this.type = 'Object3D'; - console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); + this.parent = null; + this.children = []; - } + this.up = Object3D.DefaultUp.clone(); - }, + var position = new Vector3(); + var rotation = new Euler(); + var quaternion = new Quaternion(); + var scale = new Vector3( 1, 1, 1 ); - computeBoundingSphere: function () { + function onRotationChange() { - var box = new THREE.Box3(); - var vector = new THREE.Vector3(); + quaternion.setFromEuler( rotation, false ); - return function computeBoundingSphere() { + } - if ( this.boundingSphere === null ) { + function onQuaternionChange() { - this.boundingSphere = new THREE.Sphere(); + rotation.setFromQuaternion( quaternion, undefined, false ); - } + } - var positions = this.attributes.position; + rotation.onChange( onRotationChange ); + quaternion.onChange( onQuaternionChange ); - if ( positions ) { + Object.defineProperties( this, { + position: { + enumerable: true, + value: position + }, + rotation: { + enumerable: true, + value: rotation + }, + quaternion: { + enumerable: true, + value: quaternion + }, + scale: { + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); - var array = positions.array; - var center = this.boundingSphere.center; + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - box.setFromArray( array ); - box.center( center ); + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; + this.matrixWorldNeedsUpdate = false; - // hoping to find a boundingSphere with a radius smaller than the - // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + this.layers = new Layers(); + this.visible = true; - var maxRadiusSq = 0; + this.castShadow = false; + this.receiveShadow = false; - for ( var i = 0, il = array.length; i < il; i += 3 ) { + this.frustumCulled = true; + this.renderOrder = 0; - vector.fromArray( array, i ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); + this.userData = {}; - } + }; - this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + Object3D.DefaultUp = new Vector3( 0, 1, 0 ); + Object3D.DefaultMatrixAutoUpdate = true; - if ( isNaN( this.boundingSphere.radius ) ) { + Object.assign( Object3D.prototype, EventDispatcher.prototype, { - console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + applyMatrix: function ( matrix ) { - } + this.matrix.multiplyMatrices( matrix, this.matrix ); - } + this.matrix.decompose( this.position, this.quaternion, this.scale ); - }; + }, - }(), + setRotationFromAxisAngle: function ( axis, angle ) { - computeFaceNormals: function () { + // assumes axis is normalized - // backwards compatibility + this.quaternion.setFromAxisAngle( axis, angle ); - }, + }, - computeVertexNormals: function () { + setRotationFromEuler: function ( euler ) { - var index = this.index; - var attributes = this.attributes; - var groups = this.groups; + this.quaternion.setFromEuler( euler, true ); - if ( attributes.position ) { + }, - var positions = attributes.position.array; + setRotationFromMatrix: function ( m ) { - if ( attributes.normal === undefined ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) ); + this.quaternion.setFromRotationMatrix( m ); - } else { + }, - // reset existing normals to zero + setRotationFromQuaternion: function ( q ) { - var array = attributes.normal.array; + // assumes q is normalized - for ( var i = 0, il = array.length; i < il; i ++ ) { + this.quaternion.copy( q ); - array[ i ] = 0; + }, - } + rotateOnAxis: function () { - } + // rotate object on axis in object space + // axis is assumed to be normalized - var normals = attributes.normal.array; + var q1 = new Quaternion(); - var vA, vB, vC, + return function rotateOnAxis( axis, angle ) { - pA = new THREE.Vector3(), - pB = new THREE.Vector3(), - pC = new THREE.Vector3(), + q1.setFromAxisAngle( axis, angle ); - cb = new THREE.Vector3(), - ab = new THREE.Vector3(); + this.quaternion.multiply( q1 ); - // indexed elements + return this; - if ( index ) { + }; - var indices = index.array; + }(), - if ( groups.length === 0 ) { + rotateX: function () { - this.addGroup( 0, indices.length ); + var v1 = new Vector3( 1, 0, 0 ); - } + return function rotateX( angle ) { - for ( var j = 0, jl = groups.length; j < jl; ++ j ) { + return this.rotateOnAxis( v1, angle ); - var group = groups[ j ]; + }; - var start = group.start; - var count = group.count; + }(), - for ( var i = start, il = start + count; i < il; i += 3 ) { + rotateY: function () { - vA = indices[ i + 0 ] * 3; - vB = indices[ i + 1 ] * 3; - vC = indices[ i + 2 ] * 3; + var v1 = new Vector3( 0, 1, 0 ); - pA.fromArray( positions, vA ); - pB.fromArray( positions, vB ); - pC.fromArray( positions, vC ); + return function rotateY( angle ) { - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + return this.rotateOnAxis( v1, angle ); - normals[ vA ] += cb.x; - normals[ vA + 1 ] += cb.y; - normals[ vA + 2 ] += cb.z; + }; - normals[ vB ] += cb.x; - normals[ vB + 1 ] += cb.y; - normals[ vB + 2 ] += cb.z; + }(), - normals[ vC ] += cb.x; - normals[ vC + 1 ] += cb.y; - normals[ vC + 2 ] += cb.z; + rotateZ: function () { - } + var v1 = new Vector3( 0, 0, 1 ); - } + return function rotateZ( angle ) { - } else { + return this.rotateOnAxis( v1, angle ); - // non-indexed elements (unconnected triangle soup) + }; - for ( var i = 0, il = positions.length; i < il; i += 9 ) { + }(), - pA.fromArray( positions, i ); - pB.fromArray( positions, i + 3 ); - pC.fromArray( positions, i + 6 ); + translateOnAxis: function () { - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + // translate object by distance along axis in object space + // axis is assumed to be normalized - normals[ i ] = cb.x; - normals[ i + 1 ] = cb.y; - normals[ i + 2 ] = cb.z; + var v1 = new Vector3(); - normals[ i + 3 ] = cb.x; - normals[ i + 4 ] = cb.y; - normals[ i + 5 ] = cb.z; + return function translateOnAxis( axis, distance ) { - normals[ i + 6 ] = cb.x; - normals[ i + 7 ] = cb.y; - normals[ i + 8 ] = cb.z; + v1.copy( axis ).applyQuaternion( this.quaternion ); - } + this.position.add( v1.multiplyScalar( distance ) ); - } + return this; - this.normalizeNormals(); + }; - attributes.normal.needsUpdate = true; + }(), - } + translateX: function () { - }, + var v1 = new Vector3( 1, 0, 0 ); - merge: function ( geometry, offset ) { + return function translateX( distance ) { - if ( geometry instanceof THREE.BufferGeometry === false ) { + return this.translateOnAxis( v1, distance ); - console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); - return; + }; - } + }(), - if ( offset === undefined ) offset = 0; + translateY: function () { - var attributes = this.attributes; + var v1 = new Vector3( 0, 1, 0 ); - for ( var key in attributes ) { + return function translateY( distance ) { - if ( geometry.attributes[ key ] === undefined ) continue; + return this.translateOnAxis( v1, distance ); - var attribute1 = attributes[ key ]; - var attributeArray1 = attribute1.array; + }; - var attribute2 = geometry.attributes[ key ]; - var attributeArray2 = attribute2.array; + }(), - var attributeSize = attribute2.itemSize; + translateZ: function () { - for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { + var v1 = new Vector3( 0, 0, 1 ); - attributeArray1[ j ] = attributeArray2[ i ]; + return function translateZ( distance ) { - } + return this.translateOnAxis( v1, distance ); - } + }; - return this; + }(), - }, + localToWorld: function ( vector ) { - normalizeNormals: function () { + return vector.applyMatrix4( this.matrixWorld ); - var normals = this.attributes.normal.array; + }, - var x, y, z, n; + worldToLocal: function () { - for ( var i = 0, il = normals.length; i < il; i += 3 ) { + var m1 = new Matrix4(); - x = normals[ i ]; - y = normals[ i + 1 ]; - z = normals[ i + 2 ]; + return function worldToLocal( vector ) { - n = 1.0 / Math.sqrt( x * x + y * y + z * z ); + return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); - normals[ i ] *= n; - normals[ i + 1 ] *= n; - normals[ i + 2 ] *= n; + }; - } + }(), - }, + lookAt: function () { - toNonIndexed: function () { + // This routine does not support objects with rotated and/or translated parent(s) - if ( this.index === null ) { + var m1 = new Matrix4(); - console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); - return this; + return function lookAt( vector ) { - } + m1.lookAt( vector, this.position, this.up ); - var geometry2 = new THREE.BufferGeometry(); + this.quaternion.setFromRotationMatrix( m1 ); - var indices = this.index.array; - var attributes = this.attributes; + }; - for ( var name in attributes ) { + }(), - var attribute = attributes[ name ]; + add: function ( object ) { - var array = attribute.array; - var itemSize = attribute.itemSize; + if ( arguments.length > 1 ) { - var array2 = new array.constructor( indices.length * itemSize ); + for ( var i = 0; i < arguments.length; i ++ ) { - var index = 0, index2 = 0; + this.add( arguments[ i ] ); - for ( var i = 0, l = indices.length; i < l; i ++ ) { + } - index = indices[ i ] * itemSize; + return this; - for ( var j = 0; j < itemSize; j ++ ) { + } - array2[ index2 ++ ] = array[ index ++ ]; + if ( object === this ) { - } + console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); + return this; - } + } - geometry2.addAttribute( name, new THREE.BufferAttribute( array2, itemSize ) ); + if ( (object && object.isObject3D) ) { - } + if ( object.parent !== null ) { - return geometry2; + object.parent.remove( object ); - }, + } - toJSON: function () { + object.parent = this; + object.dispatchEvent( { type: 'added' } ); - var data = { - metadata: { - version: 4.4, - type: 'BufferGeometry', - generator: 'BufferGeometry.toJSON' - } - }; + this.children.push( object ); - // standard BufferGeometry serialization + } else { - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); - if ( this.parameters !== undefined ) { + } - var parameters = this.parameters; + return this; - for ( var key in parameters ) { + }, - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + remove: function ( object ) { - } + if ( arguments.length > 1 ) { - return data; + for ( var i = 0; i < arguments.length; i ++ ) { - } + this.remove( arguments[ i ] ); - data.data = { attributes: {} }; + } - var index = this.index; + } - if ( index !== null ) { + var index = this.children.indexOf( object ); - var array = Array.prototype.slice.call( index.array ); + if ( index !== - 1 ) { - data.data.index = { - type: index.array.constructor.name, - array: array - }; + object.parent = null; - } + object.dispatchEvent( { type: 'removed' } ); - var attributes = this.attributes; + this.children.splice( index, 1 ); - for ( var key in attributes ) { + } - var attribute = attributes[ key ]; + }, - var array = Array.prototype.slice.call( attribute.array ); + getObjectById: function ( id ) { - data.data.attributes[ key ] = { - itemSize: attribute.itemSize, - type: attribute.array.constructor.name, - array: array, - normalized: attribute.normalized - }; + return this.getObjectByProperty( 'id', id ); - } + }, - var groups = this.groups; + getObjectByName: function ( name ) { - if ( groups.length > 0 ) { + return this.getObjectByProperty( 'name', name ); - data.data.groups = JSON.parse( JSON.stringify( groups ) ); + }, - } + getObjectByProperty: function ( name, value ) { - var boundingSphere = this.boundingSphere; + if ( this[ name ] === value ) return this; - if ( boundingSphere !== null ) { + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - data.data.boundingSphere = { - center: boundingSphere.center.toArray(), - radius: boundingSphere.radius - }; + var child = this.children[ i ]; + var object = child.getObjectByProperty( name, value ); - } + if ( object !== undefined ) { - return data; + return object; - }, + } - clone: function () { + } - /* - // Handle primitives + return undefined; - var parameters = this.parameters; + }, - if ( parameters !== undefined ) { + getWorldPosition: function ( optionalTarget ) { - var values = []; + var result = optionalTarget || new Vector3(); - for ( var key in parameters ) { + this.updateMatrixWorld( true ); - values.push( parameters[ key ] ); + return result.setFromMatrixPosition( this.matrixWorld ); - } + }, - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + getWorldQuaternion: function () { - } + var position = new Vector3(); + var scale = new Vector3(); - return new this.constructor().copy( this ); - */ + return function getWorldQuaternion( optionalTarget ) { - return new THREE.BufferGeometry().copy( this ); + var result = optionalTarget || new Quaternion(); - }, + this.updateMatrixWorld( true ); - copy: function ( source ) { + this.matrixWorld.decompose( position, result, scale ); - var index = source.index; + return result; - if ( index !== null ) { + }; - this.setIndex( index.clone() ); + }(), - } + getWorldRotation: function () { - var attributes = source.attributes; + var quaternion = new Quaternion(); - for ( var name in attributes ) { + return function getWorldRotation( optionalTarget ) { - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + var result = optionalTarget || new Euler(); - } + this.getWorldQuaternion( quaternion ); - var groups = source.groups; + return result.setFromQuaternion( quaternion, this.rotation.order, false ); - for ( var i = 0, l = groups.length; i < l; i ++ ) { + }; - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.materialIndex ); + }(), - } + getWorldScale: function () { - return this; + var position = new Vector3(); + var quaternion = new Quaternion(); - }, + return function getWorldScale( optionalTarget ) { - dispose: function () { + var result = optionalTarget || new Vector3(); - this.dispatchEvent( { type: 'dispose' } ); + this.updateMatrixWorld( true ); - } + this.matrixWorld.decompose( position, quaternion, result ); -} ); + return result; -THREE.BufferGeometry.MaxIndex = 65535; + }; -// File:src/core/InstancedBufferGeometry.js + }(), -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + getWorldDirection: function () { -THREE.InstancedBufferGeometry = function () { + var quaternion = new Quaternion(); - THREE.BufferGeometry.call( this ); + return function getWorldDirection( optionalTarget ) { - this.type = 'InstancedBufferGeometry'; - this.maxInstancedCount = undefined; + var result = optionalTarget || new Vector3(); -}; + this.getWorldQuaternion( quaternion ); -THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry; + return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); -THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { + }; - this.groups.push( { + }(), - start: start, - count: count, - instances: instances + raycast: function () {}, - } ); + traverse: function ( callback ) { -}; + callback( this ); -THREE.InstancedBufferGeometry.prototype.copy = function ( source ) { + var children = this.children; - var index = source.index; + for ( var i = 0, l = children.length; i < l; i ++ ) { - if ( index !== null ) { + children[ i ].traverse( callback ); - this.setIndex( index.clone() ); + } - } + }, - var attributes = source.attributes; + traverseVisible: function ( callback ) { - for ( var name in attributes ) { + if ( this.visible === false ) return; - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + callback( this ); - } + var children = this.children; - var groups = source.groups; + for ( var i = 0, l = children.length; i < l; i ++ ) { - for ( var i = 0, l = groups.length; i < l; i ++ ) { + children[ i ].traverseVisible( callback ); - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.instances ); + } - } + }, - return this; + traverseAncestors: function ( callback ) { -}; + var parent = this.parent; -// File:src/core/Uniform.js + if ( parent !== null ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + callback( parent ); -THREE.Uniform = function ( value ) { + parent.traverseAncestors( callback ); - if ( typeof value === 'string' ) { + } - console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); - value = arguments[ 1 ]; + }, - } + updateMatrix: function () { - this.value = value; + this.matrix.compose( this.position, this.quaternion, this.scale ); - this.dynamic = false; + this.matrixWorldNeedsUpdate = true; -}; + }, -THREE.Uniform.prototype = { + updateMatrixWorld: function ( force ) { - constructor: THREE.Uniform, + if ( this.matrixAutoUpdate === true ) this.updateMatrix(); - onUpdate: function ( callback ) { + if ( this.matrixWorldNeedsUpdate === true || force === true ) { - this.dynamic = true; - this.onUpdateCallback = callback; + if ( this.parent === null ) { - return this; + this.matrixWorld.copy( this.matrix ); - } + } else { -}; + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); -// File:src/animation/AnimationAction.js + } -/** - * - * Action provided by AnimationMixer for scheduling clip playback on specific - * objects. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - * - */ + this.matrixWorldNeedsUpdate = false; -THREE.AnimationAction = function() { + force = true; - throw new Error( "THREE.AnimationAction: " + - "Use mixer.clipAction for construction." ); + } -}; + // update children -THREE.AnimationAction._new = - function AnimationAction( mixer, clip, localRoot ) { + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - this._mixer = mixer; - this._clip = clip; - this._localRoot = localRoot || null; + this.children[ i ].updateMatrixWorld( force ); - var tracks = clip.tracks, - nTracks = tracks.length, - interpolants = new Array( nTracks ); + } - var interpolantSettings = { - endingStart: THREE.ZeroCurvatureEnding, - endingEnd: THREE.ZeroCurvatureEnding - }; + }, - for ( var i = 0; i !== nTracks; ++ i ) { + toJSON: function ( meta ) { - var interpolant = tracks[ i ].createInterpolant( null ); - interpolants[ i ] = interpolant; - interpolant.settings = interpolantSettings; + // meta is '' when called from JSON.stringify + var isRootObject = ( meta === undefined || meta === '' ); - } + var output = {}; - this._interpolantSettings = interpolantSettings; + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { - this._interpolants = interpolants; // bound by the mixer + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {} + }; - // inside: PropertyMixer (managed by the mixer) - this._propertyBindings = new Array( nTracks ); + output.metadata = { + version: 4.4, + type: 'Object', + generator: 'Object3D.toJSON' + }; - this._cacheIndex = null; // for the memory manager - this._byClipCacheIndex = null; // for the memory manager + } - this._timeScaleInterpolant = null; - this._weightInterpolant = null; + // standard Object3D serialization - this.loop = THREE.LoopRepeat; - this._loopCount = -1; + var object = {}; - // global mixer time when the action is to be started - // it's set back to 'null' upon start of the action - this._startTime = null; + object.uuid = this.uuid; + object.type = this.type; - // scaled local time of the action - // gets clamped or wrapped to 0..clip.duration according to loop - this.time = 0; + if ( this.name !== '' ) object.name = this.name; + if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; - this.timeScale = 1; - this._effectiveTimeScale = 1; + object.matrix = this.matrix.toArray(); - this.weight = 1; - this._effectiveWeight = 1; + // - this.repetitions = Infinity; // no. of repetitions when looping + if ( this.geometry !== undefined ) { - this.paused = false; // false -> zero effective time scale - this.enabled = true; // true -> zero effective weight + if ( meta.geometries[ this.geometry.uuid ] === undefined ) { - this.clampWhenFinished = false; // keep feeding the last frame? + meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta ); - this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate - this.zeroSlopeAtEnd = true; // clips for start, loop and end + } -}; + object.geometry = this.geometry.uuid; -THREE.AnimationAction._new.prototype = { + } - constructor: THREE.AnimationAction._new, + if ( this.material !== undefined ) { - // State & Scheduling + if ( meta.materials[ this.material.uuid ] === undefined ) { - play: function() { + meta.materials[ this.material.uuid ] = this.material.toJSON( meta ); - this._mixer._activateAction( this ); + } - return this; + object.material = this.material.uuid; - }, + } - stop: function() { + // - this._mixer._deactivateAction( this ); + if ( this.children.length > 0 ) { - return this.reset(); + object.children = []; - }, + for ( var i = 0; i < this.children.length; i ++ ) { - reset: function() { + object.children.push( this.children[ i ].toJSON( meta ).object ); - this.paused = false; - this.enabled = true; + } - this.time = 0; // restart clip - this._loopCount = -1; // forget previous loops - this._startTime = null; // forget scheduling + } - return this.stopFading().stopWarping(); + if ( isRootObject ) { - }, + var geometries = extractFromCache( meta.geometries ); + var materials = extractFromCache( meta.materials ); + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - isRunning: function() { + if ( geometries.length > 0 ) output.geometries = geometries; + if ( materials.length > 0 ) output.materials = materials; + if ( textures.length > 0 ) output.textures = textures; + if ( images.length > 0 ) output.images = images; - var start = this._startTime; + } - return this.enabled && ! this.paused && this.timeScale !== 0 && - this._startTime === null && this._mixer._isActiveAction( this ); + output.object = object; - }, + return output; - // return true when play has been called - isScheduled: function() { + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache ( cache ) { - return this._mixer._isActiveAction( this ); + var values = []; + for ( var key in cache ) { - }, + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - startAt: function( time ) { + } + return values; - this._startTime = time; + } - return this; + }, - }, + clone: function ( recursive ) { - setLoop: function( mode, repetitions ) { + return new this.constructor().copy( this, recursive ); - this.loop = mode; - this.repetitions = repetitions; + }, - return this; + copy: function ( source, recursive ) { - }, + if ( recursive === undefined ) recursive = true; - // Weight + this.name = source.name; - // set the weight stopping any scheduled fading - // although .enabled = false yields an effective weight of zero, this - // method does *not* change .enabled, because it would be confusing - setEffectiveWeight: function( weight ) { + this.up.copy( source.up ); - this.weight = weight; + this.position.copy( source.position ); + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); - // note: same logic as when updated at runtime - this._effectiveWeight = this.enabled ? weight : 0; + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); - return this.stopFading(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; - }, + this.visible = source.visible; - // return the weight considering fading and .enabled - getEffectiveWeight: function() { + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; - return this._effectiveWeight; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; - }, + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - fadeIn: function( duration ) { + if ( recursive === true ) { - return this._scheduleFading( duration, 0, 1 ); + for ( var i = 0; i < source.children.length; i ++ ) { - }, + var child = source.children[ i ]; + this.add( child.clone() ); - fadeOut: function( duration ) { + } - return this._scheduleFading( duration, 1, 0 ); + } - }, + return this; - crossFadeFrom: function( fadeOutAction, duration, warp ) { + } - var mixer = this._mixer; + } ); - fadeOutAction.fadeOut( duration ); - this.fadeIn( duration ); + var count$3 = 0; + function Object3DIdCount () { return count$3++; }; - if( warp ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author kile / http://kile.stravaganza.org/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author bhouston / http://clara.io + */ - var fadeInDuration = this._clip.duration, - fadeOutDuration = fadeOutAction._clip.duration, + function Geometry () { + this.isGeometry = true; - startEndRatio = fadeOutDuration / fadeInDuration, - endStartRatio = fadeInDuration / fadeOutDuration; + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - fadeOutAction.warp( 1.0, startEndRatio, duration ); - this.warp( endStartRatio, 1.0, duration ); + this.uuid = exports.Math.generateUUID(); - } + this.name = ''; + this.type = 'Geometry'; - return this; + this.vertices = []; + this.colors = []; + this.faces = []; + this.faceVertexUvs = [ [] ]; - }, + this.morphTargets = []; + this.morphNormals = []; - crossFadeTo: function( fadeInAction, duration, warp ) { + this.skinWeights = []; + this.skinIndices = []; - return fadeInAction.crossFadeFrom( this, duration, warp ); + this.lineDistances = []; - }, + this.boundingBox = null; + this.boundingSphere = null; - stopFading: function() { + // update flags - var weightInterpolant = this._weightInterpolant; + this.elementsNeedUpdate = false; + this.verticesNeedUpdate = false; + this.uvsNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.lineDistancesNeedUpdate = false; + this.groupsNeedUpdate = false; - if ( weightInterpolant !== null ) { + }; - this._weightInterpolant = null; - this._mixer._takeBackControlInterpolant( weightInterpolant ); + Object.assign( Geometry.prototype, EventDispatcher.prototype, { - } + applyMatrix: function ( matrix ) { - return this; + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - }, + for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { - // Time Scale Control + var vertex = this.vertices[ i ]; + vertex.applyMatrix4( matrix ); - // set the weight stopping any scheduled warping - // although .paused = true yields an effective time scale of zero, this - // method does *not* change .paused, because it would be confusing - setEffectiveTimeScale: function( timeScale ) { + } - this.timeScale = timeScale; - this._effectiveTimeScale = this.paused ? 0 :timeScale; + for ( var i = 0, il = this.faces.length; i < il; i ++ ) { - return this.stopWarping(); + var face = this.faces[ i ]; + face.normal.applyMatrix3( normalMatrix ).normalize(); - }, + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - // return the time scale considering warping and .paused - getEffectiveTimeScale: function() { + face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); - return this._effectiveTimeScale; + } - }, + } - setDuration: function( duration ) { + if ( this.boundingBox !== null ) { - this.timeScale = this._clip.duration / duration; + this.computeBoundingBox(); - return this.stopWarping(); + } - }, + if ( this.boundingSphere !== null ) { - syncWith: function( action ) { + this.computeBoundingSphere(); - this.time = action.time; - this.timeScale = action.timeScale; + } - return this.stopWarping(); + this.verticesNeedUpdate = true; + this.normalsNeedUpdate = true; - }, + return this; - halt: function( duration ) { + }, - return this.warp( this._effectiveTimeScale, 0, duration ); + rotateX: function () { - }, + // rotate geometry around world x-axis - warp: function( startTimeScale, endTimeScale, duration ) { + var m1; - var mixer = this._mixer, now = mixer.time, - interpolant = this._timeScaleInterpolant, + return function rotateX( angle ) { - timeScale = this.timeScale; + if ( m1 === undefined ) m1 = new Matrix4(); - if ( interpolant === null ) { + m1.makeRotationX( angle ); - interpolant = mixer._lendControlInterpolant(), - this._timeScaleInterpolant = interpolant; + this.applyMatrix( m1 ); - } + return this; - var times = interpolant.parameterPositions, - values = interpolant.sampleValues; + }; - times[ 0 ] = now; - times[ 1 ] = now + duration; + }(), - values[ 0 ] = startTimeScale / timeScale; - values[ 1 ] = endTimeScale / timeScale; + rotateY: function () { - return this; + // rotate geometry around world y-axis - }, + var m1; - stopWarping: function() { + return function rotateY( angle ) { - var timeScaleInterpolant = this._timeScaleInterpolant; + if ( m1 === undefined ) m1 = new Matrix4(); - if ( timeScaleInterpolant !== null ) { + m1.makeRotationY( angle ); - this._timeScaleInterpolant = null; - this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); + this.applyMatrix( m1 ); - } + return this; - return this; + }; - }, + }(), - // Object Accessors + rotateZ: function () { - getMixer: function() { + // rotate geometry around world z-axis - return this._mixer; + var m1; - }, + return function rotateZ( angle ) { - getClip: function() { + if ( m1 === undefined ) m1 = new Matrix4(); - return this._clip; + m1.makeRotationZ( angle ); - }, + this.applyMatrix( m1 ); - getRoot: function() { + return this; - return this._localRoot || this._mixer._root; + }; - }, + }(), - // Interna + translate: function () { - _update: function( time, deltaTime, timeDirection, accuIndex ) { - // called by the mixer + // translate geometry - var startTime = this._startTime; + var m1; - if ( startTime !== null ) { + return function translate( x, y, z ) { - // check for scheduled start of action + if ( m1 === undefined ) m1 = new Matrix4(); - var timeRunning = ( time - startTime ) * timeDirection; - if ( timeRunning < 0 || timeDirection === 0 ) { + m1.makeTranslation( x, y, z ); - return; // yet to come / don't decide when delta = 0 + this.applyMatrix( m1 ); - } + return this; - // start + }; - this._startTime = null; // unschedule - deltaTime = timeDirection * timeRunning; + }(), - } + scale: function () { - // apply time scale and advance time + // scale geometry - deltaTime *= this._updateTimeScale( time ); - var clipTime = this._updateTime( deltaTime ); + var m1; - // note: _updateTime may disable the action resulting in - // an effective weight of 0 + return function scale( x, y, z ) { - var weight = this._updateWeight( time ); + if ( m1 === undefined ) m1 = new Matrix4(); - if ( weight > 0 ) { + m1.makeScale( x, y, z ); - var interpolants = this._interpolants; - var propertyMixers = this._propertyBindings; + this.applyMatrix( m1 ); - for ( var j = 0, m = interpolants.length; j !== m; ++ j ) { + return this; - interpolants[ j ].evaluate( clipTime ); - propertyMixers[ j ].accumulate( accuIndex, weight ); + }; - } + }(), - } + lookAt: function () { - }, + var obj; - _updateWeight: function( time ) { + return function lookAt( vector ) { - var weight = 0; + if ( obj === undefined ) obj = new Object3D(); - if ( this.enabled ) { + obj.lookAt( vector ); - weight = this.weight; - var interpolant = this._weightInterpolant; + obj.updateMatrix(); - if ( interpolant !== null ) { + this.applyMatrix( obj.matrix ); - var interpolantValue = interpolant.evaluate( time )[ 0 ]; + }; - weight *= interpolantValue; + }(), - if ( time > interpolant.parameterPositions[ 1 ] ) { + fromBufferGeometry: function ( geometry ) { - this.stopFading(); + var scope = this; - if ( interpolantValue === 0 ) { + var indices = geometry.index !== null ? geometry.index.array : undefined; + var attributes = geometry.attributes; - // faded out, disable - this.enabled = false; + var positions = attributes.position.array; + var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; + var colors = attributes.color !== undefined ? attributes.color.array : undefined; + var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; + var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; - } + if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; - } + var tempNormals = []; + var tempUVs = []; + var tempUVs2 = []; - } + for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { - } + scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); - this._effectiveWeight = weight; - return weight; + if ( normals !== undefined ) { - }, + tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); - _updateTimeScale: function( time ) { + } - var timeScale = 0; + if ( colors !== undefined ) { - if ( ! this.paused ) { + scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); - timeScale = this.timeScale; + } - var interpolant = this._timeScaleInterpolant; + if ( uvs !== undefined ) { - if ( interpolant !== null ) { + tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); - var interpolantValue = interpolant.evaluate( time )[ 0 ]; + } - timeScale *= interpolantValue; + if ( uvs2 !== undefined ) { - if ( time > interpolant.parameterPositions[ 1 ] ) { + tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); - this.stopWarping(); + } - if ( timeScale === 0 ) { + } - // motion has halted, pause - this.paused = true; + function addFace( a, b, c, materialIndex ) { - } else { + var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; + var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; - // warp done - apply final time scale - this.timeScale = timeScale; + var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); - } + scope.faces.push( face ); - } + if ( uvs !== undefined ) { - } + scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); - } + } - this._effectiveTimeScale = timeScale; - return timeScale; + if ( uvs2 !== undefined ) { - }, + scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); - _updateTime: function( deltaTime ) { + } - var time = this.time + deltaTime; + } - if ( deltaTime === 0 ) return time; + if ( indices !== undefined ) { - var duration = this._clip.duration, + var groups = geometry.groups; - loop = this.loop, - loopCount = this._loopCount; + if ( groups.length > 0 ) { - if ( loop === THREE.LoopOnce ) { + for ( var i = 0; i < groups.length; i ++ ) { - if ( loopCount === -1 ) { - // just started + var group = groups[ i ]; - this.loopCount = 0; - this._setEndings( true, true, false ); + var start = group.start; + var count = group.count; - } + for ( var j = start, jl = start + count; j < jl; j += 3 ) { - handle_stop: { + addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); - if ( time >= duration ) { + } - time = duration; + } - } else if ( time < 0 ) { + } else { - time = 0; + for ( var i = 0; i < indices.length; i += 3 ) { - } else break handle_stop; + addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); - if ( this.clampWhenFinished ) this.paused = true; - else this.enabled = false; + } - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime < 0 ? -1 : 1 - } ); + } - } + } else { - } else { // repetitive Repeat or PingPong + for ( var i = 0; i < positions.length / 3; i += 3 ) { - var pingPong = ( loop === THREE.LoopPingPong ); + addFace( i, i + 1, i + 2 ); - if ( loopCount === -1 ) { - // just started + } - if ( deltaTime >= 0 ) { + } - loopCount = 0; + this.computeFaceNormals(); - this._setEndings( - true, this.repetitions === 0, pingPong ); + if ( geometry.boundingBox !== null ) { - } else { + this.boundingBox = geometry.boundingBox.clone(); - // when looping in reverse direction, the initial - // transition through zero counts as a repetition, - // so leave loopCount at -1 + } - this._setEndings( - this.repetitions === 0, true, pingPong ); + if ( geometry.boundingSphere !== null ) { - } + this.boundingSphere = geometry.boundingSphere.clone(); - } + } - if ( time >= duration || time < 0 ) { - // wrap around + return this; - var loopDelta = Math.floor( time / duration ); // signed - time -= duration * loopDelta; + }, - loopCount += Math.abs( loopDelta ); + center: function () { - var pending = this.repetitions - loopCount; + this.computeBoundingBox(); - if ( pending < 0 ) { - // have to stop (switch state, clamp time, fire event) + var offset = this.boundingBox.center().negate(); - if ( this.clampWhenFinished ) this.paused = true; - else this.enabled = false; + this.translate( offset.x, offset.y, offset.z ); - time = deltaTime > 0 ? duration : 0; + return offset; - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime > 0 ? 1 : -1 - } ); + }, - } else { - // keep running + normalize: function () { - if ( pending === 0 ) { - // entering the last round + this.computeBoundingSphere(); - var atStart = deltaTime < 0; - this._setEndings( atStart, ! atStart, pingPong ); + var center = this.boundingSphere.center; + var radius = this.boundingSphere.radius; - } else { + var s = radius === 0 ? 1 : 1.0 / radius; - this._setEndings( false, false, pingPong ); + var matrix = new Matrix4(); + matrix.set( + s, 0, 0, - s * center.x, + 0, s, 0, - s * center.y, + 0, 0, s, - s * center.z, + 0, 0, 0, 1 + ); - } + this.applyMatrix( matrix ); - this._loopCount = loopCount; + return this; - this._mixer.dispatchEvent( { - type: 'loop', action: this, loopDelta: loopDelta - } ); + }, - } + computeFaceNormals: function () { - } + var cb = new Vector3(), ab = new Vector3(); - if ( pingPong && ( loopCount & 1 ) === 1 ) { - // invert time for the "pong round" + for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { - this.time = time; - return duration - time; + var face = this.faces[ f ]; - } + var vA = this.vertices[ face.a ]; + var vB = this.vertices[ face.b ]; + var vC = this.vertices[ face.c ]; - } + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - this.time = time; - return time; + cb.normalize(); - }, + face.normal.copy( cb ); - _setEndings: function( atStart, atEnd, pingPong ) { + } - var settings = this._interpolantSettings; + }, - if ( pingPong ) { + computeVertexNormals: function ( areaWeighted ) { - settings.endingStart = THREE.ZeroSlopeEnding; - settings.endingEnd = THREE.ZeroSlopeEnding; + if ( areaWeighted === undefined ) areaWeighted = true; - } else { + var v, vl, f, fl, face, vertices; - // assuming for LoopOnce atStart == atEnd == true + vertices = new Array( this.vertices.length ); - if ( atStart ) { + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - settings.endingStart = this.zeroSlopeAtStart ? - THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding; + vertices[ v ] = new Vector3(); - } else { + } - settings.endingStart = THREE.WrapAroundEnding; + if ( areaWeighted ) { - } + // vertex normals weighted by triangle areas + // http://www.iquilezles.org/www/articles/normals/normals.htm - if ( atEnd ) { + var vA, vB, vC; + var cb = new Vector3(), ab = new Vector3(); - settings.endingEnd = this.zeroSlopeAtEnd ? - THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - } else { + face = this.faces[ f ]; - settings.endingEnd = THREE.WrapAroundEnding; + vA = this.vertices[ face.a ]; + vB = this.vertices[ face.b ]; + vC = this.vertices[ face.c ]; - } + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - } + vertices[ face.a ].add( cb ); + vertices[ face.b ].add( cb ); + vertices[ face.c ].add( cb ); - }, + } - _scheduleFading: function( duration, weightNow, weightThen ) { + } else { - var mixer = this._mixer, now = mixer.time, - interpolant = this._weightInterpolant; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - if ( interpolant === null ) { + face = this.faces[ f ]; - interpolant = mixer._lendControlInterpolant(), - this._weightInterpolant = interpolant; + vertices[ face.a ].add( face.normal ); + vertices[ face.b ].add( face.normal ); + vertices[ face.c ].add( face.normal ); - } + } - var times = interpolant.parameterPositions, - values = interpolant.sampleValues; + } - times[ 0 ] = now; values[ 0 ] = weightNow; - times[ 1 ] = now + duration; values[ 1 ] = weightThen; + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - return this; + vertices[ v ].normalize(); - } + } -}; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + face = this.faces[ f ]; -// File:src/animation/AnimationClip.js + var vertexNormals = face.vertexNormals; -/** - * - * Reusable set of Tracks that represent an animation. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + if ( vertexNormals.length === 3 ) { -THREE.AnimationClip = function ( name, duration, tracks ) { + vertexNormals[ 0 ].copy( vertices[ face.a ] ); + vertexNormals[ 1 ].copy( vertices[ face.b ] ); + vertexNormals[ 2 ].copy( vertices[ face.c ] ); - this.name = name; - this.tracks = tracks; - this.duration = ( duration !== undefined ) ? duration : -1; + } else { - this.uuid = THREE.Math.generateUUID(); + vertexNormals[ 0 ] = vertices[ face.a ].clone(); + vertexNormals[ 1 ] = vertices[ face.b ].clone(); + vertexNormals[ 2 ] = vertices[ face.c ].clone(); - // this means it should figure out its duration by scanning the tracks - if ( this.duration < 0 ) { + } - this.resetDuration(); + } - } + if ( this.faces.length > 0 ) { - // maybe only do these on demand, as doing them here could potentially slow down loading - // but leaving these here during development as this ensures a lot of testing of these functions - this.trim(); - this.optimize(); + this.normalsNeedUpdate = true; -}; + } -THREE.AnimationClip.prototype = { + }, - constructor: THREE.AnimationClip, + computeMorphNormals: function () { - resetDuration: function() { + var i, il, f, fl, face; - var tracks = this.tracks, - duration = 0; + // save original normals + // - create temp variables on first access + // otherwise just copy (for faster repeated calls) - for ( var i = 0, n = tracks.length; i !== n; ++ i ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - var track = this.tracks[ i ]; + face = this.faces[ f ]; - duration = Math.max( - duration, track.times[ track.times.length - 1 ] ); + if ( ! face.__originalFaceNormal ) { - } + face.__originalFaceNormal = face.normal.clone(); - this.duration = duration; + } else { - }, + face.__originalFaceNormal.copy( face.normal ); - trim: function() { + } - for ( var i = 0; i < this.tracks.length; i ++ ) { + if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; - this.tracks[ i ].trim( 0, this.duration ); + for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { - } + if ( ! face.__originalVertexNormals[ i ] ) { - return this; + face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); - }, + } else { - optimize: function() { + face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); - for ( var i = 0; i < this.tracks.length; i ++ ) { + } - this.tracks[ i ].optimize(); + } - } + } - return this; + // use temp geometry to compute face and vertex normals for each morph - } + var tmpGeo = new Geometry(); + tmpGeo.faces = this.faces; -}; + for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { -// Static methods: + // create on first access -Object.assign( THREE.AnimationClip, { + if ( ! this.morphNormals[ i ] ) { - parse: function( json ) { + this.morphNormals[ i ] = {}; + this.morphNormals[ i ].faceNormals = []; + this.morphNormals[ i ].vertexNormals = []; - var tracks = [], - jsonTracks = json.tracks, - frameTime = 1.0 / ( json.fps || 1.0 ); + var dstNormalsFace = this.morphNormals[ i ].faceNormals; + var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; - for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { + var faceNormal, vertexNormals; - tracks.push( THREE.KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - } + faceNormal = new Vector3(); + vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; - return new THREE.AnimationClip( json.name, json.duration, tracks ); + dstNormalsFace.push( faceNormal ); + dstNormalsVertex.push( vertexNormals ); - }, + } + } - toJSON: function( clip ) { + var morphNormals = this.morphNormals[ i ]; - var tracks = [], - clipTracks = clip.tracks; + // set vertices to morph target - var json = { + tmpGeo.vertices = this.morphTargets[ i ].vertices; - 'name': clip.name, - 'duration': clip.duration, - 'tracks': tracks + // compute morph normals - }; + tmpGeo.computeFaceNormals(); + tmpGeo.computeVertexNormals(); - for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { + // store morph normals - tracks.push( THREE.KeyframeTrack.toJSON( clipTracks[ i ] ) ); + var faceNormal, vertexNormals; - } + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - return json; + face = this.faces[ f ]; - }, + faceNormal = morphNormals.faceNormals[ f ]; + vertexNormals = morphNormals.vertexNormals[ f ]; + faceNormal.copy( face.normal ); - CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) { + vertexNormals.a.copy( face.vertexNormals[ 0 ] ); + vertexNormals.b.copy( face.vertexNormals[ 1 ] ); + vertexNormals.c.copy( face.vertexNormals[ 2 ] ); - var numMorphTargets = morphTargetSequence.length; - var tracks = []; + } - for ( var i = 0; i < numMorphTargets; i ++ ) { + } - var times = []; - var values = []; + // restore original normals - times.push( - ( i + numMorphTargets - 1 ) % numMorphTargets, - i, - ( i + 1 ) % numMorphTargets ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - values.push( 0, 1, 0 ); + face = this.faces[ f ]; - var order = THREE.AnimationUtils.getKeyframeOrder( times ); - times = THREE.AnimationUtils.sortedArray( times, 1, order ); - values = THREE.AnimationUtils.sortedArray( values, 1, order ); + face.normal = face.__originalFaceNormal; + face.vertexNormals = face.__originalVertexNormals; - // if there is a key at the first frame, duplicate it as the - // last frame as well for perfect loop. - if ( ! noLoop && times[ 0 ] === 0 ) { + } - times.push( numMorphTargets ); - values.push( values[ 0 ] ); + }, - } + computeTangents: function () { - tracks.push( - new THREE.NumberKeyframeTrack( - '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', - times, values - ).scale( 1.0 / fps ) ); - } + console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); - return new THREE.AnimationClip( name, -1, tracks ); + }, - }, + computeLineDistances: function () { - findByName: function( objectOrClipArray, name ) { + var d = 0; + var vertices = this.vertices; - var clipArray = objectOrClipArray; + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - if ( ! Array.isArray( objectOrClipArray ) ) { + if ( i > 0 ) { - var o = objectOrClipArray; - clipArray = o.geometry && o.geometry.animations || o.animations; + d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); - } + } - for ( var i = 0; i < clipArray.length; i ++ ) { + this.lineDistances[ i ] = d; - if ( clipArray[ i ].name === name ) { + } - return clipArray[ i ]; + }, - } - } + computeBoundingBox: function () { - return null; + if ( this.boundingBox === null ) { - }, + this.boundingBox = new Box3(); - CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) { + } - var animationToMorphTargets = {}; + this.boundingBox.setFromPoints( this.vertices ); - // tested with https://regex101.com/ on trick sequences - // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 - var pattern = /^([\w-]*?)([\d]+)$/; + }, - // sort morph target names into animation groups based - // patterns like Walk_001, Walk_002, Run_001, Run_002 - for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { + computeBoundingSphere: function () { - var morphTarget = morphTargets[ i ]; - var parts = morphTarget.name.match( pattern ); + if ( this.boundingSphere === null ) { - if ( parts && parts.length > 1 ) { + this.boundingSphere = new Sphere(); - var name = parts[ 1 ]; + } - var animationMorphTargets = animationToMorphTargets[ name ]; - if ( ! animationMorphTargets ) { + this.boundingSphere.setFromPoints( this.vertices ); - animationToMorphTargets[ name ] = animationMorphTargets = []; + }, - } + merge: function ( geometry, matrix, materialIndexOffset ) { - animationMorphTargets.push( morphTarget ); + if ( (geometry && geometry.isGeometry) === false ) { - } + console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); + return; - } + } - var clips = []; + var normalMatrix, + vertexOffset = this.vertices.length, + vertices1 = this.vertices, + vertices2 = geometry.vertices, + faces1 = this.faces, + faces2 = geometry.faces, + uvs1 = this.faceVertexUvs[ 0 ], + uvs2 = geometry.faceVertexUvs[ 0 ]; - for ( var name in animationToMorphTargets ) { + if ( materialIndexOffset === undefined ) materialIndexOffset = 0; - clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + if ( matrix !== undefined ) { - } + normalMatrix = new Matrix3().getNormalMatrix( matrix ); - return clips; + } - }, + // vertices - // parse the animation.hierarchy format - parseAnimation: function( animation, bones, nodeName ) { + for ( var i = 0, il = vertices2.length; i < il; i ++ ) { - if ( ! animation ) { + var vertex = vertices2[ i ]; - console.error( " no animation in JSONLoader data" ); - return null; + var vertexCopy = vertex.clone(); - } + if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); - var addNonemptyTrack = function( - trackType, trackName, animationKeys, propertyName, destTracks ) { + vertices1.push( vertexCopy ); - // only return track if there are actually keys. - if ( animationKeys.length !== 0 ) { + } - var times = []; - var values = []; + // faces - THREE.AnimationUtils.flattenJSON( - animationKeys, times, values, propertyName ); + for ( i = 0, il = faces2.length; i < il; i ++ ) { - // empty keys are filtered out, so check again - if ( times.length !== 0 ) { + var face = faces2[ i ], faceCopy, normal, color, + faceVertexNormals = face.vertexNormals, + faceVertexColors = face.vertexColors; - destTracks.push( new trackType( trackName, times, values ) ); + faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); + faceCopy.normal.copy( face.normal ); - } + if ( normalMatrix !== undefined ) { - } + faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); - }; + } - var tracks = []; + for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { - var clipName = animation.name || 'default'; - // automatic length determination in AnimationClip. - var duration = animation.length || -1; - var fps = animation.fps || 30; + normal = faceVertexNormals[ j ].clone(); - var hierarchyTracks = animation.hierarchy || []; + if ( normalMatrix !== undefined ) { - for ( var h = 0; h < hierarchyTracks.length; h ++ ) { + normal.applyMatrix3( normalMatrix ).normalize(); - var animationKeys = hierarchyTracks[ h ].keys; + } - // skip empty tracks - if ( ! animationKeys || animationKeys.length === 0 ) continue; + faceCopy.vertexNormals.push( normal ); - // process morph targets in a way exactly compatible - // with AnimationHandler.init( animation ) - if ( animationKeys[0].morphTargets ) { + } - // figure out all morph targets used in this track - var morphTargetNames = {}; - for ( var k = 0; k < animationKeys.length; k ++ ) { + faceCopy.color.copy( face.color ); - if ( animationKeys[k].morphTargets ) { + for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { - for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) { + color = faceVertexColors[ j ]; + faceCopy.vertexColors.push( color.clone() ); - morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1; - } + } - } + faceCopy.materialIndex = face.materialIndex + materialIndexOffset; - } + faces1.push( faceCopy ); - // create a track for each morph target with all zero - // morphTargetInfluences except for the keys in which - // the morphTarget is named. - for ( var morphTargetName in morphTargetNames ) { + } - var times = []; - var values = []; + // uvs - for ( var m = 0; - m !== animationKeys[k].morphTargets.length; ++ m ) { + for ( i = 0, il = uvs2.length; i < il; i ++ ) { - var animationKey = animationKeys[k]; + var uv = uvs2[ i ], uvCopy = []; - times.push( animationKey.time ); - values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + if ( uv === undefined ) { - } + continue; - tracks.push( new THREE.NumberKeyframeTrack( - '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + } - } + for ( var j = 0, jl = uv.length; j < jl; j ++ ) { - duration = morphTargetNames.length * ( fps || 1.0 ); + uvCopy.push( uv[ j ].clone() ); - } else { - // ...assume skeletal animation + } - var boneName = '.bones[' + bones[ h ].name + ']'; + uvs1.push( uvCopy ); - addNonemptyTrack( - THREE.VectorKeyframeTrack, boneName + '.position', - animationKeys, 'pos', tracks ); + } - addNonemptyTrack( - THREE.QuaternionKeyframeTrack, boneName + '.quaternion', - animationKeys, 'rot', tracks ); + }, - addNonemptyTrack( - THREE.VectorKeyframeTrack, boneName + '.scale', - animationKeys, 'scl', tracks ); + mergeMesh: function ( mesh ) { - } + if ( (mesh && mesh.isMesh) === false ) { - } + console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); + return; - if ( tracks.length === 0 ) { + } - return null; + mesh.matrixAutoUpdate && mesh.updateMatrix(); - } + this.merge( mesh.geometry, mesh.matrix ); - var clip = new THREE.AnimationClip( clipName, duration, tracks ); + }, - return clip; + /* + * Checks for duplicate vertices with hashmap. + * Duplicated vertices are removed + * and faces' vertices are updated. + */ - } + mergeVertices: function () { -} ); + var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) + var unique = [], changes = []; -// File:src/animation/AnimationMixer.js + var v, key; + var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 + var precision = Math.pow( 10, precisionPoints ); + var i, il, face; + var indices, j, jl; -/** - * - * Player for AnimationClips. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + for ( i = 0, il = this.vertices.length; i < il; i ++ ) { -THREE.AnimationMixer = function( root ) { + v = this.vertices[ i ]; + key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); - this._root = root; - this._initMemoryManager(); - this._accuIndex = 0; + if ( verticesMap[ key ] === undefined ) { - this.time = 0; + verticesMap[ key ] = i; + unique.push( this.vertices[ i ] ); + changes[ i ] = unique.length - 1; - this.timeScale = 1.0; + } else { -}; + //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); + changes[ i ] = changes[ verticesMap[ key ] ]; -Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, { + } - // return an action for a clip optionally using a custom root target - // object (this method allocates a lot of dynamic memory in case a - // previously unknown clip/root combination is specified) - clipAction: function( clip, optionalRoot ) { + } - var root = optionalRoot || this._root, - rootUuid = root.uuid, - clipObject = typeof clip === 'string' ? - THREE.AnimationClip.findByName( root, clip ) : clip, + // if faces are completely degenerate after merging vertices, we + // have to remove them from the geometry. + var faceIndicesToRemove = []; - clipUuid = clipObject !== null ? clipObject.uuid : clip, + for ( i = 0, il = this.faces.length; i < il; i ++ ) { - actionsForClip = this._actionsByClip[ clipUuid ], - prototypeAction = null; + face = this.faces[ i ]; - if ( actionsForClip !== undefined ) { + face.a = changes[ face.a ]; + face.b = changes[ face.b ]; + face.c = changes[ face.c ]; - var existingAction = - actionsForClip.actionByRoot[ rootUuid ]; + indices = [ face.a, face.b, face.c ]; - if ( existingAction !== undefined ) { + var dupIndex = - 1; - return existingAction; + // if any duplicate vertices are found in a Face3 + // we have to remove the face as nothing can be saved + for ( var n = 0; n < 3; n ++ ) { - } + if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { - // we know the clip, so we don't have to parse all - // the bindings again but can just copy - prototypeAction = actionsForClip.knownActions[ 0 ]; + dupIndex = n; + faceIndicesToRemove.push( i ); + break; - // also, take the clip from the prototype action - if ( clipObject === null ) - clipObject = prototypeAction._clip; + } - } + } - // clip must be known when specified via string - if ( clipObject === null ) return null; + } - // allocate all resources required to run it - var newAction = new THREE. - AnimationMixer._Action( this, clipObject, optionalRoot ); + for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { - this._bindAction( newAction, prototypeAction ); + var idx = faceIndicesToRemove[ i ]; - // and make the action known to the memory manager - this._addInactiveAction( newAction, clipUuid, rootUuid ); + this.faces.splice( idx, 1 ); - return newAction; + for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { - }, + this.faceVertexUvs[ j ].splice( idx, 1 ); - // get an existing action - existingAction: function( clip, optionalRoot ) { + } - var root = optionalRoot || this._root, - rootUuid = root.uuid, + } - clipObject = typeof clip === 'string' ? - THREE.AnimationClip.findByName( root, clip ) : clip, + // Use unique set of vertices - clipUuid = clipObject ? clipObject.uuid : clip, + var diff = this.vertices.length - unique.length; + this.vertices = unique; + return diff; - actionsForClip = this._actionsByClip[ clipUuid ]; + }, - if ( actionsForClip !== undefined ) { + sortFacesByMaterialIndex: function () { - return actionsForClip.actionByRoot[ rootUuid ] || null; + var faces = this.faces; + var length = faces.length; - } + // tag faces - return null; + for ( var i = 0; i < length; i ++ ) { - }, + faces[ i ]._id = i; - // deactivates all previously scheduled actions - stopAllAction: function() { + } - var actions = this._actions, - nActions = this._nActiveActions, - bindings = this._bindings, - nBindings = this._nActiveBindings; + // sort faces - this._nActiveActions = 0; - this._nActiveBindings = 0; + function materialIndexSort( a, b ) { - for ( var i = 0; i !== nActions; ++ i ) { + return a.materialIndex - b.materialIndex; - actions[ i ].reset(); + } - } + faces.sort( materialIndexSort ); - for ( var i = 0; i !== nBindings; ++ i ) { + // sort uvs - bindings[ i ].useCount = 0; + var uvs1 = this.faceVertexUvs[ 0 ]; + var uvs2 = this.faceVertexUvs[ 1 ]; - } + var newUvs1, newUvs2; - return this; + if ( uvs1 && uvs1.length === length ) newUvs1 = []; + if ( uvs2 && uvs2.length === length ) newUvs2 = []; - }, + for ( var i = 0; i < length; i ++ ) { - // advance the time and update apply the animation - update: function( deltaTime ) { + var id = faces[ i ]._id; - deltaTime *= this.timeScale; + if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); + if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); - var actions = this._actions, - nActions = this._nActiveActions, + } - time = this.time += deltaTime, - timeDirection = Math.sign( deltaTime ), + if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; + if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; - accuIndex = this._accuIndex ^= 1; + }, - // run active actions + toJSON: function () { - for ( var i = 0; i !== nActions; ++ i ) { + var data = { + metadata: { + version: 4.4, + type: 'Geometry', + generator: 'Geometry.toJSON' + } + }; - var action = actions[ i ]; + // standard Geometry serialization - if ( action.enabled ) { + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - action._update( time, deltaTime, timeDirection, accuIndex ); + if ( this.parameters !== undefined ) { - } + var parameters = this.parameters; - } + for ( var key in parameters ) { - // update scene graph + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - var bindings = this._bindings, - nBindings = this._nActiveBindings; + } - for ( var i = 0; i !== nBindings; ++ i ) { + return data; - bindings[ i ].apply( accuIndex ); + } - } + var vertices = []; - return this; + for ( var i = 0; i < this.vertices.length; i ++ ) { - }, + var vertex = this.vertices[ i ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - // return this mixer's root target object - getRoot: function() { + } - return this._root; + var faces = []; + var normals = []; + var normalsHash = {}; + var colors = []; + var colorsHash = {}; + var uvs = []; + var uvsHash = {}; - }, + for ( var i = 0; i < this.faces.length; i ++ ) { - // free all resources specific to a particular clip - uncacheClip: function( clip ) { + var face = this.faces[ i ]; - var actions = this._actions, - clipUuid = clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ]; + var hasMaterial = true; + var hasFaceUv = false; // deprecated + var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; + var hasFaceNormal = face.normal.length() > 0; + var hasFaceVertexNormal = face.vertexNormals.length > 0; + var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; + var hasFaceVertexColor = face.vertexColors.length > 0; - if ( actionsForClip !== undefined ) { + var faceType = 0; - // note: just calling _removeInactiveAction would mess up the - // iteration state and also require updating the state we can - // just throw away + faceType = setBit( faceType, 0, 0 ); // isQuad + faceType = setBit( faceType, 1, hasMaterial ); + faceType = setBit( faceType, 2, hasFaceUv ); + faceType = setBit( faceType, 3, hasFaceVertexUv ); + faceType = setBit( faceType, 4, hasFaceNormal ); + faceType = setBit( faceType, 5, hasFaceVertexNormal ); + faceType = setBit( faceType, 6, hasFaceColor ); + faceType = setBit( faceType, 7, hasFaceVertexColor ); - var actionsToRemove = actionsForClip.knownActions; + faces.push( faceType ); + faces.push( face.a, face.b, face.c ); + faces.push( face.materialIndex ); - for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) { + if ( hasFaceVertexUv ) { - var action = actionsToRemove[ i ]; + var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; - this._deactivateAction( action ); + faces.push( + getUvIndex( faceVertexUvs[ 0 ] ), + getUvIndex( faceVertexUvs[ 1 ] ), + getUvIndex( faceVertexUvs[ 2 ] ) + ); - var cacheIndex = action._cacheIndex, - lastInactiveAction = actions[ actions.length - 1 ]; + } - action._cacheIndex = null; - action._byClipCacheIndex = null; + if ( hasFaceNormal ) { - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + faces.push( getNormalIndex( face.normal ) ); - this._removeInactiveBindingsForAction( action ); + } - } + if ( hasFaceVertexNormal ) { - delete actionsByClip[ clipUuid ]; + var vertexNormals = face.vertexNormals; - } + faces.push( + getNormalIndex( vertexNormals[ 0 ] ), + getNormalIndex( vertexNormals[ 1 ] ), + getNormalIndex( vertexNormals[ 2 ] ) + ); - }, + } - // free all resources specific to a particular root target object - uncacheRoot: function( root ) { + if ( hasFaceColor ) { - var rootUuid = root.uuid, - actionsByClip = this._actionsByClip; + faces.push( getColorIndex( face.color ) ); - for ( var clipUuid in actionsByClip ) { + } - var actionByRoot = actionsByClip[ clipUuid ].actionByRoot, - action = actionByRoot[ rootUuid ]; + if ( hasFaceVertexColor ) { - if ( action !== undefined ) { + var vertexColors = face.vertexColors; - this._deactivateAction( action ); - this._removeInactiveAction( action ); + faces.push( + getColorIndex( vertexColors[ 0 ] ), + getColorIndex( vertexColors[ 1 ] ), + getColorIndex( vertexColors[ 2 ] ) + ); - } + } - } + } - var bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ]; + function setBit( value, position, enabled ) { - if ( bindingByName !== undefined ) { + return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); - for ( var trackName in bindingByName ) { + } - var binding = bindingByName[ trackName ]; - binding.restoreOriginalState(); - this._removeInactiveBinding( binding ); + function getNormalIndex( normal ) { - } + var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); - } + if ( normalsHash[ hash ] !== undefined ) { - }, + return normalsHash[ hash ]; - // remove a targeted clip from the cache - uncacheAction: function( clip, optionalRoot ) { + } - var action = this.existingAction( clip, optionalRoot ); + normalsHash[ hash ] = normals.length / 3; + normals.push( normal.x, normal.y, normal.z ); - if ( action !== null ) { + return normalsHash[ hash ]; - this._deactivateAction( action ); - this._removeInactiveAction( action ); + } - } + function getColorIndex( color ) { - } + var hash = color.r.toString() + color.g.toString() + color.b.toString(); -} ); + if ( colorsHash[ hash ] !== undefined ) { -THREE.AnimationMixer._Action = THREE.AnimationAction._new; + return colorsHash[ hash ]; -// Implementation details: + } -Object.assign( THREE.AnimationMixer.prototype, { + colorsHash[ hash ] = colors.length; + colors.push( color.getHex() ); - _bindAction: function( action, prototypeAction ) { + return colorsHash[ hash ]; - var root = action._localRoot || this._root, - tracks = action._clip.tracks, - nTracks = tracks.length, - bindings = action._propertyBindings, - interpolants = action._interpolants, - rootUuid = root.uuid, - bindingsByRoot = this._bindingsByRootAndName, - bindingsByName = bindingsByRoot[ rootUuid ]; + } - if ( bindingsByName === undefined ) { + function getUvIndex( uv ) { - bindingsByName = {}; - bindingsByRoot[ rootUuid ] = bindingsByName; + var hash = uv.x.toString() + uv.y.toString(); - } + if ( uvsHash[ hash ] !== undefined ) { - for ( var i = 0; i !== nTracks; ++ i ) { + return uvsHash[ hash ]; - var track = tracks[ i ], - trackName = track.name, - binding = bindingsByName[ trackName ]; + } - if ( binding !== undefined ) { + uvsHash[ hash ] = uvs.length / 2; + uvs.push( uv.x, uv.y ); - bindings[ i ] = binding; + return uvsHash[ hash ]; - } else { + } - binding = bindings[ i ]; + data.data = {}; - if ( binding !== undefined ) { + data.data.vertices = vertices; + data.data.normals = normals; + if ( colors.length > 0 ) data.data.colors = colors; + if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility + data.data.faces = faces; - // existing binding, make sure the cache knows + return data; - if ( binding._cacheIndex === null ) { + }, - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + clone: function () { - } + /* + // Handle primitives - continue; + var parameters = this.parameters; - } + if ( parameters !== undefined ) { - var path = prototypeAction && prototypeAction. - _propertyBindings[ i ].binding.parsedPath; + var values = []; - binding = new THREE.PropertyMixer( - THREE.PropertyBinding.create( root, trackName, path ), - track.ValueTypeName, track.getValueSize() ); + for ( var key in parameters ) { - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + values.push( parameters[ key ] ); - bindings[ i ] = binding; + } - } + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - interpolants[ i ].resultBuffer = binding.buffer; + } - } + return new this.constructor().copy( this ); + */ - }, + return new Geometry().copy( this ); - _activateAction: function( action ) { + }, - if ( ! this._isActiveAction( action ) ) { + copy: function ( source ) { - if ( action._cacheIndex === null ) { + this.vertices = []; + this.faces = []; + this.faceVertexUvs = [ [] ]; - // this action has been forgotten by the cache, but the user - // appears to be still using it -> rebind + var vertices = source.vertices; - var rootUuid = ( action._localRoot || this._root ).uuid, - clipUuid = action._clip.uuid, - actionsForClip = this._actionsByClip[ clipUuid ]; + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - this._bindAction( action, - actionsForClip && actionsForClip.knownActions[ 0 ] ); + this.vertices.push( vertices[ i ].clone() ); - this._addInactiveAction( action, clipUuid, rootUuid ); + } - } + var faces = source.faces; - var bindings = action._propertyBindings; + for ( var i = 0, il = faces.length; i < il; i ++ ) { - // increment reference counts / sort out state - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + this.faces.push( faces[ i ].clone() ); - var binding = bindings[ i ]; + } - if ( binding.useCount ++ === 0 ) { + for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { - this._lendBinding( binding ); - binding.saveOriginalState(); + var faceVertexUvs = source.faceVertexUvs[ i ]; - } + if ( this.faceVertexUvs[ i ] === undefined ) { - } + this.faceVertexUvs[ i ] = []; - this._lendAction( action ); + } - } + for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { - }, + var uvs = faceVertexUvs[ j ], uvsCopy = []; - _deactivateAction: function( action ) { + for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { - if ( this._isActiveAction( action ) ) { + var uv = uvs[ k ]; - var bindings = action._propertyBindings; + uvsCopy.push( uv.clone() ); - // decrement reference counts / sort out state - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + } - var binding = bindings[ i ]; + this.faceVertexUvs[ i ].push( uvsCopy ); - if ( -- binding.useCount === 0 ) { + } - binding.restoreOriginalState(); - this._takeBackBinding( binding ); + } - } + return this; - } + }, - this._takeBackAction( action ); + dispose: function () { - } + this.dispatchEvent( { type: 'dispose' } ); - }, + } - // Memory manager + } ); - _initMemoryManager: function() { + var count$2 = 0; + function GeometryIdCount () { return count$2++; }; - this._actions = []; // 'nActiveActions' followed by inactive ones - this._nActiveActions = 0; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this._actionsByClip = {}; - // inside: - // { - // knownActions: Array< _Action > - used as prototypes - // actionByRoot: _Action - lookup - // } + function DirectGeometry () { + this.isDirectGeometry = true; + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - this._bindings = []; // 'nActiveBindings' followed by inactive ones - this._nActiveBindings = 0; + this.uuid = exports.Math.generateUUID(); - this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > + this.name = ''; + this.type = 'DirectGeometry'; + this.indices = []; + this.vertices = []; + this.normals = []; + this.colors = []; + this.uvs = []; + this.uvs2 = []; - this._controlInterpolants = []; // same game as above - this._nActiveControlInterpolants = 0; + this.groups = []; - var scope = this; + this.morphTargets = {}; - this.stats = { + this.skinWeights = []; + this.skinIndices = []; - actions: { - get total() { return scope._actions.length; }, - get inUse() { return scope._nActiveActions; } - }, - bindings: { - get total() { return scope._bindings.length; }, - get inUse() { return scope._nActiveBindings; } - }, - controlInterpolants: { - get total() { return scope._controlInterpolants.length; }, - get inUse() { return scope._nActiveControlInterpolants; } - } + // this.lineDistances = []; - }; + this.boundingBox = null; + this.boundingSphere = null; - }, + // update flags - // Memory management for _Action objects + this.verticesNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.uvsNeedUpdate = false; + this.groupsNeedUpdate = false; - _isActiveAction: function( action ) { + }; - var index = action._cacheIndex; - return index !== null && index < this._nActiveActions; + Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, { - }, + computeBoundingBox: Geometry.prototype.computeBoundingBox, + computeBoundingSphere: Geometry.prototype.computeBoundingSphere, - _addInactiveAction: function( action, clipUuid, rootUuid ) { + computeFaceNormals: function () { - var actions = this._actions, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ]; + console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' ); - if ( actionsForClip === undefined ) { + }, - actionsForClip = { + computeVertexNormals: function () { - knownActions: [ action ], - actionByRoot: {} + console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' ); - }; + }, - action._byClipCacheIndex = 0; + computeGroups: function ( geometry ) { - actionsByClip[ clipUuid ] = actionsForClip; + var group; + var groups = []; + var materialIndex; - } else { + var faces = geometry.faces; - var knownActions = actionsForClip.knownActions; + for ( var i = 0; i < faces.length; i ++ ) { - action._byClipCacheIndex = knownActions.length; - knownActions.push( action ); + var face = faces[ i ]; - } + // materials - action._cacheIndex = actions.length; - actions.push( action ); + if ( face.materialIndex !== materialIndex ) { - actionsForClip.actionByRoot[ rootUuid ] = action; + materialIndex = face.materialIndex; - }, + if ( group !== undefined ) { - _removeInactiveAction: function( action ) { + group.count = ( i * 3 ) - group.start; + groups.push( group ); - var actions = this._actions, - lastInactiveAction = actions[ actions.length - 1 ], - cacheIndex = action._cacheIndex; + } - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + group = { + start: i * 3, + materialIndex: materialIndex + }; - action._cacheIndex = null; + } + } - var clipUuid = action._clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ], - knownActionsForClip = actionsForClip.knownActions, + if ( group !== undefined ) { - lastKnownAction = - knownActionsForClip[ knownActionsForClip.length - 1 ], + group.count = ( i * 3 ) - group.start; + groups.push( group ); - byClipCacheIndex = action._byClipCacheIndex; + } - lastKnownAction._byClipCacheIndex = byClipCacheIndex; - knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; - knownActionsForClip.pop(); + this.groups = groups; - action._byClipCacheIndex = null; + }, + fromGeometry: function ( geometry ) { - var actionByRoot = actionsForClip.actionByRoot, - rootUuid = ( actions._localRoot || this._root ).uuid; + var faces = geometry.faces; + var vertices = geometry.vertices; + var faceVertexUvs = geometry.faceVertexUvs; - delete actionByRoot[ rootUuid ]; + var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; + var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; - if ( knownActionsForClip.length === 0 ) { + // morphs - delete actionsByClip[ clipUuid ]; + var morphTargets = geometry.morphTargets; + var morphTargetsLength = morphTargets.length; - } + var morphTargetsPosition; - this._removeInactiveBindingsForAction( action ); + if ( morphTargetsLength > 0 ) { - }, + morphTargetsPosition = []; - _removeInactiveBindingsForAction: function( action ) { + for ( var i = 0; i < morphTargetsLength; i ++ ) { - var bindings = action._propertyBindings; - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + morphTargetsPosition[ i ] = []; - var binding = bindings[ i ]; + } - if ( -- binding.referenceCount === 0 ) { + this.morphTargets.position = morphTargetsPosition; - this._removeInactiveBinding( binding ); + } - } + var morphNormals = geometry.morphNormals; + var morphNormalsLength = morphNormals.length; - } + var morphTargetsNormal; - }, + if ( morphNormalsLength > 0 ) { - _lendAction: function( action ) { + morphTargetsNormal = []; - // [ active actions | inactive actions ] - // [ active actions >| inactive actions ] - // s a - // <-swap-> - // a s + for ( var i = 0; i < morphNormalsLength; i ++ ) { - var actions = this._actions, - prevIndex = action._cacheIndex, + morphTargetsNormal[ i ] = []; - lastActiveIndex = this._nActiveActions ++, + } - firstInactiveAction = actions[ lastActiveIndex ]; + this.morphTargets.normal = morphTargetsNormal; - action._cacheIndex = lastActiveIndex; - actions[ lastActiveIndex ] = action; + } - firstInactiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = firstInactiveAction; + // skins - }, + var skinIndices = geometry.skinIndices; + var skinWeights = geometry.skinWeights; - _takeBackAction: function( action ) { + var hasSkinIndices = skinIndices.length === vertices.length; + var hasSkinWeights = skinWeights.length === vertices.length; - // [ active actions | inactive actions ] - // [ active actions |< inactive actions ] - // a s - // <-swap-> - // s a + // - var actions = this._actions, - prevIndex = action._cacheIndex, + for ( var i = 0; i < faces.length; i ++ ) { - firstInactiveIndex = -- this._nActiveActions, + var face = faces[ i ]; - lastActiveAction = actions[ firstInactiveIndex ]; + this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); - action._cacheIndex = firstInactiveIndex; - actions[ firstInactiveIndex ] = action; + var vertexNormals = face.vertexNormals; - lastActiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = lastActiveAction; + if ( vertexNormals.length === 3 ) { - }, + this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); - // Memory management for PropertyMixer objects + } else { - _addInactiveBinding: function( binding, rootUuid, trackName ) { + var normal = face.normal; - var bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ], + this.normals.push( normal, normal, normal ); - bindings = this._bindings; + } - if ( bindingByName === undefined ) { + var vertexColors = face.vertexColors; - bindingByName = {}; - bindingsByRoot[ rootUuid ] = bindingByName; + if ( vertexColors.length === 3 ) { - } + this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); - bindingByName[ trackName ] = binding; + } else { - binding._cacheIndex = bindings.length; - bindings.push( binding ); + var color = face.color; - }, + this.colors.push( color, color, color ); - _removeInactiveBinding: function( binding ) { + } - var bindings = this._bindings, - propBinding = binding.binding, - rootUuid = propBinding.rootNode.uuid, - trackName = propBinding.path, - bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ], + if ( hasFaceVertexUv === true ) { - lastInactiveBinding = bindings[ bindings.length - 1 ], - cacheIndex = binding._cacheIndex; + var vertexUvs = faceVertexUvs[ 0 ][ i ]; - lastInactiveBinding._cacheIndex = cacheIndex; - bindings[ cacheIndex ] = lastInactiveBinding; - bindings.pop(); + if ( vertexUvs !== undefined ) { - delete bindingByName[ trackName ]; + this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - remove_empty_map: { + } else { - for ( var _ in bindingByName ) break remove_empty_map; + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); - delete bindingsByRoot[ rootUuid ]; + this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); - } + } - }, + } - _lendBinding: function( binding ) { + if ( hasFaceVertexUv2 === true ) { - var bindings = this._bindings, - prevIndex = binding._cacheIndex, + var vertexUvs = faceVertexUvs[ 1 ][ i ]; - lastActiveIndex = this._nActiveBindings ++, + if ( vertexUvs !== undefined ) { - firstInactiveBinding = bindings[ lastActiveIndex ]; + this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - binding._cacheIndex = lastActiveIndex; - bindings[ lastActiveIndex ] = binding; + } else { - firstInactiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = firstInactiveBinding; + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); - }, + this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); - _takeBackBinding: function( binding ) { + } - var bindings = this._bindings, - prevIndex = binding._cacheIndex, + } - firstInactiveIndex = -- this._nActiveBindings, + // morphs - lastActiveBinding = bindings[ firstInactiveIndex ]; + for ( var j = 0; j < morphTargetsLength; j ++ ) { - binding._cacheIndex = firstInactiveIndex; - bindings[ firstInactiveIndex ] = binding; + var morphTarget = morphTargets[ j ].vertices; - lastActiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = lastActiveBinding; + morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); - }, + } + for ( var j = 0; j < morphNormalsLength; j ++ ) { - // Memory management of Interpolants for weight and time scale + var morphNormal = morphNormals[ j ].vertexNormals[ i ]; - _lendControlInterpolant: function() { + morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); - var interpolants = this._controlInterpolants, - lastActiveIndex = this._nActiveControlInterpolants ++, - interpolant = interpolants[ lastActiveIndex ]; + } - if ( interpolant === undefined ) { + // skins - interpolant = new THREE.LinearInterpolant( - new Float32Array( 2 ), new Float32Array( 2 ), - 1, this._controlInterpolantsResultBuffer ); + if ( hasSkinIndices ) { - interpolant.__cacheIndex = lastActiveIndex; - interpolants[ lastActiveIndex ] = interpolant; + this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); - } + } - return interpolant; + if ( hasSkinWeights ) { - }, + this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); - _takeBackControlInterpolant: function( interpolant ) { + } - var interpolants = this._controlInterpolants, - prevIndex = interpolant.__cacheIndex, + } - firstInactiveIndex = -- this._nActiveControlInterpolants, + this.computeGroups( geometry ); - lastActiveInterpolant = interpolants[ firstInactiveIndex ]; + this.verticesNeedUpdate = geometry.verticesNeedUpdate; + this.normalsNeedUpdate = geometry.normalsNeedUpdate; + this.colorsNeedUpdate = geometry.colorsNeedUpdate; + this.uvsNeedUpdate = geometry.uvsNeedUpdate; + this.groupsNeedUpdate = geometry.groupsNeedUpdate; - interpolant.__cacheIndex = firstInactiveIndex; - interpolants[ firstInactiveIndex ] = interpolant; + return this; - lastActiveInterpolant.__cacheIndex = prevIndex; - interpolants[ prevIndex ] = lastActiveInterpolant; + }, - }, + dispose: function () { - _controlInterpolantsResultBuffer: new Float32Array( 1 ) + this.dispatchEvent( { type: 'dispose' } ); -} ); + } -// File:src/animation/AnimationObjectGroup.js + } ); -/** - * - * A group of objects that receives a shared animation state. - * - * Usage: - * - * - Add objects you would otherwise pass as 'root' to the - * constructor or the .clipAction method of AnimationMixer. - * - * - Instead pass this object as 'root'. - * - * - You can also add and remove objects later when the mixer - * is running. - * - * Note: - * - * Objects of this class appear as one object to the mixer, - * so cache control of the individual objects must be done - * on the group. - * - * Limitation: - * - * - The animated properties must be compatible among the - * all objects in the group. - * - * - A single property can either be controlled through a - * target group or directly, but not both. - * - * @author tschw - */ + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ -THREE.AnimationObjectGroup = function( var_args ) { + function BufferGeometry () { + this.isBufferGeometry = true; - this.uuid = THREE.Math.generateUUID(); + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - // cached objects followed by the active ones - this._objects = Array.prototype.slice.call( arguments ); + this.uuid = exports.Math.generateUUID(); - this.nCachedObjects_ = 0; // threshold - // note: read by PropertyBinding.Composite + this.name = ''; + this.type = 'BufferGeometry'; - var indices = {}; - this._indicesByUUID = indices; // for bookkeeping + this.index = null; + this.attributes = {}; - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + this.morphAttributes = {}; - indices[ arguments[ i ].uuid ] = i; + this.groups = []; - } + this.boundingBox = null; + this.boundingSphere = null; - this._paths = []; // inside: string - this._parsedPaths = []; // inside: { we don't care, here } - this._bindings = []; // inside: Array< PropertyBinding > - this._bindingsIndicesByPath = {}; // inside: indices in these arrays + this.drawRange = { start: 0, count: Infinity }; - var scope = this; + }; - this.stats = { + Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, { - objects: { - get total() { return scope._objects.length; }, - get inUse() { return this.total - scope.nCachedObjects_; } - }, + getIndex: function () { - get bindingsPerObject() { return scope._bindings.length; } + return this.index; - }; + }, -}; + setIndex: function ( index ) { -THREE.AnimationObjectGroup.prototype = { + this.index = index; - constructor: THREE.AnimationObjectGroup, + }, - add: function( var_args ) { + addAttribute: function ( name, attribute ) { - var objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - nBindings = bindings.length; + if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) { - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); - if ( index === undefined ) { + return; - // unknown object -> add it to the ACTIVE region + } - index = nObjects ++; - indicesByUUID[ uuid ] = index; - objects.push( object ); + if ( name === 'index' ) { - // accounting is done, now do the same for all bindings + console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); + this.setIndex( attribute ); - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + return; - bindings[ j ].push( - new THREE.PropertyBinding( - object, paths[ j ], parsedPaths[ j ] ) ); + } - } + this.attributes[ name ] = attribute; - } else if ( index < nCachedObjects ) { + return this; - var knownObject = objects[ index ]; + }, - // move existing object to the ACTIVE region + getAttribute: function ( name ) { - var firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ]; + return this.attributes[ name ]; - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + }, - indicesByUUID[ uuid ] = firstActiveIndex; - objects[ firstActiveIndex ] = object; + removeAttribute: function ( name ) { - // accounting is done, now do the same for all bindings + delete this.attributes[ name ]; - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + return this; - var bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ], - binding = bindingsForPath[ index ]; + }, - bindingsForPath[ index ] = lastCached; + addGroup: function ( start, count, materialIndex ) { - if ( binding === undefined ) { + this.groups.push( { - // since we do not bother to create new bindings - // for objects that are cached, the binding may - // or may not exist + start: start, + count: count, + materialIndex: materialIndex !== undefined ? materialIndex : 0 - binding = new THREE.PropertyBinding( - object, paths[ j ], parsedPaths[ j ] ); + } ); - } + }, - bindingsForPath[ firstActiveIndex ] = binding; + clearGroups: function () { - } + this.groups = []; - } else if ( objects[ index ] !== knownObject) { + }, - console.error( "Different objects with the same UUID " + - "detected. Clean the caches or recreate your " + - "infrastructure when reloading scenes..." ); + setDrawRange: function ( start, count ) { - } // else the object is already where we want it to be + this.drawRange.start = start; + this.drawRange.count = count; - } // for arguments + }, - this.nCachedObjects_ = nCachedObjects; + applyMatrix: function ( matrix ) { - }, + var position = this.attributes.position; - remove: function( var_args ) { + if ( position !== undefined ) { - var objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + matrix.applyToVector3Array( position.array ); + position.needsUpdate = true; - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + } - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + var normal = this.attributes.normal; - if ( index !== undefined && index >= nCachedObjects ) { + if ( normal !== undefined ) { - // move existing object into the CACHED region + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - var lastCachedIndex = nCachedObjects ++, - firstActiveObject = objects[ lastCachedIndex ]; + normalMatrix.applyToVector3Array( normal.array ); + normal.needsUpdate = true; - indicesByUUID[ firstActiveObject.uuid ] = index; - objects[ index ] = firstActiveObject; + } - indicesByUUID[ uuid ] = lastCachedIndex; - objects[ lastCachedIndex ] = object; + if ( this.boundingBox !== null ) { - // accounting is done, now do the same for all bindings + this.computeBoundingBox(); - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + } - var bindingsForPath = bindings[ j ], - firstActive = bindingsForPath[ lastCachedIndex ], - binding = bindingsForPath[ index ]; + if ( this.boundingSphere !== null ) { - bindingsForPath[ index ] = firstActive; - bindingsForPath[ lastCachedIndex ] = binding; + this.computeBoundingSphere(); - } + } - } + return this; - } // for arguments + }, - this.nCachedObjects_ = nCachedObjects; + rotateX: function () { - }, + // rotate geometry around world x-axis - // remove & forget - uncache: function( var_args ) { + var m1; - var objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + return function rotateX( angle ) { - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + if ( m1 === undefined ) m1 = new Matrix4(); - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + m1.makeRotationX( angle ); - if ( index !== undefined ) { + this.applyMatrix( m1 ); - delete indicesByUUID[ uuid ]; + return this; - if ( index < nCachedObjects ) { + }; - // object is cached, shrink the CACHED region + }(), - var firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ], - lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + rotateY: function () { - // last cached object takes this object's place - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + // rotate geometry around world y-axis - // last object goes to the activated slot and pop - indicesByUUID[ lastObject.uuid ] = firstActiveIndex; - objects[ firstActiveIndex ] = lastObject; - objects.pop(); + var m1; - // accounting is done, now do the same for all bindings + return function rotateY( angle ) { - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + if ( m1 === undefined ) m1 = new Matrix4(); - var bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ], - last = bindingsForPath[ lastIndex ]; + m1.makeRotationY( angle ); - bindingsForPath[ index ] = lastCached; - bindingsForPath[ firstActiveIndex ] = last; - bindingsForPath.pop(); + this.applyMatrix( m1 ); - } + return this; - } else { + }; - // object is active, just swap with the last and pop + }(), - var lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + rotateZ: function () { - indicesByUUID[ lastObject.uuid ] = index; - objects[ index ] = lastObject; - objects.pop(); + // rotate geometry around world z-axis - // accounting is done, now do the same for all bindings + var m1; - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + return function rotateZ( angle ) { - var bindingsForPath = bindings[ j ]; + if ( m1 === undefined ) m1 = new Matrix4(); - bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; - bindingsForPath.pop(); + m1.makeRotationZ( angle ); - } + this.applyMatrix( m1 ); - } // cached or active + return this; - } // if object is known + }; - } // for arguments + }(), - this.nCachedObjects_ = nCachedObjects; + translate: function () { - }, + // translate geometry - // Internal interface used by befriended PropertyBinding.Composite: + var m1; - subscribe_: function( path, parsedPath ) { - // returns an array of bindings for the given path that is changed - // according to the contained objects in the group + return function translate( x, y, z ) { - var indicesByPath = this._bindingsIndicesByPath, - index = indicesByPath[ path ], - bindings = this._bindings; + if ( m1 === undefined ) m1 = new Matrix4(); - if ( index !== undefined ) return bindings[ index ]; + m1.makeTranslation( x, y, z ); - var paths = this._paths, - parsedPaths = this._parsedPaths, - objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - bindingsForPath = new Array( nObjects ); + this.applyMatrix( m1 ); - index = bindings.length; + return this; - indicesByPath[ path ] = index; + }; - paths.push( path ); - parsedPaths.push( parsedPath ); - bindings.push( bindingsForPath ); + }(), - for ( var i = nCachedObjects, - n = objects.length; i !== n; ++ i ) { + scale: function () { - var object = objects[ i ]; + // scale geometry - bindingsForPath[ i ] = - new THREE.PropertyBinding( object, path, parsedPath ); + var m1; - } + return function scale( x, y, z ) { - return bindingsForPath; + if ( m1 === undefined ) m1 = new Matrix4(); - }, + m1.makeScale( x, y, z ); - unsubscribe_: function( path ) { - // tells the group to forget about a property path and no longer - // update the array previously obtained with 'subscribe_' + this.applyMatrix( m1 ); - var indicesByPath = this._bindingsIndicesByPath, - index = indicesByPath[ path ]; + return this; - if ( index !== undefined ) { + }; - var paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - lastBindingsIndex = bindings.length - 1, - lastBindings = bindings[ lastBindingsIndex ], - lastBindingsPath = path[ lastBindingsIndex ]; + }(), - indicesByPath[ lastBindingsPath ] = index; + lookAt: function () { - bindings[ index ] = lastBindings; - bindings.pop(); + var obj; - parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; - parsedPaths.pop(); + return function lookAt( vector ) { - paths[ index ] = paths[ lastBindingsIndex ]; - paths.pop(); + if ( obj === undefined ) obj = new Object3D(); - } + obj.lookAt( vector ); - } + obj.updateMatrix(); -}; + this.applyMatrix( obj.matrix ); + }; -// File:src/animation/AnimationUtils.js + }(), -/** - * @author tschw - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + center: function () { -THREE.AnimationUtils = { + this.computeBoundingBox(); - // same as Array.prototype.slice, but also works on typed arrays - arraySlice: function( array, from, to ) { + var offset = this.boundingBox.center().negate(); - if ( THREE.AnimationUtils.isTypedArray( array ) ) { + this.translate( offset.x, offset.y, offset.z ); - return new array.constructor( array.subarray( from, to ) ); + return offset; - } + }, - return array.slice( from, to ); + setFromObject: function ( object ) { - }, + // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); - // converts an array to a specific type - convertArray: function( array, type, forceClone ) { + var geometry = object.geometry; - if ( ! array || // let 'undefined' and 'null' pass - ! forceClone && array.constructor === type ) return array; + if ( (object && object.isPoints) || (object && object.isLine) ) { - if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + var positions = new Float32Attribute( geometry.vertices.length * 3, 3 ); + var colors = new Float32Attribute( geometry.colors.length * 3, 3 ); - return new type( array ); // create typed array + this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); + this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); - } + if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { - return Array.prototype.slice.call( array ); // create Array + var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 ); - }, + this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); - isTypedArray: function( object ) { + } - return ArrayBuffer.isView( object ) && - ! ( object instanceof DataView ); + if ( geometry.boundingSphere !== null ) { - }, + this.boundingSphere = geometry.boundingSphere.clone(); - // returns an array by which times and values can be sorted - getKeyframeOrder: function( times ) { + } - function compareTime( i, j ) { + if ( geometry.boundingBox !== null ) { - return times[ i ] - times[ j ]; + this.boundingBox = geometry.boundingBox.clone(); - } + } - var n = times.length; - var result = new Array( n ); - for ( var i = 0; i !== n; ++ i ) result[ i ] = i; + } else if ( (object && object.isMesh) ) { - result.sort( compareTime ); + if ( (geometry && geometry.isGeometry) ) { - return result; + this.fromGeometry( geometry ); - }, + } - // uses the array previously returned by 'getKeyframeOrder' to sort data - sortedArray: function( values, stride, order ) { + } - var nValues = values.length; - var result = new values.constructor( nValues ); + return this; - for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { + }, - var srcOffset = order[ i ] * stride; + updateFromObject: function ( object ) { - for ( var j = 0; j !== stride; ++ j ) { + var geometry = object.geometry; - result[ dstOffset ++ ] = values[ srcOffset + j ]; + if ( (object && object.isMesh) ) { - } + var direct = geometry.__directGeometry; - } + if ( direct === undefined || geometry.elementsNeedUpdate === true ) { - return result; + return this.fromGeometry( geometry ); - }, + } - // function for parsing AOS keyframe formats - flattenJSON: function( jsonKeys, times, values, valuePropertyName ) { + direct.verticesNeedUpdate = geometry.verticesNeedUpdate || geometry.elementsNeedUpdate; + direct.normalsNeedUpdate = geometry.normalsNeedUpdate || geometry.elementsNeedUpdate; + direct.colorsNeedUpdate = geometry.colorsNeedUpdate || geometry.elementsNeedUpdate; + direct.uvsNeedUpdate = geometry.uvsNeedUpdate || geometry.elementsNeedUpdate; + direct.groupsNeedUpdate = geometry.groupsNeedUpdate || geometry.elementsNeedUpdate; - var i = 1, key = jsonKeys[ 0 ]; + geometry.elementsNeedUpdate = false; + geometry.verticesNeedUpdate = false; + geometry.normalsNeedUpdate = false; + geometry.colorsNeedUpdate = false; + geometry.uvsNeedUpdate = false; + geometry.groupsNeedUpdate = false; - while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + geometry = direct; - key = jsonKeys[ i ++ ]; + } - } + var attribute; - if ( key === undefined ) return; // no data + if ( geometry.verticesNeedUpdate === true ) { - var value = key[ valuePropertyName ]; - if ( value === undefined ) return; // no data + attribute = this.attributes.position; - if ( Array.isArray( value ) ) { + if ( attribute !== undefined ) { - do { + attribute.copyVector3sArray( geometry.vertices ); + attribute.needsUpdate = true; - value = key[ valuePropertyName ]; + } - if ( value !== undefined ) { + geometry.verticesNeedUpdate = false; - times.push( key.time ); - values.push.apply( values, value ); // push all elements + } - } + if ( geometry.normalsNeedUpdate === true ) { - key = jsonKeys[ i ++ ]; + attribute = this.attributes.normal; - } while ( key !== undefined ); + if ( attribute !== undefined ) { - } else if ( value.toArray !== undefined ) { - // ...assume THREE.Math-ish + attribute.copyVector3sArray( geometry.normals ); + attribute.needsUpdate = true; - do { + } - value = key[ valuePropertyName ]; + geometry.normalsNeedUpdate = false; - if ( value !== undefined ) { + } - times.push( key.time ); - value.toArray( values, values.length ); + if ( geometry.colorsNeedUpdate === true ) { - } + attribute = this.attributes.color; - key = jsonKeys[ i ++ ]; + if ( attribute !== undefined ) { - } while ( key !== undefined ); + attribute.copyColorsArray( geometry.colors ); + attribute.needsUpdate = true; - } else { - // otherwise push as-is + } - do { + geometry.colorsNeedUpdate = false; - value = key[ valuePropertyName ]; + } - if ( value !== undefined ) { + if ( geometry.uvsNeedUpdate ) { - times.push( key.time ); - values.push( value ); + attribute = this.attributes.uv; - } + if ( attribute !== undefined ) { - key = jsonKeys[ i ++ ]; + attribute.copyVector2sArray( geometry.uvs ); + attribute.needsUpdate = true; - } while ( key !== undefined ); + } - } + geometry.uvsNeedUpdate = false; - } + } -}; + if ( geometry.lineDistancesNeedUpdate ) { -// File:src/animation/KeyframeTrack.js + attribute = this.attributes.lineDistance; -/** - * - * A timed sequence of keyframes for a specific property. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + if ( attribute !== undefined ) { -THREE.KeyframeTrack = function ( name, times, values, interpolation ) { + attribute.copyArray( geometry.lineDistances ); + attribute.needsUpdate = true; - if( name === undefined ) throw new Error( "track name is undefined" ); + } - if( times === undefined || times.length === 0 ) { + geometry.lineDistancesNeedUpdate = false; - throw new Error( "no keyframes in track named " + name ); + } - } + if ( geometry.groupsNeedUpdate ) { - this.name = name; + geometry.computeGroups( object.geometry ); + this.groups = geometry.groups; - this.times = THREE.AnimationUtils.convertArray( times, this.TimeBufferType ); - this.values = THREE.AnimationUtils.convertArray( values, this.ValueBufferType ); + geometry.groupsNeedUpdate = false; - this.setInterpolation( interpolation || this.DefaultInterpolation ); + } - this.validate(); - this.optimize(); + return this; -}; + }, -THREE.KeyframeTrack.prototype = { + fromGeometry: function ( geometry ) { - constructor: THREE.KeyframeTrack, + geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); - TimeBufferType: Float32Array, - ValueBufferType: Float32Array, + return this.fromDirectGeometry( geometry.__directGeometry ); - DefaultInterpolation: THREE.InterpolateLinear, + }, - InterpolantFactoryMethodDiscrete: function( result ) { + fromDirectGeometry: function ( geometry ) { - return new THREE.DiscreteInterpolant( - this.times, this.values, this.getValueSize(), result ); + var positions = new Float32Array( geometry.vertices.length * 3 ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); - }, + if ( geometry.normals.length > 0 ) { - InterpolantFactoryMethodLinear: function( result ) { + var normals = new Float32Array( geometry.normals.length * 3 ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); - return new THREE.LinearInterpolant( - this.times, this.values, this.getValueSize(), result ); + } - }, + if ( geometry.colors.length > 0 ) { - InterpolantFactoryMethodSmooth: function( result ) { + var colors = new Float32Array( geometry.colors.length * 3 ); + this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); - return new THREE.CubicInterpolant( - this.times, this.values, this.getValueSize(), result ); + } - }, + if ( geometry.uvs.length > 0 ) { - setInterpolation: function( interpolation ) { + var uvs = new Float32Array( geometry.uvs.length * 2 ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); - var factoryMethod; + } - switch ( interpolation ) { + if ( geometry.uvs2.length > 0 ) { - case THREE.InterpolateDiscrete: + var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); + this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); - factoryMethod = this.InterpolantFactoryMethodDiscrete; + } - break; + if ( geometry.indices.length > 0 ) { - case THREE.InterpolateLinear: + var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array; + var indices = new TypeArray( geometry.indices.length * 3 ); + this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); - factoryMethod = this.InterpolantFactoryMethodLinear; + } - break; + // groups - case THREE.InterpolateSmooth: + this.groups = geometry.groups; - factoryMethod = this.InterpolantFactoryMethodSmooth; + // morphs - break; + for ( var name in geometry.morphTargets ) { - } + var array = []; + var morphTargets = geometry.morphTargets[ name ]; - if ( factoryMethod === undefined ) { + for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { - var message = "unsupported interpolation for " + - this.ValueTypeName + " keyframe track named " + this.name; + var morphTarget = morphTargets[ i ]; - if ( this.createInterpolant === undefined ) { + var attribute = new Float32Attribute( morphTarget.length * 3, 3 ); - // fall back to default, unless the default itself is messed up - if ( interpolation !== this.DefaultInterpolation ) { + array.push( attribute.copyVector3sArray( morphTarget ) ); - this.setInterpolation( this.DefaultInterpolation ); + } - } else { + this.morphAttributes[ name ] = array; - throw new Error( message ); // fatal, in this case + } - } + // skinning - } + if ( geometry.skinIndices.length > 0 ) { - console.warn( message ); - return; + var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 ); + this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); - } + } - this.createInterpolant = factoryMethod; + if ( geometry.skinWeights.length > 0 ) { - }, + var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 ); + this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); - getInterpolation: function() { + } - switch ( this.createInterpolant ) { + // - case this.InterpolantFactoryMethodDiscrete: + if ( geometry.boundingSphere !== null ) { - return THREE.InterpolateDiscrete; + this.boundingSphere = geometry.boundingSphere.clone(); - case this.InterpolantFactoryMethodLinear: + } - return THREE.InterpolateLinear; + if ( geometry.boundingBox !== null ) { - case this.InterpolantFactoryMethodSmooth: + this.boundingBox = geometry.boundingBox.clone(); - return THREE.InterpolateSmooth; + } - } + return this; - }, + }, - getValueSize: function() { + computeBoundingBox: function () { - return this.values.length / this.times.length; + if ( this.boundingBox === null ) { - }, + this.boundingBox = new Box3(); - // move all keyframes either forwards or backwards in time - shift: function( timeOffset ) { + } - if( timeOffset !== 0.0 ) { + var positions = this.attributes.position.array; - var times = this.times; + if ( positions !== undefined ) { - for( var i = 0, n = times.length; i !== n; ++ i ) { + this.boundingBox.setFromArray( positions ); - times[ i ] += timeOffset; + } else { - } + this.boundingBox.makeEmpty(); - } + } - return this; + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { - }, + console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); - // scale all keyframe times by a factor (useful for frame <-> seconds conversions) - scale: function( timeScale ) { + } - if( timeScale !== 1.0 ) { + }, - var times = this.times; + computeBoundingSphere: function () { - for( var i = 0, n = times.length; i !== n; ++ i ) { + var box = new Box3(); + var vector = new Vector3(); - times[ i ] *= timeScale; + return function computeBoundingSphere() { - } + if ( this.boundingSphere === null ) { - } + this.boundingSphere = new Sphere(); - return this; + } - }, + var positions = this.attributes.position; - // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. - // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values - trim: function( startTime, endTime ) { + if ( positions ) { - var times = this.times, - nKeys = times.length, - from = 0, - to = nKeys - 1; + var array = positions.array; + var center = this.boundingSphere.center; - while ( from !== nKeys && times[ from ] < startTime ) ++ from; - while ( to !== -1 && times[ to ] > endTime ) -- to; + box.setFromArray( array ); + box.center( center ); - ++ to; // inclusive -> exclusive bound + // hoping to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case - if( from !== 0 || to !== nKeys ) { + var maxRadiusSq = 0; - // empty tracks are forbidden, so keep at least one keyframe - if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; + for ( var i = 0, il = array.length; i < il; i += 3 ) { - var stride = this.getValueSize(); - this.times = THREE.AnimationUtils.arraySlice( times, from, to ); - this.values = THREE.AnimationUtils. - arraySlice( this.values, from * stride, to * stride ); + vector.fromArray( array, i ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); - } + } - return this; + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); - }, + if ( isNaN( this.boundingSphere.radius ) ) { - // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable - validate: function() { + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); - var valid = true; + } - var valueSize = this.getValueSize(); - if ( valueSize - Math.floor( valueSize ) !== 0 ) { + } - console.error( "invalid value size in track", this ); - valid = false; + }; - } + }(), - var times = this.times, - values = this.values, + computeFaceNormals: function () { - nKeys = times.length; + // backwards compatibility - if( nKeys === 0 ) { + }, - console.error( "track is empty", this ); - valid = false; + computeVertexNormals: function () { - } + var index = this.index; + var attributes = this.attributes; + var groups = this.groups; - var prevTime = null; + if ( attributes.position ) { - for( var i = 0; i !== nKeys; i ++ ) { + var positions = attributes.position.array; - var currTime = times[ i ]; + if ( attributes.normal === undefined ) { - if ( typeof currTime === 'number' && isNaN( currTime ) ) { + this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); - console.error( "time is not a valid number", this, i, currTime ); - valid = false; - break; + } else { - } + // reset existing normals to zero - if( prevTime !== null && prevTime > currTime ) { + var array = attributes.normal.array; - console.error( "out of order keys", this, i, currTime, prevTime ); - valid = false; - break; + for ( var i = 0, il = array.length; i < il; i ++ ) { - } + array[ i ] = 0; - prevTime = currTime; + } - } + } - if ( values !== undefined ) { + var normals = attributes.normal.array; - if ( THREE.AnimationUtils.isTypedArray( values ) ) { + var vA, vB, vC, - for ( var i = 0, n = values.length; i !== n; ++ i ) { + pA = new Vector3(), + pB = new Vector3(), + pC = new Vector3(), - var value = values[ i ]; + cb = new Vector3(), + ab = new Vector3(); - if ( isNaN( value ) ) { + // indexed elements - console.error( "value is not a valid number", this, i, value ); - valid = false; - break; + if ( index ) { - } + var indices = index.array; - } + if ( groups.length === 0 ) { - } + this.addGroup( 0, indices.length ); - } + } - return valid; + for ( var j = 0, jl = groups.length; j < jl; ++ j ) { - }, + var group = groups[ j ]; - // removes equivalent sequential keys as common in morph target sequences - // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) - optimize: function() { + var start = group.start; + var count = group.count; - var times = this.times, - values = this.values, - stride = this.getValueSize(), + for ( var i = start, il = start + count; i < il; i += 3 ) { - writeIndex = 1; + vA = indices[ i + 0 ] * 3; + vB = indices[ i + 1 ] * 3; + vC = indices[ i + 2 ] * 3; - for( var i = 1, n = times.length - 1; i <= n; ++ i ) { + pA.fromArray( positions, vA ); + pB.fromArray( positions, vB ); + pC.fromArray( positions, vC ); - var keep = false; + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - var time = times[ i ]; - var timeNext = times[ i + 1 ]; + normals[ vA ] += cb.x; + normals[ vA + 1 ] += cb.y; + normals[ vA + 2 ] += cb.z; - // remove adjacent keyframes scheduled at the same time + normals[ vB ] += cb.x; + normals[ vB + 1 ] += cb.y; + normals[ vB + 2 ] += cb.z; - if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { + normals[ vC ] += cb.x; + normals[ vC + 1 ] += cb.y; + normals[ vC + 2 ] += cb.z; - // remove unnecessary keyframes same as their neighbors - var offset = i * stride, - offsetP = offset - stride, - offsetN = offset + stride; + } - for ( var j = 0; j !== stride; ++ j ) { + } - var value = values[ offset + j ]; + } else { - if ( value !== values[ offsetP + j ] || - value !== values[ offsetN + j ] ) { + // non-indexed elements (unconnected triangle soup) - keep = true; - break; + for ( var i = 0, il = positions.length; i < il; i += 9 ) { - } + pA.fromArray( positions, i ); + pB.fromArray( positions, i + 3 ); + pC.fromArray( positions, i + 6 ); - } + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - } + normals[ i ] = cb.x; + normals[ i + 1 ] = cb.y; + normals[ i + 2 ] = cb.z; - // in-place compaction + normals[ i + 3 ] = cb.x; + normals[ i + 4 ] = cb.y; + normals[ i + 5 ] = cb.z; - if ( keep ) { + normals[ i + 6 ] = cb.x; + normals[ i + 7 ] = cb.y; + normals[ i + 8 ] = cb.z; - if ( i !== writeIndex ) { + } - times[ writeIndex ] = times[ i ]; + } - var readOffset = i * stride, - writeOffset = writeIndex * stride; + this.normalizeNormals(); - for ( var j = 0; j !== stride; ++ j ) { + attributes.normal.needsUpdate = true; - values[ writeOffset + j ] = values[ readOffset + j ]; + } - } + }, + merge: function ( geometry, offset ) { - } + if ( (geometry && geometry.isBufferGeometry) === false ) { - ++ writeIndex; + console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); + return; - } + } - } + if ( offset === undefined ) offset = 0; - if ( writeIndex !== times.length ) { + var attributes = this.attributes; - this.times = THREE.AnimationUtils.arraySlice( times, 0, writeIndex ); - this.values = THREE.AnimationUtils.arraySlice( values, 0, writeIndex * stride ); + for ( var key in attributes ) { - } + if ( geometry.attributes[ key ] === undefined ) continue; - return this; + var attribute1 = attributes[ key ]; + var attributeArray1 = attribute1.array; - } + var attribute2 = geometry.attributes[ key ]; + var attributeArray2 = attribute2.array; -}; + var attributeSize = attribute2.itemSize; -// Static methods: + for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { -Object.assign( THREE.KeyframeTrack, { + attributeArray1[ j ] = attributeArray2[ i ]; - // Serialization (in static context, because of constructor invocation - // and automatic invocation of .toJSON): + } - parse: function( json ) { + } - if( json.type === undefined ) { + return this; - throw new Error( "track type undefined, can not parse" ); + }, - } + normalizeNormals: function () { - var trackType = THREE.KeyframeTrack._getTrackTypeForValueTypeName( json.type ); + var normals = this.attributes.normal.array; - if ( json.times === undefined ) { + var x, y, z, n; - var times = [], values = []; + for ( var i = 0, il = normals.length; i < il; i += 3 ) { - THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); + x = normals[ i ]; + y = normals[ i + 1 ]; + z = normals[ i + 2 ]; - json.times = times; - json.values = values; + n = 1.0 / Math.sqrt( x * x + y * y + z * z ); - } + normals[ i ] *= n; + normals[ i + 1 ] *= n; + normals[ i + 2 ] *= n; - // derived classes can define a static parse method - if ( trackType.parse !== undefined ) { + } - return trackType.parse( json ); + }, - } else { + toNonIndexed: function () { - // by default, we asssume a constructor compatible with the base - return new trackType( - json.name, json.times, json.values, json.interpolation ); + if ( this.index === null ) { - } + console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); + return this; - }, + } - toJSON: function( track ) { + var geometry2 = new BufferGeometry(); - var trackType = track.constructor; + var indices = this.index.array; + var attributes = this.attributes; - var json; + for ( var name in attributes ) { - // derived classes can define a static toJSON method - if ( trackType.toJSON !== undefined ) { + var attribute = attributes[ name ]; - json = trackType.toJSON( track ); + var array = attribute.array; + var itemSize = attribute.itemSize; - } else { + var array2 = new array.constructor( indices.length * itemSize ); - // by default, we assume the data can be serialized as-is - json = { + var index = 0, index2 = 0; - 'name': track.name, - 'times': THREE.AnimationUtils.convertArray( track.times, Array ), - 'values': THREE.AnimationUtils.convertArray( track.values, Array ) + for ( var i = 0, l = indices.length; i < l; i ++ ) { - }; + index = indices[ i ] * itemSize; - var interpolation = track.getInterpolation(); + for ( var j = 0; j < itemSize; j ++ ) { - if ( interpolation !== track.DefaultInterpolation ) { + array2[ index2 ++ ] = array[ index ++ ]; - json.interpolation = interpolation; + } - } + } - } + geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); - json.type = track.ValueTypeName; // mandatory + } - return json; + return geometry2; - }, + }, - _getTrackTypeForValueTypeName: function( typeName ) { + toJSON: function () { - switch( typeName.toLowerCase() ) { + var data = { + metadata: { + version: 4.4, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; - case "scalar": - case "double": - case "float": - case "number": - case "integer": + // standard BufferGeometry serialization - return THREE.NumberKeyframeTrack; + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - case "vector": - case "vector2": - case "vector3": - case "vector4": + if ( this.parameters !== undefined ) { - return THREE.VectorKeyframeTrack; + var parameters = this.parameters; - case "color": + for ( var key in parameters ) { - return THREE.ColorKeyframeTrack; + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - case "quaternion": + } - return THREE.QuaternionKeyframeTrack; + return data; - case "bool": - case "boolean": + } - return THREE.BooleanKeyframeTrack; + data.data = { attributes: {} }; - case "string": + var index = this.index; - return THREE.StringKeyframeTrack; + if ( index !== null ) { - } + var array = Array.prototype.slice.call( index.array ); - throw new Error( "Unsupported typeName: " + typeName ); + data.data.index = { + type: index.array.constructor.name, + array: array + }; - } + } -} ); + var attributes = this.attributes; -// File:src/animation/PropertyBinding.js + for ( var key in attributes ) { -/** - * - * A reference to a real property in the scene graph. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + var attribute = attributes[ key ]; -THREE.PropertyBinding = function ( rootNode, path, parsedPath ) { + var array = Array.prototype.slice.call( attribute.array ); - this.path = path; - this.parsedPath = parsedPath || - THREE.PropertyBinding.parseTrackName( path ); + data.data.attributes[ key ] = { + itemSize: attribute.itemSize, + type: attribute.array.constructor.name, + array: array, + normalized: attribute.normalized + }; - this.node = THREE.PropertyBinding.findNode( - rootNode, this.parsedPath.nodeName ) || rootNode; + } - this.rootNode = rootNode; + var groups = this.groups; -}; + if ( groups.length > 0 ) { -THREE.PropertyBinding.prototype = { + data.data.groups = JSON.parse( JSON.stringify( groups ) ); - constructor: THREE.PropertyBinding, + } - getValue: function getValue_unbound( targetArray, offset ) { + var boundingSphere = this.boundingSphere; - this.bind(); - this.getValue( targetArray, offset ); + if ( boundingSphere !== null ) { - // Note: This class uses a State pattern on a per-method basis: - // 'bind' sets 'this.getValue' / 'setValue' and shadows the - // prototype version of these methods with one that represents - // the bound state. When the property is not found, the methods - // become no-ops. + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; - }, + } - setValue: function getValue_unbound( sourceArray, offset ) { + return data; - this.bind(); - this.setValue( sourceArray, offset ); + }, - }, + clone: function () { - // create getter / setter pair for a property in the scene graph - bind: function() { + /* + // Handle primitives - var targetObject = this.node, - parsedPath = this.parsedPath, + var parameters = this.parameters; - objectName = parsedPath.objectName, - propertyName = parsedPath.propertyName, - propertyIndex = parsedPath.propertyIndex; + if ( parameters !== undefined ) { - if ( ! targetObject ) { + var values = []; - targetObject = THREE.PropertyBinding.findNode( - this.rootNode, parsedPath.nodeName ) || this.rootNode; + for ( var key in parameters ) { - this.node = targetObject; + values.push( parameters[ key ] ); - } + } - // set fail state so we can just 'return' on error - this.getValue = this._getValue_unavailable; - this.setValue = this._setValue_unavailable; + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - // ensure there is a value node - if ( ! targetObject ) { + } - console.error( " trying to update node for track: " + this.path + " but it wasn't found." ); - return; + return new this.constructor().copy( this ); + */ - } + return new BufferGeometry().copy( this ); - if ( objectName ) { + }, - var objectIndex = parsedPath.objectIndex; + copy: function ( source ) { - // special cases were we need to reach deeper into the hierarchy to get the face materials.... - switch ( objectName ) { + var index = source.index; - case 'materials': + if ( index !== null ) { - if ( ! targetObject.material ) { + this.setIndex( index.clone() ); - console.error( ' can not bind to material as node does not have a material', this ); - return; + } - } + var attributes = source.attributes; - if ( ! targetObject.material.materials ) { + for ( var name in attributes ) { - console.error( ' can not bind to material.materials as node.material does not have a materials array', this ); - return; + var attribute = attributes[ name ]; + this.addAttribute( name, attribute.clone() ); - } + } - targetObject = targetObject.material.materials; + var groups = source.groups; - break; + for ( var i = 0, l = groups.length; i < l; i ++ ) { - case 'bones': + var group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); - if ( ! targetObject.skeleton ) { + } - console.error( ' can not bind to bones as node does not have a skeleton', this ); - return; + return this; - } + }, - // potential future optimization: skip this if propertyIndex is already an integer - // and convert the integer string to a true integer. + dispose: function () { - targetObject = targetObject.skeleton.bones; + this.dispatchEvent( { type: 'dispose' } ); - // support resolving morphTarget names into indices. - for ( var i = 0; i < targetObject.length; i ++ ) { + } - if ( targetObject[ i ].name === objectIndex ) { + } ); - objectIndex = i; - break; + BufferGeometry.MaxIndex = 65535; - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function WebGLGeometries ( gl, properties, info ) { + this.isWebGLGeometries = true; - break; + var geometries = {}; - default: + function get( object ) { - if ( targetObject[ objectName ] === undefined ) { + var geometry = object.geometry; - console.error( ' can not bind to objectName of node, undefined', this ); - return; + if ( geometries[ geometry.id ] !== undefined ) { - } + return geometries[ geometry.id ]; - targetObject = targetObject[ objectName ]; + } - } + geometry.addEventListener( 'dispose', onGeometryDispose ); + var buffergeometry; - if ( objectIndex !== undefined ) { + if ( (geometry && geometry.isBufferGeometry) ) { - if ( targetObject[ objectIndex ] === undefined ) { + buffergeometry = geometry; - console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject ); - return; + } else if ( (geometry && geometry.isGeometry) ) { - } + if ( geometry._bufferGeometry === undefined ) { - targetObject = targetObject[ objectIndex ]; + geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); - } + } - } + buffergeometry = geometry._bufferGeometry; - // resolve property - var nodeProperty = targetObject[ propertyName ]; + } - if ( nodeProperty === undefined ) { + geometries[ geometry.id ] = buffergeometry; - var nodeName = parsedPath.nodeName; + info.memory.geometries ++; - console.error( " trying to update property for track: " + nodeName + - '.' + propertyName + " but it wasn't found.", targetObject ); - return; + return buffergeometry; - } + } - // determine versioning scheme - var versioning = this.Versioning.None; + function onGeometryDispose( event ) { - if ( targetObject.needsUpdate !== undefined ) { // material + var geometry = event.target; + var buffergeometry = geometries[ geometry.id ]; - versioning = this.Versioning.NeedsUpdate; - this.targetObject = targetObject; + if ( buffergeometry.index !== null ) { - } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform + deleteAttribute( buffergeometry.index ); - versioning = this.Versioning.MatrixWorldNeedsUpdate; - this.targetObject = targetObject; + } - } + deleteAttributes( buffergeometry.attributes ); - // determine how the property gets bound - var bindingType = this.BindingType.Direct; + geometry.removeEventListener( 'dispose', onGeometryDispose ); - if ( propertyIndex !== undefined ) { - // access a sub element of the property array (only primitives are supported right now) + delete geometries[ geometry.id ]; - if ( propertyName === "morphTargetInfluences" ) { - // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. + // TODO - // support resolving morphTarget names into indices. - if ( ! targetObject.geometry ) { + var property = properties.get( geometry ); - console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this ); - return; + if ( property.wireframe ) { - } + deleteAttribute( property.wireframe ); - if ( ! targetObject.geometry.morphTargets ) { + } - console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this ); - return; + properties.delete( geometry ); - } + var bufferproperty = properties.get( buffergeometry ); - for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { + if ( bufferproperty.wireframe ) { - if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) { + deleteAttribute( bufferproperty.wireframe ); - propertyIndex = i; - break; + } - } + properties.delete( buffergeometry ); - } + // - } + info.memory.geometries --; - bindingType = this.BindingType.ArrayElement; + } - this.resolvedProperty = nodeProperty; - this.propertyIndex = propertyIndex; + function getAttributeBuffer( attribute ) { - } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { - // must use copy for Object3D.Euler/Quaternion + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - bindingType = this.BindingType.HasFromToArray; + return properties.get( attribute.data ).__webglBuffer; - this.resolvedProperty = nodeProperty; + } - } else if ( nodeProperty.length !== undefined ) { + return properties.get( attribute ).__webglBuffer; - bindingType = this.BindingType.EntireArray; + } - this.resolvedProperty = nodeProperty; + function deleteAttribute( attribute ) { - } else { + var buffer = getAttributeBuffer( attribute ); - this.propertyName = propertyName; + if ( buffer !== undefined ) { - } + gl.deleteBuffer( buffer ); + removeAttributeBuffer( attribute ); - // select getter / setter - this.getValue = this.GetterByBindingType[ bindingType ]; - this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; + } - }, + } - unbind: function() { + function deleteAttributes( attributes ) { - this.node = null; + for ( var name in attributes ) { - // back to the prototype version of getValue / setValue - // note: avoiding to mutate the shape of 'this' via 'delete' - this.getValue = this._getValue_unbound; - this.setValue = this._setValue_unbound; + deleteAttribute( attributes[ name ] ); - } + } -}; + } -Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued + function removeAttributeBuffer( attribute ) { - // these are used to "bind" a nonexistent property - _getValue_unavailable: function() {}, - _setValue_unavailable: function() {}, + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - // initial state of these methods that calls 'bind' - _getValue_unbound: THREE.PropertyBinding.prototype.getValue, - _setValue_unbound: THREE.PropertyBinding.prototype.setValue, + properties.delete( attribute.data ); - BindingType: { - Direct: 0, - EntireArray: 1, - ArrayElement: 2, - HasFromToArray: 3 - }, + } else { - Versioning: { - None: 0, - NeedsUpdate: 1, - MatrixWorldNeedsUpdate: 2 - }, + properties.delete( attribute ); - GetterByBindingType: [ + } - function getValue_direct( buffer, offset ) { + } - buffer[ offset ] = this.node[ this.propertyName ]; + this.get = get; - }, + }; - function getValue_array( buffer, offset ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - var source = this.resolvedProperty; + function WebGLObjects ( gl, properties, info ) { + this.isWebGLObjects = true; - for ( var i = 0, n = source.length; i !== n; ++ i ) { + var geometries = new WebGLGeometries( gl, properties, info ); - buffer[ offset ++ ] = source[ i ]; + // - } + function update( object ) { - }, + // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter. - function getValue_arrayElement( buffer, offset ) { + var geometry = geometries.get( object ); - buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + if ( (object.geometry && object.geometry.isGeometry) ) { - }, + geometry.updateFromObject( object ); - function getValue_toArray( buffer, offset ) { + } - this.resolvedProperty.toArray( buffer, offset ); + var index = geometry.index; + var attributes = geometry.attributes; - } + if ( index !== null ) { - ], + updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER ); - SetterByBindingTypeAndVersioning: [ + } - [ - // Direct + for ( var name in attributes ) { - function setValue_direct( buffer, offset ) { + updateAttribute( attributes[ name ], gl.ARRAY_BUFFER ); - this.node[ this.propertyName ] = buffer[ offset ]; + } - }, + // morph targets - function setValue_direct_setNeedsUpdate( buffer, offset ) { + var morphAttributes = geometry.morphAttributes; - this.node[ this.propertyName ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + for ( var name in morphAttributes ) { - }, + var array = morphAttributes[ name ]; - function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + for ( var i = 0, l = array.length; i < l; i ++ ) { - this.node[ this.propertyName ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + updateAttribute( array[ i ], gl.ARRAY_BUFFER ); - } + } - ], [ + } - // EntireArray + return geometry; - function setValue_array( buffer, offset ) { + } - var dest = this.resolvedProperty; + function updateAttribute( attribute, bufferType ) { - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + var data = ( (attribute && attribute.isInterleavedBufferAttribute) ) ? attribute.data : attribute; - dest[ i ] = buffer[ offset ++ ]; + var attributeProperties = properties.get( data ); - } + if ( attributeProperties.__webglBuffer === undefined ) { - }, + createBuffer( attributeProperties, data, bufferType ); - function setValue_array_setNeedsUpdate( buffer, offset ) { + } else if ( attributeProperties.version !== data.version ) { - var dest = this.resolvedProperty; + updateBuffer( attributeProperties, data, bufferType ); - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + } - dest[ i ] = buffer[ offset ++ ]; + } - } + function createBuffer( attributeProperties, data, bufferType ) { - this.targetObject.needsUpdate = true; + attributeProperties.__webglBuffer = gl.createBuffer(); + gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); - }, + var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; - function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + gl.bufferData( bufferType, data.array, usage ); - var dest = this.resolvedProperty; + attributeProperties.version = data.version; - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + } - dest[ i ] = buffer[ offset ++ ]; + function updateBuffer( attributeProperties, data, bufferType ) { - } + gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); - this.targetObject.matrixWorldNeedsUpdate = true; + if ( data.dynamic === false || data.updateRange.count === - 1 ) { - } + // Not using update ranges - ], [ + gl.bufferSubData( bufferType, 0, data.array ); - // ArrayElement + } else if ( data.updateRange.count === 0 ) { - function setValue_arrayElement( buffer, offset ) { + console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' ); - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + } else { - }, + gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT, + data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) ); - function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + data.updateRange.count = 0; // reset range - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + } - }, + attributeProperties.version = data.version; - function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + } - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + function getAttributeBuffer( attribute ) { - } + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - ], [ + return properties.get( attribute.data ).__webglBuffer; - // HasToFromArray + } - function setValue_fromArray( buffer, offset ) { + return properties.get( attribute ).__webglBuffer; - this.resolvedProperty.fromArray( buffer, offset ); + } - }, + function getWireframeAttribute( geometry ) { - function setValue_fromArray_setNeedsUpdate( buffer, offset ) { + var property = properties.get( geometry ); - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.needsUpdate = true; + if ( property.wireframe !== undefined ) { - }, + return property.wireframe; - function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + } - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.matrixWorldNeedsUpdate = true; + var indices = []; - } + var index = geometry.index; + var attributes = geometry.attributes; + var position = attributes.position; - ] + // console.time( 'wireframe' ); - ] + if ( index !== null ) { -} ); + var edges = {}; + var array = index.array; -THREE.PropertyBinding.Composite = - function( targetGroup, path, optionalParsedPath ) { + for ( var i = 0, l = array.length; i < l; i += 3 ) { - var parsedPath = optionalParsedPath || - THREE.PropertyBinding.parseTrackName( path ); + var a = array[ i + 0 ]; + var b = array[ i + 1 ]; + var c = array[ i + 2 ]; - this._targetGroup = targetGroup; - this._bindings = targetGroup.subscribe_( path, parsedPath ); + if ( checkEdge( edges, a, b ) ) indices.push( a, b ); + if ( checkEdge( edges, b, c ) ) indices.push( b, c ); + if ( checkEdge( edges, c, a ) ) indices.push( c, a ); -}; + } -THREE.PropertyBinding.Composite.prototype = { + } else { - constructor: THREE.PropertyBinding.Composite, + var array = attributes.position.array; - getValue: function( array, offset ) { + for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { - this.bind(); // bind all binding + var a = i + 0; + var b = i + 1; + var c = i + 2; - var firstValidIndex = this._targetGroup.nCachedObjects_, - binding = this._bindings[ firstValidIndex ]; + indices.push( a, b, b, c, c, a ); - // and only call .getValue on the first - if ( binding !== undefined ) binding.getValue( array, offset ); + } - }, + } - setValue: function( array, offset ) { + // console.timeEnd( 'wireframe' ); - var bindings = this._bindings; + var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; + var attribute = new BufferAttribute( new TypeArray( indices ), 1 ); - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); - bindings[ i ].setValue( array, offset ); + property.wireframe = attribute; - } + return attribute; - }, + } - bind: function() { + function checkEdge( edges, a, b ) { - var bindings = this._bindings; + if ( a > b ) { - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + var tmp = a; + a = b; + b = tmp; - bindings[ i ].bind(); + } - } + var list = edges[ a ]; - }, + if ( list === undefined ) { - unbind: function() { + edges[ a ] = [ b ]; + return true; - var bindings = this._bindings; + } else if ( list.indexOf( b ) === -1 ) { - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + list.push( b ); + return true; - bindings[ i ].unbind(); + } - } + return false; - } + } -}; + this.getAttributeBuffer = getAttributeBuffer; + this.getWireframeAttribute = getWireframeAttribute; -THREE.PropertyBinding.create = function( root, path, parsedPath ) { + this.update = update; - if ( ! ( root instanceof THREE.AnimationObjectGroup ) ) { + }; - return new THREE.PropertyBinding( root, path, parsedPath ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - } else { + function WebGLLights () { + this.isWebGLLights = true; - return new THREE.PropertyBinding.Composite( root, path, parsedPath ); + var lights = {}; - } + this.get = function ( light ) { -}; + if ( lights[ light.id ] !== undefined ) { -THREE.PropertyBinding.parseTrackName = function( trackName ) { + return lights[ light.id ]; - // matches strings in the form of: - // nodeName.property - // nodeName.property[accessor] - // nodeName.material.property[accessor] - // uuid.property[accessor] - // uuid.objectName[objectIndex].propertyName[propertyIndex] - // parentName/nodeName.property - // parentName/parentName/nodeName.property[index] - // .bone[Armature.DEF_cog].position - // created and tested via https://regex101.com/#javascript + } - var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_.:\- ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/; - var matches = re.exec( trackName ); + var uniforms; - if ( ! matches ) { + switch ( light.type ) { - throw new Error( "cannot parse trackName at all: " + trackName ); + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color(), - } + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - if ( matches.index === re.lastIndex ) { + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0, - re.lastIndex++; + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - } + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0, - var results = { - // directoryName: matches[ 1 ], // (tschw) currently unused - nodeName: matches[ 3 ], // allowed to be null, specified root node. - objectName: matches[ 5 ], - objectIndex: matches[ 7 ], - propertyName: matches[ 9 ], - propertyIndex: matches[ 11 ] // allowed to be null, specifies that the whole property is set. - }; + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - if ( results.propertyName === null || results.propertyName.length === 0 ) { + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; - throw new Error( "can not parse propertyName from trackName: " + trackName ); + } - } + lights[ light.id ] = uniforms; - return results; + return uniforms; -}; + }; -THREE.PropertyBinding.findNode = function( root, nodeName ) { + }; - if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { + function WebGLCapabilities ( gl, extensions, parameters ) { + this.isWebGLCapabilities = true; - return root; + var maxAnisotropy; - } + function getMaxAnisotropy() { - // search into skeleton bones. - if ( root.skeleton ) { + if ( maxAnisotropy !== undefined ) return maxAnisotropy; - var searchSkeleton = function( skeleton ) { + var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - for( var i = 0; i < skeleton.bones.length; i ++ ) { + if ( extension !== null ) { - var bone = skeleton.bones[ i ]; + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); - if ( bone.name === nodeName ) { + } else { - return bone; + maxAnisotropy = 0; - } - } + } - return null; + return maxAnisotropy; - }; + } - var bone = searchSkeleton( root.skeleton ); + function getMaxPrecision( precision ) { - if ( bone ) { + if ( precision === 'highp' ) { - return bone; + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { - } - } + return 'highp'; - // search into node subtree. - if ( root.children ) { + } - var searchNodeSubtree = function( children ) { + precision = 'mediump'; - for( var i = 0; i < children.length; i ++ ) { + } - var childNode = children[ i ]; + if ( precision === 'mediump' ) { - if ( childNode.name === nodeName || childNode.uuid === nodeName ) { + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { - return childNode; + return 'mediump'; - } + } - var result = searchNodeSubtree( childNode.children ); + } - if ( result ) return result; + return 'lowp'; - } + } - return null; + this.getMaxAnisotropy = getMaxAnisotropy; + this.getMaxPrecision = getMaxPrecision; - }; + this.precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false; - var subTreeNode = searchNodeSubtree( root.children ); + this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); + this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); - if ( subTreeNode ) { + this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); + this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); + this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); - return subTreeNode; + this.vertexTextures = this.maxVertexTextures > 0; + this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); + this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures; - } + var _maxPrecision = getMaxPrecision( this.precision ); - } + if ( _maxPrecision !== this.precision ) { - return null; + console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' ); + this.precision = _maxPrecision; -}; + } -// File:src/animation/PropertyMixer.js + if ( this.logarithmicDepthBuffer ) { -/** - * - * Buffered scene graph property that allows weighted accumulation. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' ); -THREE.PropertyMixer = function ( binding, typeName, valueSize ) { + } - this.binding = binding; - this.valueSize = valueSize; + }; - var bufferType = Float64Array, - mixFunction; + /** + * @author mrdoob / http://mrdoob.com/ + */ - switch ( typeName ) { + function WebGLExtensions ( gl ) { + this.isWebGLExtensions = true; - case 'quaternion': mixFunction = this._slerp; break; + var extensions = {}; - case 'string': - case 'bool': + this.get = function ( name ) { - bufferType = Array, mixFunction = this._select; break; + if ( extensions[ name ] !== undefined ) { - default: mixFunction = this._lerp; + return extensions[ name ]; - } + } - this.buffer = new bufferType( valueSize * 4 ); - // layout: [ incoming | accu0 | accu1 | orig ] - // - // interpolators can use .buffer as their .result - // the data then goes to 'incoming' - // - // 'accu0' and 'accu1' are used frame-interleaved for - // the cumulative result and are compared to detect - // changes - // - // 'orig' stores the original state of the property + var extension; - this._mixBufferRegion = mixFunction; + switch ( name ) { - this.cumulativeWeight = 0; + case 'WEBGL_depth_texture': + extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); + break; - this.useCount = 0; - this.referenceCount = 0; + case 'EXT_texture_filter_anisotropic': + extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); + break; -}; + case 'WEBGL_compressed_texture_s3tc': + extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); + break; -THREE.PropertyMixer.prototype = { + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; - constructor: THREE.PropertyMixer, + case 'WEBGL_compressed_texture_etc1': + extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); + break; - // accumulate data in the 'incoming' region into 'accu' - accumulate: function( accuIndex, weight ) { + default: + extension = gl.getExtension( name ); - // note: happily accumulating nothing when weight = 0, the caller knows - // the weight and shouldn't have made the call in the first place + } - var buffer = this.buffer, - stride = this.valueSize, - offset = accuIndex * stride + stride, + if ( extension === null ) { - currentWeight = this.cumulativeWeight; + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); - if ( currentWeight === 0 ) { + } - // accuN := incoming * weight + extensions[ name ] = extension; - for ( var i = 0; i !== stride; ++ i ) { + return extension; - buffer[ offset + i ] = buffer[ i ]; + }; - } + }; - currentWeight = weight; + /** + * @author mrdoob / http://mrdoob.com/ + */ - } else { + function WebGLIndexedBufferRenderer ( _gl, extensions, _infoRender ) { + this.isWebGLIndexedBufferRenderer = true; - // accuN := accuN + incoming * weight + var mode; - currentWeight += weight; - var mix = weight / currentWeight; - this._mixBufferRegion( buffer, offset, 0, mix, stride ); + function setMode( value ) { - } + mode = value; - this.cumulativeWeight = currentWeight; + } - }, + var type, size; - // apply the state of 'accu' to the binding when accus differ - apply: function( accuIndex ) { + function setIndex( index ) { - var stride = this.valueSize, - buffer = this.buffer, - offset = accuIndex * stride + stride, + if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { - weight = this.cumulativeWeight, + type = _gl.UNSIGNED_INT; + size = 4; - binding = this.binding; + } else { - this.cumulativeWeight = 0; + type = _gl.UNSIGNED_SHORT; + size = 2; - if ( weight < 1 ) { + } - // accuN := accuN + original * ( 1 - cumulativeWeight ) + } - var originalValueOffset = stride * 3; + function render( start, count ) { - this._mixBufferRegion( - buffer, offset, originalValueOffset, 1 - weight, stride ); + _gl.drawElements( mode, count, type, start * size ); - } + _infoRender.calls ++; + _infoRender.vertices += count; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; - for ( var i = stride, e = stride + stride; i !== e; ++ i ) { + } - if ( buffer[ i ] !== buffer[ i + stride ] ) { + function renderInstances( geometry, start, count ) { - // value has changed -> update scene graph + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - binding.setValue( buffer, offset ); - break; + if ( extension === null ) { - } + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - } + } - }, + extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount ); - // remember the state of the bound property and copy it to both accus - saveOriginalState: function() { + _infoRender.calls ++; + _infoRender.vertices += count * geometry.maxInstancedCount; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; + } - var binding = this.binding; + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; - var buffer = this.buffer, - stride = this.valueSize, + }; - originalValueOffset = stride * 3; + function WebGLClipping() { + this.isWebGLClipping = true; - binding.getValue( buffer, originalValueOffset ); + var scope = this, - // accu[0..1] := orig -- initially detect changes against the original - for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { + globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false, - buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + plane = new Plane(), + viewNormalMatrix = new Matrix3(), - } + uniform = { value: null, needsUpdate: false }; - this.cumulativeWeight = 0; + this.uniform = uniform; + this.numPlanes = 0; - }, + this.init = function( planes, enableLocalClipping, camera ) { - // apply the state previously taken via 'saveOriginalState' to the binding - restoreOriginalState: function() { + var enabled = + planes.length !== 0 || + enableLocalClipping || + // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || + localClippingEnabled; - var originalValueOffset = this.valueSize * 3; - this.binding.setValue( this.buffer, originalValueOffset ); + localClippingEnabled = enableLocalClipping; - }, + globalState = projectPlanes( planes, camera, 0 ); + numGlobalPlanes = planes.length; + return enabled; - // mix functions + }; - _select: function( buffer, dstOffset, srcOffset, t, stride ) { + this.beginShadows = function() { - if ( t >= 0.5 ) { + renderingShadows = true; + projectPlanes( null ); - for ( var i = 0; i !== stride; ++ i ) { + }; - buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + this.endShadows = function() { - } + renderingShadows = false; + resetGlobalState(); - } + }; - }, + this.setState = function( planes, clipShadows, camera, cache, fromCache ) { - _slerp: function( buffer, dstOffset, srcOffset, t, stride ) { + if ( ! localClippingEnabled || + planes === null || planes.length === 0 || + renderingShadows && ! clipShadows ) { + // there's no local clipping - THREE.Quaternion.slerpFlat( buffer, dstOffset, - buffer, dstOffset, buffer, srcOffset, t ); + if ( renderingShadows ) { + // there's no global clipping - }, + projectPlanes( null ); - _lerp: function( buffer, dstOffset, srcOffset, t, stride ) { + } else { - var s = 1 - t; + resetGlobalState(); + } - for ( var i = 0; i !== stride; ++ i ) { + } else { - var j = dstOffset + i; + var nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4, - buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + dstArray = cache.clippingState || null; - } + uniform.value = dstArray; // ensure unique state - } + dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); -}; + for ( var i = 0; i !== lGlobal; ++ i ) { -// File:src/animation/tracks/BooleanKeyframeTrack.js + dstArray[ i ] = globalState[ i ]; -/** - * - * A Track of Boolean keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + } -THREE.BooleanKeyframeTrack = function ( name, times, values ) { + cache.clippingState = dstArray; + this.numPlanes += nGlobal; - THREE.KeyframeTrack.call( this, name, times, values ); + } -}; -THREE.BooleanKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + }; - constructor: THREE.BooleanKeyframeTrack, + function resetGlobalState() { - ValueTypeName: 'bool', - ValueBufferType: Array, + if ( uniform.value !== globalState ) { - DefaultInterpolation: THREE.InterpolateDiscrete, + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; - InterpolantFactoryMethodLinear: undefined, - InterpolantFactoryMethodSmooth: undefined + } - // Note: Actually this track could have a optimized / compressed - // representation of a single value and a custom interpolant that - // computes "firstValue ^ isOdd( index )". + scope.numPlanes = numGlobalPlanes; -} ); + } -// File:src/animation/tracks/ColorKeyframeTrack.js + function projectPlanes( planes, camera, dstOffset, skipTransform ) { -/** - * - * A Track of keyframe values that represent color. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + var nPlanes = planes !== null ? planes.length : 0, + dstArray = null; -THREE.ColorKeyframeTrack = function ( name, times, values, interpolation ) { + if ( nPlanes !== 0 ) { - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + dstArray = uniform.value; -}; + if ( skipTransform !== true || dstArray === null ) { -THREE.ColorKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + var flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; - constructor: THREE.ColorKeyframeTrack, + viewNormalMatrix.getNormalMatrix( viewMatrix ); - ValueTypeName: 'color' + if ( dstArray === null || dstArray.length < flatSize ) { - // ValueBufferType is inherited + dstArray = new Float32Array( flatSize ); - // DefaultInterpolation is inherited + } + for ( var i = 0, i4 = dstOffset; + i !== nPlanes; ++ i, i4 += 4 ) { - // Note: Very basic implementation and nothing special yet. - // However, this is the place for color space parameterization. + plane.copy( planes[ i ] ). + applyMatrix4( viewMatrix, viewNormalMatrix ); -} ); + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; -// File:src/animation/tracks/NumberKeyframeTrack.js + } -/** - * - * A Track of numeric keyframe values. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + } -THREE.NumberKeyframeTrack = function ( name, times, values, interpolation ) { + uniform.value = dstArray; + uniform.needsUpdate = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + } -}; + scope.numPlanes = nPlanes; + return dstArray; -THREE.NumberKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + } - constructor: THREE.NumberKeyframeTrack, + }; - ValueTypeName: 'number', + /** + * @author mrdoob / http://mrdoob.com/ + */ - // ValueBufferType is inherited + function WebGLBufferRenderer ( _gl, extensions, _infoRender ) { + this.isWebGLBufferRenderer = true; - // DefaultInterpolation is inherited + var mode; -} ); + function setMode( value ) { -// File:src/animation/tracks/QuaternionKeyframeTrack.js + mode = value; -/** - * - * A Track of quaternion keyframe values. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + } -THREE.QuaternionKeyframeTrack = function ( name, times, values, interpolation ) { + function render( start, count ) { - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + _gl.drawArrays( mode, start, count ); -}; + _infoRender.calls ++; + _infoRender.vertices += count; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; -THREE.QuaternionKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + } - constructor: THREE.QuaternionKeyframeTrack, + function renderInstances( geometry ) { - ValueTypeName: 'quaternion', + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - // ValueBufferType is inherited + if ( extension === null ) { - DefaultInterpolation: THREE.InterpolateLinear, + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - InterpolantFactoryMethodLinear: function( result ) { + } - return new THREE.QuaternionLinearInterpolant( - this.times, this.values, this.getValueSize(), result ); + var position = geometry.attributes.position; - }, + var count = 0; - InterpolantFactoryMethodSmooth: undefined // not yet implemented + if ( (position && position.isInterleavedBufferAttribute) ) { -} ); + count = position.data.count; -// File:src/animation/tracks/StringKeyframeTrack.js + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); -/** - * - * A Track that interpolates Strings - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + } else { -THREE.StringKeyframeTrack = function ( name, times, values, interpolation ) { + count = position.count; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); -}; + } -THREE.StringKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + _infoRender.calls ++; + _infoRender.vertices += count * geometry.maxInstancedCount; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; - constructor: THREE.StringKeyframeTrack, + } - ValueTypeName: 'string', - ValueBufferType: Array, + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; - DefaultInterpolation: THREE.InterpolateDiscrete, + }; - InterpolantFactoryMethodLinear: undefined, + /** + * @author alteredq / http://alteredqualia.com + */ - InterpolantFactoryMethodSmooth: undefined + function WebGLRenderTargetCube ( width, height, options ) { + this.isWebGLRenderTargetCube = this.isWebGLRenderTarget = true; -} ); + WebGLRenderTarget.call( this, width, height, options ); -// File:src/animation/tracks/VectorKeyframeTrack.js + this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 + this.activeMipMapLevel = 0; -/** - * - * A Track of vectored keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + }; -THREE.VectorKeyframeTrack = function ( name, times, values, interpolation ) { + WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); + WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + /** + * @author Mugen87 / https://github.com/Mugen87 + */ -}; + function BoxBufferGeometry ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + this.isBoxBufferGeometry = this.isBufferGeometry = true; -THREE.VectorKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + BufferGeometry.call( this ); - constructor: THREE.VectorKeyframeTrack, + this.type = 'BoxBufferGeometry'; - ValueTypeName: 'vector' + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; - // ValueBufferType is inherited + var scope = this; - // DefaultInterpolation is inherited + // segments + widthSegments = Math.floor( widthSegments ) || 1; + heightSegments = Math.floor( heightSegments ) || 1; + depthSegments = Math.floor( depthSegments ) || 1; -} ); + // these are used to calculate buffer length + var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments ); + var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments ); -// File:src/audio/Audio.js + // buffers + var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); + var vertices = new Float32Array( vertexCount * 3 ); + var normals = new Float32Array( vertexCount * 3 ); + var uvs = new Float32Array( vertexCount * 2 ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author Reece Aaron Lecrivain / http://reecenotes.com/ - */ + // offset variables + var vertexBufferOffset = 0; + var uvBufferOffset = 0; + var indexBufferOffset = 0; + var numberOfVertices = 0; -THREE.Audio = function ( listener ) { + // group variables + var groupStart = 0; - THREE.Object3D.call( this ); + // build each side of the box geometry + buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px + buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx + buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py + buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny + buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz + buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz - this.type = 'Audio'; + // build geometry + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); - this.context = listener.context; - this.source = this.context.createBufferSource(); - this.source.onended = this.onEnded.bind( this ); + // helper functions - this.gain = this.context.createGain(); - this.gain.connect( listener.getInput() ); + function calculateVertexCount ( w, h, d ) { - this.autoplay = false; + var vertices = 0; - this.startTime = 0; - this.playbackRate = 1; - this.isPlaying = false; - this.hasPlaybackControl = true; - this.sourceType = 'empty'; + // calculate the amount of vertices for each side (plane) + vertices += (w + 1) * (h + 1) * 2; // xy + vertices += (w + 1) * (d + 1) * 2; // xz + vertices += (d + 1) * (h + 1) * 2; // zy - this.filters = []; + return vertices; -}; + } -THREE.Audio.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + function calculateIndexCount ( w, h, d ) { - constructor: THREE.Audio, + var index = 0; - getOutput: function () { + // calculate the amount of squares for each side + index += w * h * 2; // xy + index += w * d * 2; // xz + index += d * h * 2; // zy - return this.gain; + return index * 6; // two triangles per square => six vertices per square - }, + } - setNodeSource: function ( audioNode ) { + function buildPlane ( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { - this.hasPlaybackControl = false; - this.sourceType = 'audioNode'; - this.source = audioNode; - this.connect(); + var segmentWidth = width / gridX; + var segmentHeight = height / gridY; - return this; + var widthHalf = width / 2; + var heightHalf = height / 2; + var depthHalf = depth / 2; - }, + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - setBuffer: function ( audioBuffer ) { + var vertexCounter = 0; + var groupCount = 0; - this.source.buffer = audioBuffer; - this.sourceType = 'buffer'; + var vector = new Vector3(); - if ( this.autoplay ) this.play(); + // generate vertices, normals and uvs - return this; + for ( var iy = 0; iy < gridY1; iy ++ ) { - }, + var y = iy * segmentHeight - heightHalf; - play: function () { + for ( var ix = 0; ix < gridX1; ix ++ ) { - if ( this.isPlaying === true ) { + var x = ix * segmentWidth - widthHalf; - console.warn( 'THREE.Audio: Audio is already playing.' ); - return; + // set values to correct vector component + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; - } + // now apply vector to vertex buffer + vertices[ vertexBufferOffset ] = vector.x; + vertices[ vertexBufferOffset + 1 ] = vector.y; + vertices[ vertexBufferOffset + 2 ] = vector.z; - if ( this.hasPlaybackControl === false ) { + // set values to correct vector component + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + // now apply vector to normal buffer + normals[ vertexBufferOffset ] = vector.x; + normals[ vertexBufferOffset + 1 ] = vector.y; + normals[ vertexBufferOffset + 2 ] = vector.z; - } + // uvs + uvs[ uvBufferOffset ] = ix / gridX; + uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY ); - var source = this.context.createBufferSource(); + // update offsets and counters + vertexBufferOffset += 3; + uvBufferOffset += 2; + vertexCounter += 1; - source.buffer = this.source.buffer; - source.loop = this.source.loop; - source.onended = this.source.onended; - source.start( 0, this.startTime ); - source.playbackRate.value = this.playbackRate; + } - this.isPlaying = true; + } - this.source = source; + // 1. you need three indices to draw a single face + // 2. a single segment consists of two faces + // 3. so we need to generate six (2*3) indices per segment - return this.connect(); + for ( iy = 0; iy < gridY; iy ++ ) { - }, + for ( ix = 0; ix < gridX; ix ++ ) { - pause: function () { + // indices + var a = numberOfVertices + ix + gridX1 * iy; + var b = numberOfVertices + ix + gridX1 * ( iy + 1 ); + var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; - if ( this.hasPlaybackControl === false ) { + // face one + indices[ indexBufferOffset ] = a; + indices[ indexBufferOffset + 1 ] = b; + indices[ indexBufferOffset + 2 ] = d; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + // face two + indices[ indexBufferOffset + 3 ] = b; + indices[ indexBufferOffset + 4 ] = c; + indices[ indexBufferOffset + 5 ] = d; - } + // update offsets and counters + indexBufferOffset += 6; + groupCount += 6; - this.source.stop(); - this.startTime = this.context.currentTime; - this.isPlaying = false; + } - return this; + } - }, + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, materialIndex ); - stop: function () { + // calculate new start value for groups + groupStart += groupCount; - if ( this.hasPlaybackControl === false ) { + // update total number of vertices + numberOfVertices += vertexCounter; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + } - } + }; - this.source.stop(); - this.startTime = 0; - this.isPlaying = false; + BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; - return this; + /** + * @author bhouston / http://clara.io + */ - }, + function Ray ( origin, direction ) { + this.isRay = true; - connect: function () { + this.origin = ( origin !== undefined ) ? origin : new Vector3(); + this.direction = ( direction !== undefined ) ? direction : new Vector3(); - if ( this.filters.length > 0 ) { + }; - this.source.connect( this.filters[ 0 ] ); + Ray.prototype = { - for ( var i = 1, l = this.filters.length; i < l; i ++ ) { + constructor: Ray, - this.filters[ i - 1 ].connect( this.filters[ i ] ); + set: function ( origin, direction ) { - } + this.origin.copy( origin ); + this.direction.copy( direction ); - this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); + return this; - } else { + }, - this.source.connect( this.getOutput() ); + clone: function () { - } + return new this.constructor().copy( this ); - return this; + }, - }, + copy: function ( ray ) { - disconnect: function () { + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); - if ( this.filters.length > 0 ) { + return this; - this.source.disconnect( this.filters[ 0 ] ); + }, - for ( var i = 1, l = this.filters.length; i < l; i ++ ) { + at: function ( t, optionalTarget ) { - this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + var result = optionalTarget || new Vector3(); - } + return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + }, - } else { + lookAt: function ( v ) { - this.source.disconnect( this.getOutput() ); + this.direction.copy( v ).sub( this.origin ).normalize(); - } + return this; - return this; + }, - }, + recast: function () { - getFilters: function () { + var v1 = new Vector3(); - return this.filters; + return function recast( t ) { - }, + this.origin.copy( this.at( t, v1 ) ); - setFilters: function ( value ) { + return this; - if ( ! value ) value = []; + }; - if ( this.isPlaying === true ) { + }(), - this.disconnect(); - this.filters = value; - this.connect(); + closestPointToPoint: function ( point, optionalTarget ) { - } else { + var result = optionalTarget || new Vector3(); + result.subVectors( point, this.origin ); + var directionDistance = result.dot( this.direction ); - this.filters = value; + if ( directionDistance < 0 ) { - } + return result.copy( this.origin ); - return this; + } - }, + return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - getFilter: function () { + }, - return this.getFilters()[ 0 ]; + distanceToPoint: function ( point ) { - }, + return Math.sqrt( this.distanceSqToPoint( point ) ); - setFilter: function ( filter ) { + }, - return this.setFilters( filter ? [ filter ] : [] ); + distanceSqToPoint: function () { - }, + var v1 = new Vector3(); - setPlaybackRate: function ( value ) { + return function distanceSqToPoint( point ) { - if ( this.hasPlaybackControl === false ) { + var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + // point behind the ray - } + if ( directionDistance < 0 ) { - this.playbackRate = value; + return this.origin.distanceToSquared( point ); - if ( this.isPlaying === true ) { + } - this.source.playbackRate.value = this.playbackRate; + v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - } + return v1.distanceToSquared( point ); - return this; + }; - }, + }(), - getPlaybackRate: function () { + distanceSqToSegment: function () { - return this.playbackRate; + var segCenter = new Vector3(); + var segDir = new Vector3(); + var diff = new Vector3(); - }, + return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - onEnded: function () { + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h + // It returns the min distance between the ray and the segment + // defined by v0 and v1 + // It can also set two optional targets : + // - The closest point on the ray + // - The closest point on the segment - this.isPlaying = false; + segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + segDir.copy( v1 ).sub( v0 ).normalize(); + diff.copy( this.origin ).sub( segCenter ); - }, + var segExtent = v0.distanceTo( v1 ) * 0.5; + var a01 = - this.direction.dot( segDir ); + var b0 = diff.dot( this.direction ); + var b1 = - diff.dot( segDir ); + var c = diff.lengthSq(); + var det = Math.abs( 1 - a01 * a01 ); + var s0, s1, sqrDist, extDet; - getLoop: function () { + if ( det > 0 ) { - if ( this.hasPlaybackControl === false ) { + // The ray and segment are not parallel. - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return false; + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; - } + if ( s0 >= 0 ) { - return this.source.loop; + if ( s1 >= - extDet ) { - }, + if ( s1 <= extDet ) { - setLoop: function ( value ) { + // region 0 + // Minimum at interior points of ray and segment. - if ( this.hasPlaybackControl === false ) { + var invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + } else { - } + // region 1 - this.source.loop = value; + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - }, + } - getVolume: function () { + } else { - return this.gain.gain.value; + // region 5 - }, + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + } - setVolume: function ( value ) { + } else { - this.gain.gain.value = value; + if ( s1 <= - extDet ) { - return this; + // region 4 - } + s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; -} ); + } else if ( s1 <= extDet ) { -// File:src/audio/AudioAnalyser.js + // region 3 -/** - * @author mrdoob / http://mrdoob.com/ - */ + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; -THREE.AudioAnalyser = function ( audio, fftSize ) { + } else { - this.analyser = audio.context.createAnalyser(); - this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; + // region 2 - this.data = new Uint8Array( this.analyser.frequencyBinCount ); + s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - audio.getOutput().connect( this.analyser ); + } -}; + } -Object.assign( THREE.AudioAnalyser.prototype, { + } else { - getFrequencyData: function () { + // Ray and segment are parallel. - this.analyser.getByteFrequencyData( this.data ); + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - return this.data; + } - }, + if ( optionalPointOnRay ) { - getAverageFrequency: function () { + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); - var value = 0, data = this.getFrequencyData(); + } - for ( var i = 0; i < data.length; i ++ ) { + if ( optionalPointOnSegment ) { - value += data[ i ]; + optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); - } + } - return value / data.length; + return sqrDist; - } + }; -} ); + }(), -// File:src/audio/AudioContext.js + intersectSphere: function () { -/** - * @author mrdoob / http://mrdoob.com/ - */ + var v1 = new Vector3(); -Object.defineProperty( THREE, 'AudioContext', { + return function intersectSphere( sphere, optionalTarget ) { - get: ( function () { + v1.subVectors( sphere.center, this.origin ); + var tca = v1.dot( this.direction ); + var d2 = v1.dot( v1 ) - tca * tca; + var radius2 = sphere.radius * sphere.radius; - var context; + if ( d2 > radius2 ) return null; - return function get() { + var thc = Math.sqrt( radius2 - d2 ); - if ( context === undefined ) { + // t0 = first intersect point - entrance on front of sphere + var t0 = tca - thc; - context = new ( window.AudioContext || window.webkitAudioContext )(); + // t1 = second intersect point - exit point on back of sphere + var t1 = tca + thc; - } + // test to see if both t0 and t1 are behind the ray - if so, return null + if ( t0 < 0 && t1 < 0 ) return null; - return context; + // test to see if t0 is behind the ray: + // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, + // in order to always return an intersect point that is in front of the ray. + if ( t0 < 0 ) return this.at( t1, optionalTarget ); - }; + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, optionalTarget ); - } )() + }; -} ); + }(), -// File:src/audio/PositionalAudio.js + intersectsSphere: function ( sphere ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + return this.distanceToPoint( sphere.center ) <= sphere.radius; -THREE.PositionalAudio = function ( listener ) { + }, - THREE.Audio.call( this, listener ); + distanceToPlane: function ( plane ) { - this.panner = this.context.createPanner(); - this.panner.connect( this.gain ); + var denominator = plane.normal.dot( this.direction ); -}; + if ( denominator === 0 ) { -THREE.PositionalAudio.prototype = Object.assign( Object.create( THREE.Audio.prototype ), { + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { - constructor: THREE.PositionalAudio, + return 0; - getOutput: function () { + } - return this.panner; + // Null is preferable to undefined since undefined means.... it is undefined - }, + return null; - getRefDistance: function () { + } - return this.panner.refDistance; + var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - }, + // Return if the ray never intersects the plane - setRefDistance: function ( value ) { + return t >= 0 ? t : null; - this.panner.refDistance = value; + }, - }, + intersectPlane: function ( plane, optionalTarget ) { - getRolloffFactor: function () { + var t = this.distanceToPlane( plane ); - return this.panner.rolloffFactor; + if ( t === null ) { - }, + return null; - setRolloffFactor: function ( value ) { + } - this.panner.rolloffFactor = value; + return this.at( t, optionalTarget ); - }, + }, - getDistanceModel: function () { - return this.panner.distanceModel; - }, + intersectsPlane: function ( plane ) { - setDistanceModel: function ( value ) { + // check if the ray lies on the plane first - this.panner.distanceModel = value; + var distToPoint = plane.distanceToPoint( this.origin ); - }, + if ( distToPoint === 0 ) { - getMaxDistance: function () { + return true; - return this.panner.maxDistance; + } - }, + var denominator = plane.normal.dot( this.direction ); - setMaxDistance: function ( value ) { + if ( denominator * distToPoint < 0 ) { - this.panner.maxDistance = value; + return true; - }, + } - updateMatrixWorld: ( function () { + // ray origin is behind the plane (and is pointing behind it) - var position = new THREE.Vector3(); + return false; - return function updateMatrixWorld( force ) { + }, - THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); + intersectBox: function ( box, optionalTarget ) { - position.setFromMatrixPosition( this.matrixWorld ); + var tmin, tmax, tymin, tymax, tzmin, tzmax; - this.panner.setPosition( position.x, position.y, position.z ); + var invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; - }; + var origin = this.origin; - } )() + if ( invdirx >= 0 ) { + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; -} ); + } else { -// File:src/audio/AudioListener.js + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.AudioListener = function () { + if ( invdiry >= 0 ) { - THREE.Object3D.call( this ); + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; - this.type = 'AudioListener'; + } else { - this.context = THREE.AudioContext; + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; - this.gain = this.context.createGain(); - this.gain.connect( this.context.destination ); + } - this.filter = null; + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; -}; + // These lines also handle the case where tmin or tmax is NaN + // (result of 0 * Infinity). x !== x returns true if x is NaN -THREE.AudioListener.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - constructor: THREE.AudioListener, + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - getInput: function () { + if ( invdirz >= 0 ) { - return this.gain; + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; - }, + } else { - removeFilter: function ( ) { + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; - if ( this.filter !== null ) { + } - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); - this.gain.connect( this.context.destination ); - this.filter = null; + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - } + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - }, + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - getFilter: function () { + //return point closest to the ray (positive side) - return this.filter; + if ( tmax < 0 ) return null; - }, + return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); - setFilter: function ( value ) { + }, - if ( this.filter !== null ) { + intersectsBox: ( function () { - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); + var v = new Vector3(); - } else { + return function intersectsBox( box ) { - this.gain.disconnect( this.context.destination ); + return this.intersectBox( box, v ) !== null; - } + }; - this.filter = value; - this.gain.connect( this.filter ); - this.filter.connect( this.context.destination ); + } )(), - }, + intersectTriangle: function () { - getMasterVolume: function () { + // Compute the offset origin, edges, and normal. + var diff = new Vector3(); + var edge1 = new Vector3(); + var edge2 = new Vector3(); + var normal = new Vector3(); - return this.gain.gain.value; + return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { - }, + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - setMasterVolume: function ( value ) { + edge1.subVectors( b, a ); + edge2.subVectors( c, a ); + normal.crossVectors( edge1, edge2 ); - this.gain.gain.value = value; + // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, + // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by + // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) + // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) + // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) + var DdN = this.direction.dot( normal ); + var sign; - }, + if ( DdN > 0 ) { - updateMatrixWorld: ( function () { + if ( backfaceCulling ) return null; + sign = 1; - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3(); + } else if ( DdN < 0 ) { - var orientation = new THREE.Vector3(); + sign = - 1; + DdN = - DdN; - return function updateMatrixWorld( force ) { + } else { - THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); + return null; - var listener = this.context.listener; - var up = this.up; + } - this.matrixWorld.decompose( position, quaternion, scale ); + diff.subVectors( this.origin, a ); + var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); - orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { - listener.setPosition( position.x, position.y, position.z ); - listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z ); + return null; - }; + } - } )() + var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); -} ); + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { -// File:src/cameras/Camera.js + return null; -/** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author WestLangley / http://github.com/WestLangley -*/ + } -THREE.Camera = function () { + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { - THREE.Object3D.call( this ); + return null; - this.type = 'Camera'; + } - this.matrixWorldInverse = new THREE.Matrix4(); - this.projectionMatrix = new THREE.Matrix4(); + // Line intersects triangle, check if ray does. + var QdN = - sign * diff.dot( normal ); -}; + // t < 0, no intersection + if ( QdN < 0 ) { -THREE.Camera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Camera.prototype.constructor = THREE.Camera; + return null; -THREE.Camera.prototype.getWorldDirection = function () { + } - var quaternion = new THREE.Quaternion(); + // Ray intersects triangle. + return this.at( QdN / DdN, optionalTarget ); - return function getWorldDirection( optionalTarget ) { + }; - var result = optionalTarget || new THREE.Vector3(); + }(), - this.getWorldQuaternion( quaternion ); + applyMatrix4: function ( matrix4 ) { - return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + this.direction.add( this.origin ).applyMatrix4( matrix4 ); + this.origin.applyMatrix4( matrix4 ); + this.direction.sub( this.origin ); + this.direction.normalize(); - }; + return this; -}(); + }, -THREE.Camera.prototype.lookAt = function () { + equals: function ( ray ) { - // This routine does not support cameras with rotated and/or translated parent(s) + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - var m1 = new THREE.Matrix4(); + } - return function lookAt( vector ) { + }; - m1.lookAt( this.position, vector, this.up ); + /** + * @author bhouston / http://clara.io + */ - this.quaternion.setFromRotationMatrix( m1 ); + function Line3 ( start, end ) { + this.isLine3 = true; - }; + this.start = ( start !== undefined ) ? start : new Vector3(); + this.end = ( end !== undefined ) ? end : new Vector3(); -}(); + }; -THREE.Camera.prototype.clone = function () { + Line3.prototype = { - return new this.constructor().copy( this ); + constructor: Line3, -}; + set: function ( start, end ) { -THREE.Camera.prototype.copy = function ( source ) { + this.start.copy( start ); + this.end.copy( end ); - THREE.Object3D.prototype.copy.call( this, source ); + return this; - this.matrixWorldInverse.copy( source.matrixWorldInverse ); - this.projectionMatrix.copy( source.projectionMatrix ); + }, - return this; + clone: function () { -}; + return new this.constructor().copy( this ); -// File:src/cameras/CubeCamera.js + }, -/** - * Camera for rendering cube maps - * - renders scene into axis-aligned cube - * - * @author alteredq / http://alteredqualia.com/ - */ + copy: function ( line ) { -THREE.CubeCamera = function ( near, far, cubeResolution ) { + this.start.copy( line.start ); + this.end.copy( line.end ); - THREE.Object3D.call( this ); + return this; - this.type = 'CubeCamera'; + }, - var fov = 90, aspect = 1; + center: function ( optionalTarget ) { - var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPX.up.set( 0, - 1, 0 ); - cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) ); - this.add( cameraPX ); + var result = optionalTarget || new Vector3(); + return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNX.up.set( 0, - 1, 0 ); - cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) ); - this.add( cameraNX ); + }, - var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPY.up.set( 0, 0, 1 ); - cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) ); - this.add( cameraPY ); + delta: function ( optionalTarget ) { - var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNY.up.set( 0, 0, - 1 ); - cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) ); - this.add( cameraNY ); + var result = optionalTarget || new Vector3(); + return result.subVectors( this.end, this.start ); - var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPZ.up.set( 0, - 1, 0 ); - cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) ); - this.add( cameraPZ ); + }, - var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNZ.up.set( 0, - 1, 0 ); - cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) ); - this.add( cameraNZ ); + distanceSq: function () { - var options = { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter }; + return this.start.distanceToSquared( this.end ); - this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); + }, - this.updateCubeMap = function ( renderer, scene ) { + distance: function () { - if ( this.parent === null ) this.updateMatrixWorld(); + return this.start.distanceTo( this.end ); - var renderTarget = this.renderTarget; - var generateMipmaps = renderTarget.texture.generateMipmaps; + }, - renderTarget.texture.generateMipmaps = false; + at: function ( t, optionalTarget ) { - renderTarget.activeCubeFace = 0; - renderer.render( scene, cameraPX, renderTarget ); + var result = optionalTarget || new Vector3(); - renderTarget.activeCubeFace = 1; - renderer.render( scene, cameraNX, renderTarget ); + return this.delta( result ).multiplyScalar( t ).add( this.start ); - renderTarget.activeCubeFace = 2; - renderer.render( scene, cameraPY, renderTarget ); + }, - renderTarget.activeCubeFace = 3; - renderer.render( scene, cameraNY, renderTarget ); + closestPointToPointParameter: function () { - renderTarget.activeCubeFace = 4; - renderer.render( scene, cameraPZ, renderTarget ); + var startP = new Vector3(); + var startEnd = new Vector3(); - renderTarget.texture.generateMipmaps = generateMipmaps; + return function closestPointToPointParameter( point, clampToLine ) { - renderTarget.activeCubeFace = 5; - renderer.render( scene, cameraNZ, renderTarget ); + startP.subVectors( point, this.start ); + startEnd.subVectors( this.end, this.start ); - renderer.setRenderTarget( null ); + var startEnd2 = startEnd.dot( startEnd ); + var startEnd_startP = startEnd.dot( startP ); - }; + var t = startEnd_startP / startEnd2; -}; + if ( clampToLine ) { -THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.CubeCamera.prototype.constructor = THREE.CubeCamera; + t = exports.Math.clamp( t, 0, 1 ); -// File:src/cameras/OrthographicCamera.js + } -/** - * @author alteredq / http://alteredqualia.com/ - * @author arose / http://github.com/arose - */ + return t; -THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { + }; - THREE.Camera.call( this ); + }(), - this.type = 'OrthographicCamera'; + closestPointToPoint: function ( point, clampToLine, optionalTarget ) { - this.zoom = 1; - this.view = null; + var t = this.closestPointToPointParameter( point, clampToLine ); - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; + var result = optionalTarget || new Vector3(); - this.near = ( near !== undefined ) ? near : 0.1; - this.far = ( far !== undefined ) ? far : 2000; + return this.delta( result ).multiplyScalar( t ).add( this.start ); - this.updateProjectionMatrix(); + }, -}; + applyMatrix4: function ( matrix ) { -THREE.OrthographicCamera.prototype = Object.assign( Object.create( THREE.Camera.prototype ), { + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); - constructor: THREE.OrthographicCamera, + return this; - copy: function ( source ) { + }, - THREE.Camera.prototype.copy.call( this, source ); + equals: function ( line ) { - this.left = source.left; - this.right = source.right; - this.top = source.top; - this.bottom = source.bottom; - this.near = source.near; - this.far = source.far; + return line.start.equals( this.start ) && line.end.equals( this.end ); - this.zoom = source.zoom; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + } - return this; + }; - }, + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) { + function Triangle ( a, b, c ) { + this.isTriangle = true; - this.view = { - fullWidth: fullWidth, - fullHeight: fullHeight, - offsetX: x, - offsetY: y, - width: width, - height: height - }; + this.a = ( a !== undefined ) ? a : new Vector3(); + this.b = ( b !== undefined ) ? b : new Vector3(); + this.c = ( c !== undefined ) ? c : new Vector3(); - this.updateProjectionMatrix(); + }; - }, + Triangle.normal = function () { - clearViewOffset: function() { + var v0 = new Vector3(); - this.view = null; - this.updateProjectionMatrix(); + return function normal( a, b, c, optionalTarget ) { - }, + var result = optionalTarget || new Vector3(); - updateProjectionMatrix: function () { + result.subVectors( c, b ); + v0.subVectors( a, b ); + result.cross( v0 ); - var dx = ( this.right - this.left ) / ( 2 * this.zoom ); - var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); - var cx = ( this.right + this.left ) / 2; - var cy = ( this.top + this.bottom ) / 2; + var resultLengthSq = result.lengthSq(); + if ( resultLengthSq > 0 ) { - var left = cx - dx; - var right = cx + dx; - var top = cy + dy; - var bottom = cy - dy; + return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); - if ( this.view !== null ) { + } - var zoomW = this.zoom / ( this.view.width / this.view.fullWidth ); - var zoomH = this.zoom / ( this.view.height / this.view.fullHeight ); - var scaleW = ( this.right - this.left ) / this.view.width; - var scaleH = ( this.top - this.bottom ) / this.view.height; + return result.set( 0, 0, 0 ); - left += scaleW * ( this.view.offsetX / zoomW ); - right = left + scaleW * ( this.view.width / zoomW ); - top -= scaleH * ( this.view.offsetY / zoomH ); - bottom = top - scaleH * ( this.view.height / zoomH ); + }; - } + }(); - this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + Triangle.barycoordFromPoint = function () { - }, + var v0 = new Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); - toJSON: function ( meta ) { + return function barycoordFromPoint( point, a, b, c, optionalTarget ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + v0.subVectors( c, a ); + v1.subVectors( b, a ); + v2.subVectors( point, a ); - data.object.zoom = this.zoom; - data.object.left = this.left; - data.object.right = this.right; - data.object.top = this.top; - data.object.bottom = this.bottom; - data.object.near = this.near; - data.object.far = this.far; + var dot00 = v0.dot( v0 ); + var dot01 = v0.dot( v1 ); + var dot02 = v0.dot( v2 ); + var dot11 = v1.dot( v1 ); + var dot12 = v1.dot( v2 ); - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + var denom = ( dot00 * dot11 - dot01 * dot01 ); - return data; + var result = optionalTarget || new Vector3(); - } + // collinear or singular triangle + if ( denom === 0 ) { -} ); + // arbitrary location outside of triangle? + // not sure if this is the best idea, maybe should be returning undefined + return result.set( - 2, - 1, - 1 ); -// File:src/cameras/PerspectiveCamera.js + } -/** - * @author mrdoob / http://mrdoob.com/ - * @author greggman / http://games.greggman.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author tschw - */ + var invDenom = 1 / denom; + var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; -THREE.PerspectiveCamera = function ( fov, aspect, near, far ) { + // barycentric coordinates must always sum to 1 + return result.set( 1 - u - v, v, u ); - THREE.Camera.call( this ); + }; - this.type = 'PerspectiveCamera'; + }(); - this.fov = fov !== undefined ? fov : 50; - this.zoom = 1; + Triangle.containsPoint = function () { - this.near = near !== undefined ? near : 0.1; - this.far = far !== undefined ? far : 2000; - this.focus = 10; + var v1 = new Vector3(); - this.aspect = aspect !== undefined ? aspect : 1; - this.view = null; + return function containsPoint( point, a, b, c ) { - this.filmGauge = 35; // width of the film (default in millimeters) - this.filmOffset = 0; // horizontal film offset (same unit as gauge) + var result = Triangle.barycoordFromPoint( point, a, b, c, v1 ); - this.updateProjectionMatrix(); + return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); -}; + }; -THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.prototype ), { + }(); - constructor: THREE.PerspectiveCamera, + Triangle.prototype = { - copy: function ( source ) { + constructor: Triangle, - THREE.Camera.prototype.copy.call( this, source ); + set: function ( a, b, c ) { - this.fov = source.fov; - this.zoom = source.zoom; + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); - this.near = source.near; - this.far = source.far; - this.focus = source.focus; + return this; - this.aspect = source.aspect; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + }, - this.filmGauge = source.filmGauge; - this.filmOffset = source.filmOffset; + setFromPointsAndIndices: function ( points, i0, i1, i2 ) { - return this; + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); - }, + return this; - /** - * Sets the FOV by focal length in respect to the current .filmGauge. - * - * The default film gauge is 35, so that the focal length can be specified for - * a 35mm (full frame) camera. - * - * Values for focal length and film gauge must have the same unit. - */ - setFocalLength: function ( focalLength ) { + }, - // see http://www.bobatkins.com/photography/technical/field_of_view.html - var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + clone: function () { - this.fov = THREE.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); - this.updateProjectionMatrix(); + return new this.constructor().copy( this ); - }, + }, - /** - * Calculates the focal length from the current .fov and .filmGauge. - */ - getFocalLength: function () { + copy: function ( triangle ) { - var vExtentSlope = Math.tan( THREE.Math.DEG2RAD * 0.5 * this.fov ); + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); - return 0.5 * this.getFilmHeight() / vExtentSlope; + return this; - }, + }, - getEffectiveFOV: function () { + area: function () { - return THREE.Math.RAD2DEG * 2 * Math.atan( - Math.tan( THREE.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + var v0 = new Vector3(); + var v1 = new Vector3(); - }, + return function area() { - getFilmWidth: function () { + v0.subVectors( this.c, this.b ); + v1.subVectors( this.a, this.b ); - // film not completely covered in portrait format (aspect < 1) - return this.filmGauge * Math.min( this.aspect, 1 ); + return v0.cross( v1 ).length() * 0.5; - }, + }; - getFilmHeight: function () { + }(), - // film not completely covered in landscape format (aspect > 1) - return this.filmGauge / Math.max( this.aspect, 1 ); + midpoint: function ( optionalTarget ) { - }, + var result = optionalTarget || new Vector3(); + return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); - /** - * Sets an offset in a larger frustum. This is useful for multi-window or - * multi-monitor/multi-machine setups. - * - * For example, if you have 3x2 monitors and each monitor is 1920x1080 and - * the monitors are in grid like this - * - * +---+---+---+ - * | A | B | C | - * +---+---+---+ - * | D | E | F | - * +---+---+---+ - * - * then for each monitor you would call it like this - * - * var w = 1920; - * var h = 1080; - * var fullWidth = w * 3; - * var fullHeight = h * 2; - * - * --A-- - * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); - * --B-- - * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); - * --C-- - * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); - * --D-- - * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); - * --E-- - * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); - * --F-- - * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); - * - * Note there is no reason monitors have to be the same size or in a grid. - */ - setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { - - this.aspect = fullWidth / fullHeight; - - this.view = { - fullWidth: fullWidth, - fullHeight: fullHeight, - offsetX: x, - offsetY: y, - width: width, - height: height - }; - - this.updateProjectionMatrix(); + }, - }, + normal: function ( optionalTarget ) { - clearViewOffset: function() { + return Triangle.normal( this.a, this.b, this.c, optionalTarget ); - this.view = null; - this.updateProjectionMatrix(); + }, - }, + plane: function ( optionalTarget ) { - updateProjectionMatrix: function () { + var result = optionalTarget || new Plane(); - var near = this.near, - top = near * Math.tan( - THREE.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, - height = 2 * top, - width = this.aspect * height, - left = - 0.5 * width, - view = this.view; + return result.setFromCoplanarPoints( this.a, this.b, this.c ); - if ( view !== null ) { + }, - var fullWidth = view.fullWidth, - fullHeight = view.fullHeight; + barycoordFromPoint: function ( point, optionalTarget ) { - left += view.offsetX * width / fullWidth; - top -= view.offsetY * height / fullHeight; - width *= view.width / fullWidth; - height *= view.height / fullHeight; + return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); - } + }, - var skew = this.filmOffset; - if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); + containsPoint: function ( point ) { - this.projectionMatrix.makeFrustum( - left, left + width, top - height, top, near, this.far ); + return Triangle.containsPoint( point, this.a, this.b, this.c ); - }, + }, - toJSON: function ( meta ) { + closestPointToPoint: function () { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var plane, edgeList, projectedPoint, closestPoint; - data.object.fov = this.fov; - data.object.zoom = this.zoom; + return function closestPointToPoint( point, optionalTarget ) { - data.object.near = this.near; - data.object.far = this.far; - data.object.focus = this.focus; + if ( plane === undefined ) { - data.object.aspect = this.aspect; + plane = new Plane(); + edgeList = [ new Line3(), new Line3(), new Line3() ]; + projectedPoint = new Vector3(); + closestPoint = new Vector3(); - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + } - data.object.filmGauge = this.filmGauge; - data.object.filmOffset = this.filmOffset; + var result = optionalTarget || new Vector3(); + var minDistance = Infinity; - return data; + // project the point onto the plane of the triangle - } + plane.setFromCoplanarPoints( this.a, this.b, this.c ); + plane.projectPoint( point, projectedPoint ); -} ); + // check if the projection lies within the triangle -// File:src/cameras/StereoCamera.js + if( this.containsPoint( projectedPoint ) === true ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + // if so, this is the closest point -THREE.StereoCamera = function () { + result.copy( projectedPoint ); - this.type = 'StereoCamera'; + } else { - this.aspect = 1; + // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices - this.cameraL = new THREE.PerspectiveCamera(); - this.cameraL.layers.enable( 1 ); - this.cameraL.matrixAutoUpdate = false; + edgeList[ 0 ].set( this.a, this.b ); + edgeList[ 1 ].set( this.b, this.c ); + edgeList[ 2 ].set( this.c, this.a ); - this.cameraR = new THREE.PerspectiveCamera(); - this.cameraR.layers.enable( 2 ); - this.cameraR.matrixAutoUpdate = false; + for( var i = 0; i < edgeList.length; i ++ ) { -}; + edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); -Object.assign( THREE.StereoCamera.prototype, { + var distance = projectedPoint.distanceToSquared( closestPoint ); - update: ( function () { + if( distance < minDistance ) { - var focus, fov, aspect, near, far; + minDistance = distance; - var eyeRight = new THREE.Matrix4(); - var eyeLeft = new THREE.Matrix4(); + result.copy( closestPoint ); - return function update( camera ) { + } - var needsUpdate = focus !== camera.focus || fov !== camera.fov || - aspect !== camera.aspect * this.aspect || near !== camera.near || - far !== camera.far; + } - if ( needsUpdate ) { + } - focus = camera.focus; - fov = camera.fov; - aspect = camera.aspect * this.aspect; - near = camera.near; - far = camera.far; + return result; - // Off-axis stereoscopic effect based on - // http://paulbourke.net/stereographics/stereorender/ + }; - var projectionMatrix = camera.projectionMatrix.clone(); - var eyeSep = 0.064 / 2; - var eyeSepOnProjection = eyeSep * near / focus; - var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 ); - var xmin, xmax; + }(), - // translate xOffset + equals: function ( triangle ) { - eyeLeft.elements[ 12 ] = - eyeSep; - eyeRight.elements[ 12 ] = eyeSep; + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - // for left eye + } - xmin = - ymax * aspect + eyeSepOnProjection; - xmax = ymax * aspect + eyeSepOnProjection; + }; - projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * shading: THREE.SmoothShading, + * depthTest: , + * depthWrite: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: + * } + */ - this.cameraL.projectionMatrix.copy( projectionMatrix ); + function MeshBasicMaterial ( parameters ) { + this.isMeshBasicMaterial = this.isMaterial = true; - // for right eye + Material.call( this ); - xmin = - ymax * aspect - eyeSepOnProjection; - xmax = ymax * aspect - eyeSepOnProjection; + this.type = 'MeshBasicMaterial'; - projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + this.color = new Color( 0xffffff ); // emissive - this.cameraR.projectionMatrix.copy( projectionMatrix ); + this.map = null; - } + this.aoMap = null; + this.aoMapIntensity = 1.0; - this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft ); - this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight ); + this.specularMap = null; - }; + this.alphaMap = null; - } )() + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; -} ); + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; -// File:src/lights/Light.js + this.skinning = false; + this.morphTargets = false; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + this.lights = false; -THREE.Light = function ( color, intensity ) { + this.setValues( parameters ); - THREE.Object3D.call( this ); + }; - this.type = 'Light'; + MeshBasicMaterial.prototype = Object.create( Material.prototype ); + MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; - this.color = new THREE.Color( color ); - this.intensity = intensity !== undefined ? intensity : 1; + MeshBasicMaterial.prototype.copy = function ( source ) { - this.receiveShadow = undefined; + Material.prototype.copy.call( this, source ); -}; + this.color.copy( source.color ); -THREE.Light.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + this.map = source.map; - constructor: THREE.Light, + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - copy: function ( source ) { + this.specularMap = source.specularMap; - THREE.Object3D.prototype.copy.call( this, source ); + this.alphaMap = source.alphaMap; - this.color.copy( source.color ); - this.intensity = source.intensity; + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - return this; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - }, + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - toJSON: function ( meta ) { + return this; - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + }; - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author jonobr1 / http://jonobr1.com/ + */ - if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + function Mesh ( geometry, material ) { + this.isMesh = true; - if ( this.distance !== undefined ) data.object.distance = this.distance; - if ( this.angle !== undefined ) data.object.angle = this.angle; - if ( this.decay !== undefined ) data.object.decay = this.decay; - if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra; + Object3D.call( this ); - return data; + this.type = 'Mesh'; - } + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); -} ); + this.drawMode = TrianglesDrawMode; -// File:src/lights/LightShadow.js + this.updateMorphTargets(); -/** - * @author mrdoob / http://mrdoob.com/ - */ + }; -THREE.LightShadow = function ( camera ) { + Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { - this.camera = camera; + constructor: Mesh, - this.bias = 0; - this.radius = 1; + setDrawMode: function ( value ) { - this.mapSize = new THREE.Vector2( 512, 512 ); + this.drawMode = value; - this.map = null; - this.matrix = new THREE.Matrix4(); + }, -}; + copy: function ( source ) { -Object.assign( THREE.LightShadow.prototype, { + Object3D.prototype.copy.call( this, source ); - copy: function ( source ) { + this.drawMode = source.drawMode; - this.camera = source.camera.clone(); + return this; - this.bias = source.bias; - this.radius = source.radius; + }, - this.mapSize.copy( source.mapSize ); + updateMorphTargets: function () { - return this; + if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { - }, + this.morphTargetBase = - 1; + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - clone: function () { + for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { - return new this.constructor().copy( this ); + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; - } + } -} ); + } -// File:src/lights/AmbientLight.js + }, -/** - * @author mrdoob / http://mrdoob.com/ - */ + getMorphTargetIndexByName: function ( name ) { -THREE.AmbientLight = function ( color, intensity ) { + if ( this.morphTargetDictionary[ name ] !== undefined ) { - THREE.Light.call( this, color, intensity ); + return this.morphTargetDictionary[ name ]; - this.type = 'AmbientLight'; + } - this.castShadow = undefined; + console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); -}; + return 0; -THREE.AmbientLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { + }, - constructor: THREE.AmbientLight + raycast: ( function () { -} ); + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); -// File:src/lights/DirectionalLight.js + var vA = new Vector3(); + var vB = new Vector3(); + var vC = new Vector3(); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + var tempA = new Vector3(); + var tempB = new Vector3(); + var tempC = new Vector3(); -THREE.DirectionalLight = function ( color, intensity ) { + var uvA = new Vector2(); + var uvB = new Vector2(); + var uvC = new Vector2(); - THREE.Light.call( this, color, intensity ); + var barycoord = new Vector3(); - this.type = 'DirectionalLight'; + var intersectionPoint = new Vector3(); + var intersectionPointWorld = new Vector3(); - this.position.set( 0, 1, 0 ); - this.updateMatrix(); + function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { - this.target = new THREE.Object3D(); + Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); - this.shadow = new THREE.DirectionalLightShadow(); + uv1.multiplyScalar( barycoord.x ); + uv2.multiplyScalar( barycoord.y ); + uv3.multiplyScalar( barycoord.z ); -}; + uv1.add( uv2 ).add( uv3 ); -THREE.DirectionalLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { + return uv1.clone(); - constructor: THREE.DirectionalLight, + } - copy: function ( source ) { + function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) { - THREE.Light.prototype.copy.call( this, source ); + var intersect; + var material = object.material; - this.target = source.target.clone(); + if ( material.side === BackSide ) { - this.shadow = source.shadow.clone(); + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); - return this; + } else { - } + intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); -} ); + } -// File:src/lights/DirectionalLightShadow.js + if ( intersect === null ) return null; -/** - * @author mrdoob / http://mrdoob.com/ - */ + intersectionPointWorld.copy( point ); + intersectionPointWorld.applyMatrix4( object.matrixWorld ); -THREE.DirectionalLightShadow = function ( light ) { + var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); - THREE.LightShadow.call( this, new THREE.OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + if ( distance < raycaster.near || distance > raycaster.far ) return null; -}; + return { + distance: distance, + point: intersectionPointWorld.clone(), + object: object + }; -THREE.DirectionalLightShadow.prototype = Object.assign( Object.create( THREE.LightShadow.prototype ), { + } - constructor: THREE.DirectionalLightShadow + function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) { -} ); + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); -// File:src/lights/HemisphereLight.js + var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint ); -/** - * @author alteredq / http://alteredqualia.com/ - */ + if ( intersection ) { -THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) { + if ( uvs ) { - THREE.Light.call( this, skyColor, intensity ); + uvA.fromArray( uvs, a * 2 ); + uvB.fromArray( uvs, b * 2 ); + uvC.fromArray( uvs, c * 2 ); - this.type = 'HemisphereLight'; + intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); - this.castShadow = undefined; + } - this.position.set( 0, 1, 0 ); - this.updateMatrix(); + intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); + intersection.faceIndex = a; - this.groundColor = new THREE.Color( groundColor ); + } -}; + return intersection; -THREE.HemisphereLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { + } - constructor: THREE.HemisphereLight, + return function raycast( raycaster, intersects ) { - copy: function ( source ) { + var geometry = this.geometry; + var material = this.material; + var matrixWorld = this.matrixWorld; - THREE.Light.prototype.copy.call( this, source ); + if ( material === undefined ) return; - this.groundColor.copy( source.groundColor ); + // Checking boundingSphere distance to ray - return this; + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - } + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); -} ); + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; -// File:src/lights/PointLight.js + // -/** - * @author mrdoob / http://mrdoob.com/ - */ + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + // Check boundingBox before continuing -THREE.PointLight = function ( color, intensity, distance, decay ) { + if ( geometry.boundingBox !== null ) { - THREE.Light.call( this, color, intensity ); + if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; - this.type = 'PointLight'; + } - Object.defineProperty( this, 'power', { - get: function () { - // intensity = power per solid angle. - // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - return this.intensity * 4 * Math.PI; + var uvs, intersection; - }, - set: function ( power ) { - // intensity = power per solid angle. - // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - this.intensity = power / ( 4 * Math.PI ); - } - } ); + if ( (geometry && geometry.isBufferGeometry) ) { - this.distance = ( distance !== undefined ) ? distance : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + var a, b, c; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) ); + if ( attributes.uv !== undefined ) { -}; + uvs = attributes.uv.array; -THREE.PointLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { + } - constructor: THREE.PointLight, + if ( index !== null ) { - copy: function ( source ) { + var indices = index.array; - THREE.Light.prototype.copy.call( this, source ); + for ( var i = 0, l = indices.length; i < l; i += 3 ) { - this.distance = source.distance; - this.decay = source.decay; + a = indices[ i ]; + b = indices[ i + 1 ]; + c = indices[ i + 2 ]; - this.shadow = source.shadow.clone(); + intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); - return this; + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics + intersects.push( intersection ); -} ); + } -// File:src/lights/SpotLight.js + } -/** - * @author alteredq / http://alteredqualia.com/ - */ + } else { -THREE.SpotLight = function ( color, intensity, distance, angle, penumbra, decay ) { - THREE.Light.call( this, color, intensity ); + for ( var i = 0, l = positions.length; i < l; i += 9 ) { - this.type = 'SpotLight'; + a = i / 3; + b = a + 1; + c = a + 2; - this.position.set( 0, 1, 0 ); - this.updateMatrix(); + intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); - this.target = new THREE.Object3D(); + if ( intersection ) { - Object.defineProperty( this, 'power', { - get: function () { - // intensity = power per solid angle. - // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - return this.intensity * Math.PI; - }, - set: function ( power ) { - // intensity = power per solid angle. - // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - this.intensity = power / Math.PI; - } - } ); + intersection.index = a; // triangle number in positions buffer semantics + intersects.push( intersection ); - this.distance = ( distance !== undefined ) ? distance : 0; - this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; - this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + } - this.shadow = new THREE.SpotLightShadow(); + } -}; + } -THREE.SpotLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { + } else if ( (geometry && geometry.isGeometry) ) { - constructor: THREE.SpotLight, + var fvA, fvB, fvC; + var isFaceMaterial = (material && material.isMultiMaterial); + var materials = isFaceMaterial === true ? material.materials : null; - copy: function ( source ) { + var vertices = geometry.vertices; + var faces = geometry.faces; + var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; + if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; - THREE.Light.prototype.copy.call( this, source ); + for ( var f = 0, fl = faces.length; f < fl; f ++ ) { - this.distance = source.distance; - this.angle = source.angle; - this.penumbra = source.penumbra; - this.decay = source.decay; + var face = faces[ f ]; + var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material; - this.target = source.target.clone(); + if ( faceMaterial === undefined ) continue; - this.shadow = source.shadow.clone(); + fvA = vertices[ face.a ]; + fvB = vertices[ face.b ]; + fvC = vertices[ face.c ]; - return this; + if ( faceMaterial.morphTargets === true ) { - } + var morphTargets = geometry.morphTargets; + var morphInfluences = this.morphTargetInfluences; -} ); + vA.set( 0, 0, 0 ); + vB.set( 0, 0, 0 ); + vC.set( 0, 0, 0 ); -// File:src/lights/SpotLightShadow.js + for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + var influence = morphInfluences[ t ]; -THREE.SpotLightShadow = function () { + if ( influence === 0 ) continue; - THREE.LightShadow.call( this, new THREE.PerspectiveCamera( 50, 1, 0.5, 500 ) ); + var targets = morphTargets[ t ].vertices; -}; + vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence ); + vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence ); + vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence ); -THREE.SpotLightShadow.prototype = Object.assign( Object.create( THREE.LightShadow.prototype ), { + } - constructor: THREE.SpotLightShadow, + vA.add( fvA ); + vB.add( fvB ); + vC.add( fvC ); - update: function ( light ) { + fvA = vA; + fvB = vB; + fvC = vC; - var fov = THREE.Math.RAD2DEG * 2 * light.angle; - var aspect = this.mapSize.width / this.mapSize.height; - var far = light.distance || 500; + } - var camera = this.camera; + intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); - if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + if ( intersection ) { - camera.fov = fov; - camera.aspect = aspect; - camera.far = far; - camera.updateProjectionMatrix(); + if ( uvs ) { - } + var uvs_f = uvs[ f ]; + uvA.copy( uvs_f[ 0 ] ); + uvB.copy( uvs_f[ 1 ] ); + uvC.copy( uvs_f[ 2 ] ); - } + intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); -} ); + } -// File:src/loaders/AudioLoader.js + intersection.face = face; + intersection.faceIndex = f; + intersects.push( intersection ); -/** - * @author Reece Aaron Lecrivain / http://reecenotes.com/ - */ + } -THREE.AudioLoader = function ( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + } -}; + }; -Object.assign( THREE.AudioLoader.prototype, { + }() ), - load: function ( url, onLoad, onProgress, onError ) { + clone: function () { - var loader = new THREE.XHRLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); - loader.load( url, function ( buffer ) { + return new this.constructor( this.geometry, this.material ).copy( this ); - var context = THREE.AudioContext; + } - context.decodeAudioData( buffer, function ( audioBuffer ) { + } ); - onLoad( audioBuffer ); + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as + */ - } ); + function PlaneBufferGeometry ( width, height, widthSegments, heightSegments ) { + this.isPlaneBufferGeometry = this.isBufferGeometry = true; - }, onProgress, onError ); + BufferGeometry.call( this ); - } + this.type = 'PlaneBufferGeometry'; -} ); + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; -// File:src/loaders/Cache.js + var width_half = width / 2; + var height_half = height / 2; -/** - * @author mrdoob / http://mrdoob.com/ - */ + var gridX = Math.floor( widthSegments ) || 1; + var gridY = Math.floor( heightSegments ) || 1; -THREE.Cache = { + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - enabled: false, + var segment_width = width / gridX; + var segment_height = height / gridY; - files: {}, + var vertices = new Float32Array( gridX1 * gridY1 * 3 ); + var normals = new Float32Array( gridX1 * gridY1 * 3 ); + var uvs = new Float32Array( gridX1 * gridY1 * 2 ); - add: function ( key, file ) { + var offset = 0; + var offset2 = 0; - if ( this.enabled === false ) return; + for ( var iy = 0; iy < gridY1; iy ++ ) { - // console.log( 'THREE.Cache', 'Adding key:', key ); + var y = iy * segment_height - height_half; - this.files[ key ] = file; + for ( var ix = 0; ix < gridX1; ix ++ ) { - }, + var x = ix * segment_width - width_half; - get: function ( key ) { + vertices[ offset ] = x; + vertices[ offset + 1 ] = - y; - if ( this.enabled === false ) return; + normals[ offset + 2 ] = 1; - // console.log( 'THREE.Cache', 'Checking key:', key ); + uvs[ offset2 ] = ix / gridX; + uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); - return this.files[ key ]; + offset += 3; + offset2 += 2; - }, + } - remove: function ( key ) { + } - delete this.files[ key ]; + offset = 0; - }, + var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); - clear: function () { + for ( var iy = 0; iy < gridY; iy ++ ) { - this.files = {}; + for ( var ix = 0; ix < gridX; ix ++ ) { - } + var a = ix + gridX1 * iy; + var b = ix + gridX1 * ( iy + 1 ); + var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = ( ix + 1 ) + gridX1 * iy; -}; + indices[ offset ] = a; + indices[ offset + 1 ] = b; + indices[ offset + 2 ] = d; -// File:src/loaders/Loader.js + indices[ offset + 3 ] = b; + indices[ offset + 4 ] = c; + indices[ offset + 5 ] = d; -/** - * @author alteredq / http://alteredqualia.com/ - */ + offset += 6; -THREE.Loader = function () { + } - this.onLoadStart = function () {}; - this.onLoadProgress = function () {}; - this.onLoadComplete = function () {}; + } -}; + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); -THREE.Loader.prototype = { + }; - constructor: THREE.Loader, + PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; - crossOrigin: undefined, + /** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author WestLangley / http://github.com/WestLangley + */ - extractUrlBase: function ( url ) { + function Camera () { + this.isCamera = this.isObject3D = true; - var parts = url.split( '/' ); + Object3D.call( this ); - if ( parts.length === 1 ) return './'; + this.type = 'Camera'; - parts.pop(); + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); - return parts.join( '/' ) + '/'; + }; - }, + Camera.prototype = Object.create( Object3D.prototype ); + Camera.prototype.constructor = Camera; - initMaterials: function ( materials, texturePath, crossOrigin ) { + Camera.prototype.getWorldDirection = function () { - var array = []; + var quaternion = new Quaternion(); - for ( var i = 0; i < materials.length; ++ i ) { + return function getWorldDirection( optionalTarget ) { - array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); + var result = optionalTarget || new Vector3(); - } + this.getWorldQuaternion( quaternion ); - return array; + return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - }, + }; - createMaterial: ( function () { + }(); - var color, textureLoader, materialLoader; + Camera.prototype.lookAt = function () { - return function createMaterial( m, texturePath, crossOrigin ) { + // This routine does not support cameras with rotated and/or translated parent(s) - if ( color === undefined ) color = new THREE.Color(); - if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader(); - if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader(); + var m1 = new Matrix4(); - // convert from old material format + return function lookAt( vector ) { - var textures = {}; + m1.lookAt( this.position, vector, this.up ); - function loadTexture( path, repeat, offset, wrap, anisotropy ) { + this.quaternion.setFromRotationMatrix( m1 ); - var fullPath = texturePath + path; - var loader = THREE.Loader.Handlers.get( fullPath ); + }; - var texture; + }(); - if ( loader !== null ) { + Camera.prototype.clone = function () { - texture = loader.load( fullPath ); + return new this.constructor().copy( this ); - } else { + }; - textureLoader.setCrossOrigin( crossOrigin ); - texture = textureLoader.load( fullPath ); + Camera.prototype.copy = function ( source ) { - } + Object3D.prototype.copy.call( this, source ); - if ( repeat !== undefined ) { + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + this.projectionMatrix.copy( source.projectionMatrix ); - texture.repeat.fromArray( repeat ); + return this; - if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author greggman / http://games.greggman.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author tschw + */ - if ( offset !== undefined ) { + function PerspectiveCamera ( fov, aspect, near, far ) { + this.isPerspectiveCamera = true; - texture.offset.fromArray( offset ); + Camera.call( this ); - } + this.type = 'PerspectiveCamera'; - if ( wrap !== undefined ) { + this.fov = fov !== undefined ? fov : 50; + this.zoom = 1; - if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping; - if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping; - - if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping; - if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping; - - } - - if ( anisotropy !== undefined ) { - - texture.anisotropy = anisotropy; - - } - - var uuid = THREE.Math.generateUUID(); - - textures[ uuid ] = texture; - - return uuid; - - } - - // - - var json = { - uuid: THREE.Math.generateUUID(), - type: 'MeshLambertMaterial' - }; - - for ( var name in m ) { - - var value = m[ name ]; - - switch ( name ) { - case 'DbgColor': - case 'DbgIndex': - case 'opticalDensity': - case 'illumination': - break; - case 'DbgName': - json.name = value; - break; - case 'blending': - json.blending = THREE[ value ]; - break; - case 'colorAmbient': - case 'mapAmbient': - console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' ); - break; - case 'colorDiffuse': - json.color = color.fromArray( value ).getHex(); - break; - case 'colorSpecular': - json.specular = color.fromArray( value ).getHex(); - break; - case 'colorEmissive': - json.emissive = color.fromArray( value ).getHex(); - break; - case 'specularCoef': - json.shininess = value; - break; - case 'shading': - if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial'; - if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial'; - if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial'; - break; - case 'mapDiffuse': - json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); - break; - case 'mapDiffuseRepeat': - case 'mapDiffuseOffset': - case 'mapDiffuseWrap': - case 'mapDiffuseAnisotropy': - break; - case 'mapEmissive': - json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy ); - break; - case 'mapEmissiveRepeat': - case 'mapEmissiveOffset': - case 'mapEmissiveWrap': - case 'mapEmissiveAnisotropy': - break; - case 'mapLight': - json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); - break; - case 'mapLightRepeat': - case 'mapLightOffset': - case 'mapLightWrap': - case 'mapLightAnisotropy': - break; - case 'mapAO': - json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy ); - break; - case 'mapAORepeat': - case 'mapAOOffset': - case 'mapAOWrap': - case 'mapAOAnisotropy': - break; - case 'mapBump': - json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); - break; - case 'mapBumpScale': - json.bumpScale = value; - break; - case 'mapBumpRepeat': - case 'mapBumpOffset': - case 'mapBumpWrap': - case 'mapBumpAnisotropy': - break; - case 'mapNormal': - json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); - break; - case 'mapNormalFactor': - json.normalScale = [ value, value ]; - break; - case 'mapNormalRepeat': - case 'mapNormalOffset': - case 'mapNormalWrap': - case 'mapNormalAnisotropy': - break; - case 'mapSpecular': - json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); - break; - case 'mapSpecularRepeat': - case 'mapSpecularOffset': - case 'mapSpecularWrap': - case 'mapSpecularAnisotropy': - break; - case 'mapMetalness': - json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy ); - break; - case 'mapMetalnessRepeat': - case 'mapMetalnessOffset': - case 'mapMetalnessWrap': - case 'mapMetalnessAnisotropy': - break; - case 'mapRoughness': - json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy ); - break; - case 'mapRoughnessRepeat': - case 'mapRoughnessOffset': - case 'mapRoughnessWrap': - case 'mapRoughnessAnisotropy': - break; - case 'mapAlpha': - json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); - break; - case 'mapAlphaRepeat': - case 'mapAlphaOffset': - case 'mapAlphaWrap': - case 'mapAlphaAnisotropy': - break; - case 'flipSided': - json.side = THREE.BackSide; - break; - case 'doubleSided': - json.side = THREE.DoubleSide; - break; - case 'transparency': - console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' ); - json.opacity = value; - break; - case 'depthTest': - case 'depthWrite': - case 'colorWrite': - case 'opacity': - case 'reflectivity': - case 'transparent': - case 'visible': - case 'wireframe': - json[ name ] = value; - break; - case 'vertexColors': - if ( value === true ) json.vertexColors = THREE.VertexColors; - if ( value === 'face' ) json.vertexColors = THREE.FaceColors; - break; - default: - console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); - break; - } - - } - - if ( json.type === 'MeshBasicMaterial' ) delete json.emissive; - if ( json.type !== 'MeshPhongMaterial' ) delete json.specular; - - if ( json.opacity < 1 ) json.transparent = true; - - materialLoader.setTextures( textures ); - - return materialLoader.parse( json ); - - }; - - } )() + this.near = near !== undefined ? near : 0.1; + this.far = far !== undefined ? far : 2000; + this.focus = 10; -}; + this.aspect = aspect !== undefined ? aspect : 1; + this.view = null; -THREE.Loader.Handlers = { + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) - handlers: [], + this.updateProjectionMatrix(); - add: function ( regex, loader ) { + }; - this.handlers.push( regex, loader ); + PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - }, + constructor: PerspectiveCamera, - get: function ( file ) { + copy: function ( source ) { - var handlers = this.handlers; + Camera.prototype.copy.call( this, source ); - for ( var i = 0, l = handlers.length; i < l; i += 2 ) { + this.fov = source.fov; + this.zoom = source.zoom; - var regex = handlers[ i ]; - var loader = handlers[ i + 1 ]; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; - if ( regex.test( file ) ) { + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - return loader; + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; - } + return this; - } + }, - return null; + /** + * Sets the FOV by focal length in respect to the current .filmGauge. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * Values for focal length and film gauge must have the same unit. + */ + setFocalLength: function ( focalLength ) { - } + // see http://www.bobatkins.com/photography/technical/field_of_view.html + var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; -}; + this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); -// File:src/loaders/XHRLoader.js + }, -/** - * @author mrdoob / http://mrdoob.com/ - */ + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength: function () { -THREE.XHRLoader = function ( manager ) { + var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ); - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + return 0.5 * this.getFilmHeight() / vExtentSlope; -}; + }, -Object.assign( THREE.XHRLoader.prototype, { + getEffectiveFOV: function () { - load: function ( url, onLoad, onProgress, onError ) { + return exports.Math.RAD2DEG * 2 * Math.atan( + Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); - if ( this.path !== undefined ) url = this.path + url; + }, - var scope = this; + getFilmWidth: function () { - var cached = THREE.Cache.get( url ); + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); - if ( cached !== undefined ) { + }, - scope.manager.itemStart( url ); + getFilmHeight: function () { - setTimeout( function () { + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); - if ( onLoad ) onLoad( cached ); + }, - scope.manager.itemEnd( url ); + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and + * the monitors are in grid like this + * + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + * + * then for each monitor you would call it like this + * + * var w = 1920; + * var h = 1080; + * var fullWidth = w * 3; + * var fullHeight = h * 2; + * + * --A-- + * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * --B-- + * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * --C-- + * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * --D-- + * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * --E-- + * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * --F-- + * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * + * Note there is no reason monitors have to be the same size or in a grid. + */ + setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { - }, 0 ); + this.aspect = fullWidth / fullHeight; - return cached; + this.view = { + fullWidth: fullWidth, + fullHeight: fullHeight, + offsetX: x, + offsetY: y, + width: width, + height: height + }; - } + this.updateProjectionMatrix(); - var request = new XMLHttpRequest(); - request.overrideMimeType( 'text/plain' ); - request.open( 'GET', url, true ); + }, - request.addEventListener( 'load', function ( event ) { + clearViewOffset: function() { - var response = event.target.response; + this.view = null; + this.updateProjectionMatrix(); - THREE.Cache.add( url, response ); + }, - if ( this.status === 200 ) { + updateProjectionMatrix: function () { - if ( onLoad ) onLoad( response ); + var near = this.near, + top = near * Math.tan( + exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, + height = 2 * top, + width = this.aspect * height, + left = - 0.5 * width, + view = this.view; - scope.manager.itemEnd( url ); + if ( view !== null ) { - } else if ( this.status === 0 ) { + var fullWidth = view.fullWidth, + fullHeight = view.fullHeight; - // Some browsers return HTTP Status 0 when using non-http protocol - // e.g. 'file://' or 'data://'. Handle as success. + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; - console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' ); + } - if ( onLoad ) onLoad( response ); + var skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); - scope.manager.itemEnd( url ); + this.projectionMatrix.makeFrustum( + left, left + width, top - height, top, near, this.far ); - } else { + }, - if ( onError ) onError( event ); + toJSON: function ( meta ) { - scope.manager.itemError( url ); + var data = Object3D.prototype.toJSON.call( this, meta ); - } + data.object.fov = this.fov; + data.object.zoom = this.zoom; - }, false ); + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; - if ( onProgress !== undefined ) { + data.object.aspect = this.aspect; - request.addEventListener( 'progress', function ( event ) { + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - onProgress( event ); + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; - }, false ); + return data; - } + } - request.addEventListener( 'error', function ( event ) { + } ); - if ( onError ) onError( event ); + /** + * @author alteredq / http://alteredqualia.com/ + * @author arose / http://github.com/arose + */ - scope.manager.itemError( url ); + function OrthographicCamera ( left, right, top, bottom, near, far ) { + this.isOrthographicCamera = true; - }, false ); + Camera.call( this ); - if ( this.responseType !== undefined ) request.responseType = this.responseType; - if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; + this.type = 'OrthographicCamera'; - request.send( null ); + this.zoom = 1; + this.view = null; - scope.manager.itemStart( url ); + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; - return request; + this.near = ( near !== undefined ) ? near : 0.1; + this.far = ( far !== undefined ) ? far : 2000; - }, + this.updateProjectionMatrix(); - setPath: function ( value ) { + }; - this.path = value; - return this; + OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - }, + constructor: OrthographicCamera, - setResponseType: function ( value ) { + copy: function ( source ) { - this.responseType = value; - return this; + Camera.prototype.copy.call( this, source ); - }, + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; - setWithCredentials: function ( value ) { + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - this.withCredentials = value; - return this; + return this; - } + }, -} ); + setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) { -// File:src/loaders/FontLoader.js + this.view = { + fullWidth: fullWidth, + fullHeight: fullHeight, + offsetX: x, + offsetY: y, + width: width, + height: height + }; -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.updateProjectionMatrix(); -THREE.FontLoader = function ( manager ) { + }, - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + clearViewOffset: function() { -}; + this.view = null; + this.updateProjectionMatrix(); -Object.assign( THREE.FontLoader.prototype, { + }, - load: function ( url, onLoad, onProgress, onError ) { + updateProjectionMatrix: function () { - var scope = this; + var dx = ( this.right - this.left ) / ( 2 * this.zoom ); + var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + var cx = ( this.right + this.left ) / 2; + var cy = ( this.top + this.bottom ) / 2; - var loader = new THREE.XHRLoader( this.manager ); - loader.load( url, function ( text ) { + var left = cx - dx; + var right = cx + dx; + var top = cy + dy; + var bottom = cy - dy; - var json; + if ( this.view !== null ) { - try { + var zoomW = this.zoom / ( this.view.width / this.view.fullWidth ); + var zoomH = this.zoom / ( this.view.height / this.view.fullHeight ); + var scaleW = ( this.right - this.left ) / this.view.width; + var scaleH = ( this.top - this.bottom ) / this.view.height; - json = JSON.parse( text ); + left += scaleW * ( this.view.offsetX / zoomW ); + right = left + scaleW * ( this.view.width / zoomW ); + top -= scaleH * ( this.view.offsetY / zoomH ); + bottom = top - scaleH * ( this.view.height / zoomH ); - } catch ( e ) { + } - console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); - json = JSON.parse( text.substring( 65, text.length - 2 ) ); + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); - } + }, - var font = scope.parse( json ); + toJSON: function ( meta ) { - if ( onLoad ) onLoad( font ); + var data = Object3D.prototype.toJSON.call( this, meta ); - }, onProgress, onError ); + data.object.zoom = this.zoom; + data.object.left = this.left; + data.object.right = this.right; + data.object.top = this.top; + data.object.bottom = this.bottom; + data.object.near = this.near; + data.object.far = this.far; - }, + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - parse: function ( json ) { + return data; - return new THREE.Font( json ); + } - } + } ); -} ); + /** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + * @author tschw + */ -// File:src/loaders/ImageLoader.js + function WebGLRenderer ( parameters ) { + this.isWebGLRenderer = true; -/** - * @author mrdoob / http://mrdoob.com/ - */ + console.log( 'THREE.WebGLRenderer', "79dev" ); -THREE.ImageLoader = function ( manager ) { + parameters = parameters || {}; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), + _context = parameters.context !== undefined ? parameters.context : null, -}; + _alpha = parameters.alpha !== undefined ? parameters.alpha : false, + _depth = parameters.depth !== undefined ? parameters.depth : true, + _stencil = parameters.stencil !== undefined ? parameters.stencil : true, + _antialias = parameters.antialias !== undefined ? parameters.antialias : false, + _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, + _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false; -Object.assign( THREE.ImageLoader.prototype, { + var lights = []; - load: function ( url, onLoad, onProgress, onError ) { + var opaqueObjects = []; + var opaqueObjectsLastIndex = - 1; + var transparentObjects = []; + var transparentObjectsLastIndex = - 1; - var scope = this; + var morphInfluences = new Float32Array( 8 ); - var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); - image.onload = function () { + var sprites = []; + var lensFlares = []; - URL.revokeObjectURL( image.src ); + // public properties - if ( onLoad ) onLoad( image ); + this.domElement = _canvas; + this.context = null; - scope.manager.itemEnd( url ); + // clearing - }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - if ( url.indexOf( 'data:' ) === 0 ) { + // scene graph - image.src = url; + this.sortObjects = true; - } else { + // user-defined clipping - var loader = new THREE.XHRLoader(); - loader.setPath( this.path ); - loader.setResponseType( 'blob' ); - loader.load( url, function ( blob ) { + this.clippingPlanes = []; + this.localClippingEnabled = false; - image.src = URL.createObjectURL( blob ); + // physically based shading - }, onProgress, onError ); + this.gammaFactor = 2.0; // for backwards compatibility + this.gammaInput = false; + this.gammaOutput = false; - } + // physical lights - scope.manager.itemStart( url ); + this.physicallyCorrectLights = false; - return image; + // tone mapping - }, + this.toneMapping = LinearToneMapping; + this.toneMappingExposure = 1.0; + this.toneMappingWhitePoint = 1.0; - setCrossOrigin: function ( value ) { + // morphs - this.crossOrigin = value; - return this; + this.maxMorphTargets = 8; + this.maxMorphNormals = 4; - }, + // internal properties - setPath: function ( value ) { + var _this = this, - this.path = value; - return this; + // internal state cache - } + _currentProgram = null, + _currentRenderTarget = null, + _currentFramebuffer = null, + _currentMaterialId = - 1, + _currentGeometryProgram = '', + _currentCamera = null, -} ); + _currentScissor = new Vector4(), + _currentScissorTest = null, -// File:src/loaders/JSONLoader.js + _currentViewport = new Vector4(), -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + // -THREE.JSONLoader = function ( manager ) { + _usedTextureUnits = 0, - if ( typeof manager === 'boolean' ) { + // - console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); - manager = undefined; + _clearColor = new Color( 0x000000 ), + _clearAlpha = 0, - } + _width = _canvas.width, + _height = _canvas.height, - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + _pixelRatio = 1, - this.withCredentials = false; + _scissor = new Vector4( 0, 0, _width, _height ), + _scissorTest = false, -}; + _viewport = new Vector4( 0, 0, _width, _height ), -Object.assign( THREE.JSONLoader.prototype, { + // frustum - load: function( url, onLoad, onProgress, onError ) { + _frustum = new Frustum(), - var scope = this; + // clipping - var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url ); + _clipping = new WebGLClipping(), + _clippingEnabled = false, + _localClippingEnabled = false, - var loader = new THREE.XHRLoader( this.manager ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( text ) { + _sphere = new Sphere(), - var json = JSON.parse( text ); - var metadata = json.metadata; + // camera matrices cache - if ( metadata !== undefined ) { + _projScreenMatrix = new Matrix4(), - var type = metadata.type; + _vector3 = new Vector3(), - if ( type !== undefined ) { + // light arrays cache - if ( type.toLowerCase() === 'object' ) { + _lights = { - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); - return; + hash: '', - } + ambient: [ 0, 0, 0 ], + directional: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotShadowMap: [], + spotShadowMatrix: [], + point: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], - if ( type.toLowerCase() === 'scene' ) { + shadows: [] - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' ); - return; + }, - } + // info - } + _infoRender = { - } + calls: 0, + vertices: 0, + faces: 0, + points: 0 - var object = scope.parse( json, texturePath ); - onLoad( object.geometry, object.materials ); + }; - }, onProgress, onError ); + this.info = { - }, + render: _infoRender, + memory: { - setTexturePath: function ( value ) { + geometries: 0, + textures: 0 - this.texturePath = value; + }, + programs: null - }, + }; - parse: function ( json, texturePath ) { - var geometry = new THREE.Geometry(), - scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; + // initialize - parseModel( scale ); + var _gl; - parseSkin(); - parseMorphing( scale ); - parseAnimations(); + try { - geometry.computeFaceNormals(); - geometry.computeBoundingSphere(); + var attributes = { + alpha: _alpha, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer + }; - function parseModel( scale ) { + _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); - function isBitSet( value, position ) { + if ( _gl === null ) { - return value & ( 1 << position ); + if ( _canvas.getContext( 'webgl' ) !== null ) { - } + throw 'Error creating WebGL context with your selected attributes.'; - var i, j, fi, + } else { - offset, zLength, + throw 'Error creating WebGL context.'; - colorIndex, normalIndex, uvIndex, materialIndex, + } - type, - isQuad, - hasMaterial, - hasFaceVertexUv, - hasFaceNormal, hasFaceVertexNormal, - hasFaceColor, hasFaceVertexColor, + } - vertex, face, faceA, faceB, hex, normal, + // Some experimental-webgl implementations do not have getShaderPrecisionFormat - uvLayer, uv, u, v, + if ( _gl.getShaderPrecisionFormat === undefined ) { - faces = json.faces, - vertices = json.vertices, - normals = json.normals, - colors = json.colors, + _gl.getShaderPrecisionFormat = function () { - nUvLayers = 0; + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; - if ( json.uvs !== undefined ) { + }; - // disregard empty arrays + } - for ( i = 0; i < json.uvs.length; i ++ ) { + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); - if ( json.uvs[ i ].length ) nUvLayers ++; + } catch ( error ) { - } + console.error( 'THREE.WebGLRenderer: ' + error ); - for ( i = 0; i < nUvLayers; i ++ ) { + } - geometry.faceVertexUvs[ i ] = []; + var extensions = new WebGLExtensions( _gl ); - } + extensions.get( 'WEBGL_depth_texture' ); + extensions.get( 'OES_texture_float' ); + extensions.get( 'OES_texture_float_linear' ); + extensions.get( 'OES_texture_half_float' ); + extensions.get( 'OES_texture_half_float_linear' ); + extensions.get( 'OES_standard_derivatives' ); + extensions.get( 'ANGLE_instanced_arrays' ); - } + if ( extensions.get( 'OES_element_index_uint' ) ) { - offset = 0; - zLength = vertices.length; + BufferGeometry.MaxIndex = 4294967296; - while ( offset < zLength ) { + } - vertex = new THREE.Vector3(); + var capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - vertex.x = vertices[ offset ++ ] * scale; - vertex.y = vertices[ offset ++ ] * scale; - vertex.z = vertices[ offset ++ ] * scale; + var state = new WebGLState( _gl, extensions, paramThreeToGL ); + var properties = new WebGLProperties(); + var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info ); + var objects = new WebGLObjects( _gl, properties, this.info ); + var programCache = new WebGLPrograms( this, capabilities ); + var lightCache = new WebGLLights(); - geometry.vertices.push( vertex ); + this.info.programs = programCache.programs; - } + var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender ); + var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); - offset = 0; - zLength = faces.length; + // - while ( offset < zLength ) { + var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + var backgroundCamera2 = new PerspectiveCamera(); + var backgroundPlaneMesh = new Mesh( + new PlaneBufferGeometry( 2, 2 ), + new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) + ); + var backgroundBoxShader = exports.ShaderLib[ 'cube' ]; + var backgroundBoxMesh = new Mesh( + new BoxBufferGeometry( 5, 5, 5 ), + new ShaderMaterial( { + uniforms: backgroundBoxShader.uniforms, + vertexShader: backgroundBoxShader.vertexShader, + fragmentShader: backgroundBoxShader.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); - type = faces[ offset ++ ]; + // + function getTargetPixelRatio() { - isQuad = isBitSet( type, 0 ); - hasMaterial = isBitSet( type, 1 ); - hasFaceVertexUv = isBitSet( type, 3 ); - hasFaceNormal = isBitSet( type, 4 ); - hasFaceVertexNormal = isBitSet( type, 5 ); - hasFaceColor = isBitSet( type, 6 ); - hasFaceVertexColor = isBitSet( type, 7 ); + return _currentRenderTarget === null ? _pixelRatio : 1; - // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); + } - if ( isQuad ) { + function glClearColor( r, g, b, a ) { - faceA = new THREE.Face3(); - faceA.a = faces[ offset ]; - faceA.b = faces[ offset + 1 ]; - faceA.c = faces[ offset + 3 ]; + if ( _premultipliedAlpha === true ) { - faceB = new THREE.Face3(); - faceB.a = faces[ offset + 1 ]; - faceB.b = faces[ offset + 2 ]; - faceB.c = faces[ offset + 3 ]; + r *= a; g *= a; b *= a; - offset += 4; + } - if ( hasMaterial ) { + state.clearColor( r, g, b, a ); - materialIndex = faces[ offset ++ ]; - faceA.materialIndex = materialIndex; - faceB.materialIndex = materialIndex; + } - } + function setDefaultGLState() { - // to get face <=> uv index correspondence + state.init(); - fi = geometry.faces.length; + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); - if ( hasFaceVertexUv ) { + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - for ( i = 0; i < nUvLayers; i ++ ) { + } - uvLayer = json.uvs[ i ]; + function resetGLState() { - geometry.faceVertexUvs[ i ][ fi ] = []; - geometry.faceVertexUvs[ i ][ fi + 1 ] = []; + _currentProgram = null; + _currentCamera = null; - for ( j = 0; j < 4; j ++ ) { + _currentGeometryProgram = ''; + _currentMaterialId = - 1; - uvIndex = faces[ offset ++ ]; + state.reset(); - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + } - uv = new THREE.Vector2( u, v ); + setDefaultGLState(); - if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); - if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); + this.context = _gl; + this.capabilities = capabilities; + this.extensions = extensions; + this.properties = properties; + this.state = state; - } + // shadow map - } + var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities ); - } + this.shadowMap = shadowMap; - if ( hasFaceNormal ) { - normalIndex = faces[ offset ++ ] * 3; + // Plugins - faceA.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + var spritePlugin = new SpritePlugin( this, sprites ); + var lensFlarePlugin = new LensFlarePlugin( this, lensFlares ); - faceB.normal.copy( faceA.normal ); + // API - } + this.getContext = function () { - if ( hasFaceVertexNormal ) { + return _gl; - for ( i = 0; i < 4; i ++ ) { + }; - normalIndex = faces[ offset ++ ] * 3; + this.getContextAttributes = function () { - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + return _gl.getContextAttributes(); + }; - if ( i !== 2 ) faceA.vertexNormals.push( normal ); - if ( i !== 0 ) faceB.vertexNormals.push( normal ); + this.forceContextLoss = function () { - } + extensions.get( 'WEBGL_lose_context' ).loseContext(); - } + }; + this.getMaxAnisotropy = function () { - if ( hasFaceColor ) { + return capabilities.getMaxAnisotropy(); - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + }; - faceA.color.setHex( hex ); - faceB.color.setHex( hex ); + this.getPrecision = function () { - } + return capabilities.precision; + }; - if ( hasFaceVertexColor ) { + this.getPixelRatio = function () { - for ( i = 0; i < 4; i ++ ) { + return _pixelRatio; - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + }; - if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); - if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); + this.setPixelRatio = function ( value ) { - } + if ( value === undefined ) return; - } + _pixelRatio = value; - geometry.faces.push( faceA ); - geometry.faces.push( faceB ); + this.setSize( _viewport.z, _viewport.w, false ); - } else { + }; - face = new THREE.Face3(); - face.a = faces[ offset ++ ]; - face.b = faces[ offset ++ ]; - face.c = faces[ offset ++ ]; + this.getSize = function () { - if ( hasMaterial ) { + return { + width: _width, + height: _height + }; - materialIndex = faces[ offset ++ ]; - face.materialIndex = materialIndex; + }; - } + this.setSize = function ( width, height, updateStyle ) { - // to get face <=> uv index correspondence + _width = width; + _height = height; - fi = geometry.faces.length; + _canvas.width = width * _pixelRatio; + _canvas.height = height * _pixelRatio; - if ( hasFaceVertexUv ) { + if ( updateStyle !== false ) { - for ( i = 0; i < nUvLayers; i ++ ) { + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; - uvLayer = json.uvs[ i ]; + } - geometry.faceVertexUvs[ i ][ fi ] = []; + this.setViewport( 0, 0, width, height ); - for ( j = 0; j < 3; j ++ ) { + }; - uvIndex = faces[ offset ++ ]; + this.setViewport = function ( x, y, width, height ) { - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + state.viewport( _viewport.set( x, y, width, height ) ); - uv = new THREE.Vector2( u, v ); + }; - geometry.faceVertexUvs[ i ][ fi ].push( uv ); + this.setScissor = function ( x, y, width, height ) { - } + state.scissor( _scissor.set( x, y, width, height ) ); - } + }; - } + this.setScissorTest = function ( boolean ) { - if ( hasFaceNormal ) { + state.setScissorTest( _scissorTest = boolean ); - normalIndex = faces[ offset ++ ] * 3; + }; - face.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + // Clearing - } + this.getClearColor = function () { - if ( hasFaceVertexNormal ) { + return _clearColor; - for ( i = 0; i < 3; i ++ ) { + }; - normalIndex = faces[ offset ++ ] * 3; + this.setClearColor = function ( color, alpha ) { - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + _clearColor.set( color ); - face.vertexNormals.push( normal ); + _clearAlpha = alpha !== undefined ? alpha : 1; - } + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - } + }; + this.getClearAlpha = function () { - if ( hasFaceColor ) { + return _clearAlpha; - colorIndex = faces[ offset ++ ]; - face.color.setHex( colors[ colorIndex ] ); + }; - } + this.setClearAlpha = function ( alpha ) { + _clearAlpha = alpha; - if ( hasFaceVertexColor ) { + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - for ( i = 0; i < 3; i ++ ) { + }; - colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); + this.clear = function ( color, depth, stencil ) { - } + var bits = 0; - } + if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; + if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; + if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; - geometry.faces.push( face ); + _gl.clear( bits ); - } + }; - } + this.clearColor = function () { - } + this.clear( true, false, false ); - function parseSkin() { + }; - var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; + this.clearDepth = function () { - if ( json.skinWeights ) { + this.clear( false, true, false ); - for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { + }; - var x = json.skinWeights[ i ]; - var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; - var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; - var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; + this.clearStencil = function () { - geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) ); + this.clear( false, false, true ); - } + }; - } + this.clearTarget = function ( renderTarget, color, depth, stencil ) { - if ( json.skinIndices ) { + this.setRenderTarget( renderTarget ); + this.clear( color, depth, stencil ); - for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { + }; - var a = json.skinIndices[ i ]; - var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; - var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; - var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; + // Reset - geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) ); + this.resetGLState = resetGLState; - } + this.dispose = function() { - } + transparentObjects = []; + transparentObjectsLastIndex = -1; + opaqueObjects = []; + opaqueObjectsLastIndex = -1; - geometry.bones = json.bones; + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); - if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { + }; - console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + - geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); + // Events - } + function onContextLost( event ) { - } + event.preventDefault(); - function parseMorphing( scale ) { + resetGLState(); + setDefaultGLState(); - if ( json.morphTargets !== undefined ) { + properties.clear(); - for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) { + } - geometry.morphTargets[ i ] = {}; - geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; - geometry.morphTargets[ i ].vertices = []; + function onMaterialDispose( event ) { - var dstVertices = geometry.morphTargets[ i ].vertices; - var srcVertices = json.morphTargets[ i ].vertices; + var material = event.target; - for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) { + material.removeEventListener( 'dispose', onMaterialDispose ); - var vertex = new THREE.Vector3(); - vertex.x = srcVertices[ v ] * scale; - vertex.y = srcVertices[ v + 1 ] * scale; - vertex.z = srcVertices[ v + 2 ] * scale; + deallocateMaterial( material ); - dstVertices.push( vertex ); + } - } + // Buffer deallocation - } + function deallocateMaterial( material ) { - } + releaseMaterialProgramReference( material ); - if ( json.morphColors !== undefined && json.morphColors.length > 0 ) { + properties.delete( material ); - console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' ); + } - var faces = geometry.faces; - var morphColors = json.morphColors[ 0 ].colors; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + function releaseMaterialProgramReference( material ) { - faces[ i ].color.fromArray( morphColors, i * 3 ); + var programInfo = properties.get( material ).program; - } + material.program = undefined; - } + if ( programInfo !== undefined ) { - } + programCache.releaseProgram( programInfo ); - function parseAnimations() { + } - var outputAnimations = []; + } - // parse old style Bone/Hierarchy animations - var animations = []; + // Buffer rendering - if ( json.animation !== undefined ) { + this.renderBufferImmediate = function ( object, program, material ) { - animations.push( json.animation ); + state.initAttributes(); - } + var buffers = properties.get( object ); - if ( json.animations !== undefined ) { + if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); + if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); + if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); + if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); - if ( json.animations.length ) { + var attributes = program.getAttributes(); - animations = animations.concat( json.animations ); + if ( object.hasPositions ) { - } else { + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); - animations.push( json.animations ); + state.enableAttribute( attributes.position ); + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - } + } - } + if ( object.hasNormals ) { - for ( var i = 0; i < animations.length; i ++ ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); - var clip = THREE.AnimationClip.parseAnimation( animations[ i ], geometry.bones ); - if ( clip ) outputAnimations.push( clip ); + if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === FlatShading ) { - } + for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { - // parse implicit morph animations - if ( geometry.morphTargets ) { + var array = object.normalArray; - // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary. - var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); - outputAnimations = outputAnimations.concat( morphAnimationClips ); + var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3; + var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3; + var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3; - } + array[ i + 0 ] = nx; + array[ i + 1 ] = ny; + array[ i + 2 ] = nz; - if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations; + array[ i + 3 ] = nx; + array[ i + 4 ] = ny; + array[ i + 5 ] = nz; - } + array[ i + 6 ] = nx; + array[ i + 7 ] = ny; + array[ i + 8 ] = nz; - if ( json.materials === undefined || json.materials.length === 0 ) { + } - return { geometry: geometry }; + } - } else { + _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); - var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); + state.enableAttribute( attributes.normal ); - return { geometry: geometry, materials: materials }; + _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); - } + } - } + if ( object.hasUvs && material.map ) { -} ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); -// File:src/loaders/LoadingManager.js + state.enableAttribute( attributes.uv ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); -THREE.LoadingManager = function ( onLoad, onProgress, onError ) { + } - var scope = this; + if ( object.hasColors && material.vertexColors !== NoColors ) { - var isLoading = false, itemsLoaded = 0, itemsTotal = 0; + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); - this.onStart = undefined; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + state.enableAttribute( attributes.color ); - this.itemStart = function ( url ) { + _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); - itemsTotal ++; + } - if ( isLoading === false ) { + state.disableUnusedAttributes(); - if ( scope.onStart !== undefined ) { + _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); - scope.onStart( url, itemsLoaded, itemsTotal ); + object.count = 0; - } + }; - } + this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { - isLoading = true; + setMaterial( material ); - }; + var program = setProgram( camera, fog, material, object ); - this.itemEnd = function ( url ) { + var updateBuffers = false; + var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe; - itemsLoaded ++; + if ( geometryProgram !== _currentGeometryProgram ) { - if ( scope.onProgress !== undefined ) { + _currentGeometryProgram = geometryProgram; + updateBuffers = true; - scope.onProgress( url, itemsLoaded, itemsTotal ); + } - } + // morph targets - if ( itemsLoaded === itemsTotal ) { + var morphTargetInfluences = object.morphTargetInfluences; - isLoading = false; + if ( morphTargetInfluences !== undefined ) { - if ( scope.onLoad !== undefined ) { + var activeInfluences = []; - scope.onLoad(); + for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { - } + var influence = morphTargetInfluences[ i ]; + activeInfluences.push( [ influence, i ] ); - } + } - }; + activeInfluences.sort( absNumericalSort ); - this.itemError = function ( url ) { + if ( activeInfluences.length > 8 ) { - if ( scope.onError !== undefined ) { + activeInfluences.length = 8; - scope.onError( url ); + } - } + var morphAttributes = geometry.morphAttributes; - }; + for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { -}; + var influence = activeInfluences[ i ]; + morphInfluences[ i ] = influence[ 0 ]; -THREE.DefaultLoadingManager = new THREE.LoadingManager(); + if ( influence[ 0 ] !== 0 ) { -// File:src/loaders/BufferGeometryLoader.js + var index = influence[ 1 ]; -/** - * @author mrdoob / http://mrdoob.com/ - */ + if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] ); + if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] ); -THREE.BufferGeometryLoader = function ( manager ) { + } else { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); + if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); -}; + } -Object.assign( THREE.BufferGeometryLoader.prototype, { + } - load: function ( url, onLoad, onProgress, onError ) { + program.getUniforms().setValue( + _gl, 'morphTargetInfluences', morphInfluences ); - var scope = this; + updateBuffers = true; - var loader = new THREE.XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + } - onLoad( scope.parse( JSON.parse( text ) ) ); + // - }, onProgress, onError ); + var index = geometry.index; + var position = geometry.attributes.position; - }, + if ( material.wireframe === true ) { - parse: function ( json ) { + index = objects.getWireframeAttribute( geometry ); - var geometry = new THREE.BufferGeometry(); + } - var index = json.data.index; + var renderer; - var TYPED_ARRAYS = { - 'Int8Array': Int8Array, - 'Uint8Array': Uint8Array, - 'Uint8ClampedArray': Uint8ClampedArray, - 'Int16Array': Int16Array, - 'Uint16Array': Uint16Array, - 'Int32Array': Int32Array, - 'Uint32Array': Uint32Array, - 'Float32Array': Float32Array, - 'Float64Array': Float64Array - }; + if ( index !== null ) { - if ( index !== undefined ) { + renderer = indexedBufferRenderer; + renderer.setIndex( index ); - var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); - geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) ); + } else { - } + renderer = bufferRenderer; - var attributes = json.data.attributes; + } - for ( var key in attributes ) { + if ( updateBuffers ) { - var attribute = attributes[ key ]; - var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); + setupVertexAttributes( material, program, geometry ); - geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); + if ( index !== null ) { - } + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) ); - var groups = json.data.groups || json.data.drawcalls || json.data.offsets; + } - if ( groups !== undefined ) { + } - for ( var i = 0, n = groups.length; i !== n; ++ i ) { + // - var group = groups[ i ]; + var dataStart = 0; + var dataCount = Infinity; - geometry.addGroup( group.start, group.count, group.materialIndex ); + if ( index !== null ) { - } + dataCount = index.count; - } + } else if ( position !== undefined ) { - var boundingSphere = json.data.boundingSphere; + dataCount = position.count; - if ( boundingSphere !== undefined ) { + } - var center = new THREE.Vector3(); + var rangeStart = geometry.drawRange.start; + var rangeCount = geometry.drawRange.count; - if ( boundingSphere.center !== undefined ) { + var groupStart = group !== null ? group.start : 0; + var groupCount = group !== null ? group.count : Infinity; - center.fromArray( boundingSphere.center ); + var drawStart = Math.max( dataStart, rangeStart, groupStart ); + var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; - } + var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); - geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius ); + // - } + if ( (object && object.isMesh) ) { - return geometry; + if ( material.wireframe === true ) { - } + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); -} ); + } else { -// File:src/loaders/MaterialLoader.js + switch ( object.drawMode ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + case TrianglesDrawMode: + renderer.setMode( _gl.TRIANGLES ); + break; -THREE.MaterialLoader = function ( manager ) { + case TriangleStripDrawMode: + renderer.setMode( _gl.TRIANGLE_STRIP ); + break; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - this.textures = {}; + case TriangleFanDrawMode: + renderer.setMode( _gl.TRIANGLE_FAN ); + break; -}; + } -Object.assign( THREE.MaterialLoader.prototype, { + } - load: function ( url, onLoad, onProgress, onError ) { - var scope = this; + } else if ( (object && object.isLine) ) { - var loader = new THREE.XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + var lineWidth = material.linewidth; - onLoad( scope.parse( JSON.parse( text ) ) ); + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material - }, onProgress, onError ); + state.setLineWidth( lineWidth * getTargetPixelRatio() ); - }, + if ( (object && object.isLineSegments) ) { - setTextures: function ( value ) { + renderer.setMode( _gl.LINES ); - this.textures = value; + } else { - }, + renderer.setMode( _gl.LINE_STRIP ); - getTexture: function ( name ) { + } - var textures = this.textures; + } else if ( (object && object.isPoints) ) { - if ( textures[ name ] === undefined ) { + renderer.setMode( _gl.POINTS ); - console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + } - } + if ( (geometry && geometry.isInstancedBufferGeometry) ) { - return textures[ name ]; + if ( geometry.maxInstancedCount > 0 ) { - }, + renderer.renderInstances( geometry, drawStart, drawCount ); - parse: function ( json ) { - - var material = new THREE[ json.type ]; - - if ( json.uuid !== undefined ) material.uuid = json.uuid; - if ( json.name !== undefined ) material.name = json.name; - if ( json.color !== undefined ) material.color.setHex( json.color ); - if ( json.roughness !== undefined ) material.roughness = json.roughness; - if ( json.metalness !== undefined ) material.metalness = json.metalness; - if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); - if ( json.specular !== undefined ) material.specular.setHex( json.specular ); - if ( json.shininess !== undefined ) material.shininess = json.shininess; - if ( json.uniforms !== undefined ) material.uniforms = json.uniforms; - if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; - if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; - if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; - if ( json.shading !== undefined ) material.shading = json.shading; - if ( json.blending !== undefined ) material.blending = json.blending; - if ( json.side !== undefined ) material.side = json.side; - if ( json.opacity !== undefined ) material.opacity = json.opacity; - if ( json.transparent !== undefined ) material.transparent = json.transparent; - if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest; - if ( json.depthTest !== undefined ) material.depthTest = json.depthTest; - if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite; - if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite; - if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; - if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; - - // for PointsMaterial - if ( json.size !== undefined ) material.size = json.size; - if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; - - // maps - - if ( json.map !== undefined ) material.map = this.getTexture( json.map ); - - if ( json.alphaMap !== undefined ) { - - material.alphaMap = this.getTexture( json.alphaMap ); - material.transparent = true; + } - } + } else { - if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap ); - if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; + renderer.render( drawStart, drawCount ); - if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap ); - if ( json.normalScale !== undefined ) { + } - var normalScale = json.normalScale; + }; - if ( Array.isArray( normalScale ) === false ) { + function setupVertexAttributes( material, program, geometry, startIndex ) { - // Blender exporter used to export a scalar. See #7459 + var extension; - normalScale = [ normalScale, normalScale ]; + if ( (geometry && geometry.isInstancedBufferGeometry) ) { - } + extension = extensions.get( 'ANGLE_instanced_arrays' ); - material.normalScale = new THREE.Vector2().fromArray( normalScale ); + if ( extension === null ) { - } + console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap ); - if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; - if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; + } - if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap ); - if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap ); + } - if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap ); - if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; + if ( startIndex === undefined ) startIndex = 0; - if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap ); + state.initAttributes(); - if ( json.envMap !== undefined ) { + var geometryAttributes = geometry.attributes; - material.envMap = this.getTexture( json.envMap ); - material.combine = THREE.MultiplyOperation; + var programAttributes = program.getAttributes(); - } + var materialDefaultAttributeValues = material.defaultAttributeValues; - if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + for ( var name in programAttributes ) { - if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap ); - if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + var programAttribute = programAttributes[ name ]; - if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap ); - if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + if ( programAttribute >= 0 ) { - // MultiMaterial + var geometryAttribute = geometryAttributes[ name ]; - if ( json.materials !== undefined ) { + if ( geometryAttribute !== undefined ) { - for ( var i = 0, l = json.materials.length; i < l; i ++ ) { + var type = _gl.FLOAT; + var array = geometryAttribute.array; + var normalized = geometryAttribute.normalized; - material.materials.push( this.parse( json.materials[ i ] ) ); + if ( array instanceof Float32Array ) { - } + type = _gl.FLOAT; - } + } else if ( array instanceof Float64Array ) { - return material; + console.warn("Unsupported data buffer format: Float64Array"); - } + } else if ( array instanceof Uint16Array ) { -} ); + type = _gl.UNSIGNED_SHORT; -// File:src/loaders/ObjectLoader.js + } else if ( array instanceof Int16Array ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + type = _gl.SHORT; -THREE.ObjectLoader = function ( manager ) { + } else if ( array instanceof Uint32Array ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - this.texturePath = ''; + type = _gl.UNSIGNED_INT; -}; + } else if ( array instanceof Int32Array ) { -Object.assign( THREE.ObjectLoader.prototype, { + type = _gl.INT; - load: function ( url, onLoad, onProgress, onError ) { + } else if ( array instanceof Int8Array ) { - if ( this.texturePath === '' ) { + type = _gl.BYTE; - this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); + } else if ( array instanceof Uint8Array ) { - } + type = _gl.UNSIGNED_BYTE; - var scope = this; + } - var loader = new THREE.XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + var size = geometryAttribute.itemSize; + var buffer = objects.getAttributeBuffer( geometryAttribute ); - scope.parse( JSON.parse( text ), onLoad ); + if ( (geometryAttribute && geometryAttribute.isInterleavedBufferAttribute) ) { - }, onProgress, onError ); + var data = geometryAttribute.data; + var stride = data.stride; + var offset = geometryAttribute.offset; - }, + if ( (data && data.isInstancedInterleavedBuffer) ) { - setTexturePath: function ( value ) { + state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); - this.texturePath = value; + if ( geometry.maxInstancedCount === undefined ) { - }, + geometry.maxInstancedCount = data.meshPerAttribute * data.count; - setCrossOrigin: function ( value ) { + } - this.crossOrigin = value; + } else { - }, + state.enableAttribute( programAttribute ); - parse: function ( json, onLoad ) { + } - var geometries = this.parseGeometries( json.geometries ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); + _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT ); - var images = this.parseImages( json.images, function () { + } else { - if ( onLoad !== undefined ) onLoad( object ); + if ( (geometryAttribute && geometryAttribute.isInstancedBufferAttribute) ) { - } ); + state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); - var textures = this.parseTextures( json.textures, images ); - var materials = this.parseMaterials( json.materials, textures ); + if ( geometry.maxInstancedCount === undefined ) { - var object = this.parseObject( json.object, geometries, materials ); + geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; - if ( json.animations ) { + } - object.animations = this.parseAnimations( json.animations ); + } else { - } + state.enableAttribute( programAttribute ); - if ( json.images === undefined || json.images.length === 0 ) { + } - if ( onLoad !== undefined ) onLoad( object ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); + _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT ); - } + } - return object; + } else if ( materialDefaultAttributeValues !== undefined ) { - }, + var value = materialDefaultAttributeValues[ name ]; - parseGeometries: function ( json ) { + if ( value !== undefined ) { - var geometries = {}; + switch ( value.length ) { - if ( json !== undefined ) { + case 2: + _gl.vertexAttrib2fv( programAttribute, value ); + break; - var geometryLoader = new THREE.JSONLoader(); - var bufferGeometryLoader = new THREE.BufferGeometryLoader(); + case 3: + _gl.vertexAttrib3fv( programAttribute, value ); + break; - for ( var i = 0, l = json.length; i < l; i ++ ) { + case 4: + _gl.vertexAttrib4fv( programAttribute, value ); + break; - var geometry; - var data = json[ i ]; + default: + _gl.vertexAttrib1fv( programAttribute, value ); - switch ( data.type ) { + } - case 'PlaneGeometry': - case 'PlaneBufferGeometry': + } - geometry = new THREE[ data.type ]( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + } - break; + } - case 'BoxGeometry': - case 'BoxBufferGeometry': - case 'CubeGeometry': // backwards compatible + } - geometry = new THREE[ data.type ]( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + state.disableUnusedAttributes(); - break; + } - case 'CircleGeometry': - case 'CircleBufferGeometry': + // Sorting - geometry = new THREE[ data.type ]( - data.radius, - data.segments, - data.thetaStart, - data.thetaLength - ); - - break; - - case 'CylinderGeometry': - case 'CylinderBufferGeometry': + function absNumericalSort( a, b ) { - geometry = new THREE[ data.type ]( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] ); - break; + } - case 'ConeGeometry': - case 'ConeBufferGeometry': + function painterSortStable ( a, b ) { - geometry = new THREE [ data.type ]( - data.radius, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + if ( a.object.renderOrder !== b.object.renderOrder ) { - break; + return a.object.renderOrder - b.object.renderOrder; - case 'SphereGeometry': - case 'SphereBufferGeometry': + } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) { - geometry = new THREE[ data.type ]( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + return a.material.program.id - b.material.program.id; - break; + } else if ( a.material.id !== b.material.id ) { - case 'DodecahedronGeometry': - case 'IcosahedronGeometry': - case 'OctahedronGeometry': - case 'TetrahedronGeometry': + return a.material.id - b.material.id; - geometry = new THREE[ data.type ]( - data.radius, - data.detail - ); + } else if ( a.z !== b.z ) { - break; + return a.z - b.z; - case 'RingGeometry': - case 'RingBufferGeometry': + } else { - geometry = new THREE[ data.type ]( - data.innerRadius, - data.outerRadius, - data.thetaSegments, - data.phiSegments, - data.thetaStart, - data.thetaLength - ); + return a.id - b.id; - break; + } - case 'TorusGeometry': - case 'TorusBufferGeometry': + } - geometry = new THREE[ data.type ]( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + function reversePainterSortStable ( a, b ) { - break; + if ( a.object.renderOrder !== b.object.renderOrder ) { - case 'TorusKnotGeometry': - case 'TorusKnotBufferGeometry': + return a.object.renderOrder - b.object.renderOrder; - geometry = new THREE[ data.type ]( - data.radius, - data.tube, - data.tubularSegments, - data.radialSegments, - data.p, - data.q - ); + } if ( a.z !== b.z ) { - break; + return b.z - a.z; - case 'LatheGeometry': - case 'LatheBufferGeometry': + } else { - geometry = new THREE[ data.type ]( - data.points, - data.segments, - data.phiStart, - data.phiLength - ); + return a.id - b.id; - break; + } - case 'BufferGeometry': + } - geometry = bufferGeometryLoader.parse( data ); + // Rendering - break; + this.render = function ( scene, camera, renderTarget, forceClear ) { - case 'Geometry': + if ( (camera && camera.isCamera) === false ) { - geometry = geometryLoader.parse( data.data, this.texturePath ).geometry; + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; - break; + } - default: + var fog = scene.fog; - console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); + // reset caching for this frame - continue; + _currentGeometryProgram = ''; + _currentMaterialId = - 1; + _currentCamera = null; - } + // update scene graph - geometry.uuid = data.uuid; + if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - if ( data.name !== undefined ) geometry.name = data.name; + // update camera matrices and frustum - geometries[ data.uuid ] = geometry; + if ( camera.parent === null ) camera.updateMatrixWorld(); - } + camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - } + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - return geometries; + lights.length = 0; - }, + opaqueObjectsLastIndex = - 1; + transparentObjectsLastIndex = - 1; - parseMaterials: function ( json, textures ) { + sprites.length = 0; + lensFlares.length = 0; - var materials = {}; + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); - if ( json !== undefined ) { + projectObject( scene, camera ); - var loader = new THREE.MaterialLoader(); - loader.setTextures( textures ); + opaqueObjects.length = opaqueObjectsLastIndex + 1; + transparentObjects.length = transparentObjectsLastIndex + 1; - for ( var i = 0, l = json.length; i < l; i ++ ) { + if ( _this.sortObjects === true ) { - var material = loader.parse( json[ i ] ); - materials[ material.uuid ] = material; + opaqueObjects.sort( painterSortStable ); + transparentObjects.sort( reversePainterSortStable ); - } + } - } + // - return materials; + if ( _clippingEnabled ) _clipping.beginShadows(); - }, + setupShadows( lights ); - parseAnimations: function ( json ) { + shadowMap.render( scene, camera ); - var animations = []; + setupLights( lights, camera ); - for ( var i = 0; i < json.length; i ++ ) { + if ( _clippingEnabled ) _clipping.endShadows(); - var clip = THREE.AnimationClip.parse( json[ i ] ); + // - animations.push( clip ); + _infoRender.calls = 0; + _infoRender.vertices = 0; + _infoRender.faces = 0; + _infoRender.points = 0; - } + if ( renderTarget === undefined ) { - return animations; + renderTarget = null; - }, + } - parseImages: function ( json, onLoad ) { + this.setRenderTarget( renderTarget ); - var scope = this; - var images = {}; + // - function loadImage( url ) { + var background = scene.background; - scope.manager.itemStart( url ); + if ( background === null ) { - return loader.load( url, function () { + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - scope.manager.itemEnd( url ); + } else if ( (background && background.isColor) ) { - } ); + glClearColor( background.r, background.g, background.b, 1 ); - } + } - if ( json !== undefined && json.length > 0 ) { + if ( this.autoClear || forceClear ) { - var manager = new THREE.LoadingManager( onLoad ); + this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); - var loader = new THREE.ImageLoader( manager ); - loader.setCrossOrigin( this.crossOrigin ); + } - for ( var i = 0, l = json.length; i < l; i ++ ) { + if ( (background && background.isCubeTexture) ) { - var image = json[ i ]; - var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; + backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); - images[ image.uuid ] = loadImage( path ); + backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld ); + backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld ); - } + backgroundBoxMesh.material.uniforms[ "tCube" ].value = background; + backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld ); - } + objects.update( backgroundBoxMesh ); - return images; + _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); - }, + } else if ( (background && background.isTexture) ) { - parseTextures: function ( json, images ) { + backgroundPlaneMesh.material.map = background; - function parseConstant( value ) { + objects.update( backgroundPlaneMesh ); - if ( typeof( value ) === 'number' ) return value; + _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null ); - console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + } - return THREE[ value ]; + // - } + if ( scene.overrideMaterial ) { - var textures = {}; + var overrideMaterial = scene.overrideMaterial; - if ( json !== undefined ) { + renderObjects( opaqueObjects, camera, fog, overrideMaterial ); + renderObjects( transparentObjects, camera, fog, overrideMaterial ); - for ( var i = 0, l = json.length; i < l; i ++ ) { + } else { - var data = json[ i ]; + // opaque pass (front-to-back order) - if ( data.image === undefined ) { + state.setBlending( NoBlending ); + renderObjects( opaqueObjects, camera, fog ); - console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + // transparent pass (back-to-front order) - } + renderObjects( transparentObjects, camera, fog ); - if ( images[ data.image ] === undefined ) { + } - console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + // custom render plugins (post pass) - } + spritePlugin.render( scene, camera ); + lensFlarePlugin.render( scene, camera, _currentViewport ); - var texture = new THREE.Texture( images[ data.image ] ); - texture.needsUpdate = true; + // Generate mipmap if we're using any kind of mipmap filtering - texture.uuid = data.uuid; + if ( renderTarget ) { - if ( data.name !== undefined ) texture.name = data.name; + textures.updateRenderTargetMipmap( renderTarget ); - if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping ); + } - if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); - if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); - if ( data.wrap !== undefined ) { + // Ensure depth buffer writing is enabled so it can be cleared on next render - texture.wrapS = parseConstant( data.wrap[ 0 ] ); - texture.wrapT = parseConstant( data.wrap[ 1 ] ); + state.setDepthTest( true ); + state.setDepthWrite( true ); + state.setColorWrite( true ); - } + // _gl.finish(); - if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter ); - if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter ); - if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + }; - if ( data.flipY !== undefined ) texture.flipY = data.flipY; + function pushRenderItem( object, geometry, material, z, group ) { - textures[ data.uuid ] = texture; + var array, index; - } + // allocate the next position in the appropriate array - } + if ( material.transparent ) { - return textures; + array = transparentObjects; + index = ++ transparentObjectsLastIndex; - }, + } else { - parseObject: function () { + array = opaqueObjects; + index = ++ opaqueObjectsLastIndex; - var matrix = new THREE.Matrix4(); + } - return function parseObject( data, geometries, materials ) { + // recycle existing render item or grow the array - var object; + var renderItem = array[ index ]; - function getGeometry( name ) { + if ( renderItem !== undefined ) { - if ( geometries[ name ] === undefined ) { + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.z = _vector3.z; + renderItem.group = group; - console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + } else { - } + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + z: _vector3.z, + group: group + }; - return geometries[ name ]; + // assert( index === array.length ); + array.push( renderItem ); - } + } - function getMaterial( name ) { + } - if ( name === undefined ) return undefined; + // TODO Duplicated code (Frustum) - if ( materials[ name ] === undefined ) { + function isObjectViewable( object ) { - console.warn( 'THREE.ObjectLoader: Undefined material', name ); + var geometry = object.geometry; - } + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); - return materials[ name ]; + _sphere.copy( geometry.boundingSphere ). + applyMatrix4( object.matrixWorld ); - } + return isSphereViewable( _sphere ); - switch ( data.type ) { + } - case 'Scene': + function isSpriteViewable( sprite ) { - object = new THREE.Scene(); + _sphere.center.set( 0, 0, 0 ); + _sphere.radius = 0.7071067811865476; + _sphere.applyMatrix4( sprite.matrixWorld ); - break; + return isSphereViewable( _sphere ); - case 'PerspectiveCamera': + } - object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + function isSphereViewable( sphere ) { - if ( data.focus !== undefined ) object.focus = data.focus; - if ( data.zoom !== undefined ) object.zoom = data.zoom; - if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge; - if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset; - if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); + if ( ! _frustum.intersectsSphere( sphere ) ) return false; - break; + var numPlanes = _clipping.numPlanes; - case 'OrthographicCamera': + if ( numPlanes === 0 ) return true; - object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + var planes = _this.clippingPlanes, - break; + center = sphere.center, + negRad = - sphere.radius, + i = 0; - case 'AmbientLight': + do { - object = new THREE.AmbientLight( data.color, data.intensity ); + // out when deeper than radius in the negative halfspace + if ( planes[ i ].distanceToPoint( center ) < negRad ) return false; - break; + } while ( ++ i !== numPlanes ); - case 'DirectionalLight': + return true; - object = new THREE.DirectionalLight( data.color, data.intensity ); + } - break; + function projectObject( object, camera ) { - case 'PointLight': + if ( object.visible === false ) return; - object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay ); + if ( object.layers.test( camera.layers ) ) { - break; + if ( (object && object.isLight) ) { - case 'SpotLight': + lights.push( object ); - object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + } else if ( (object && object.isSprite) ) { - break; + if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) { - case 'HemisphereLight': + sprites.push( object ); - object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); + } - break; + } else if ( (object && object.isLensFlare) ) { - case 'Mesh': + lensFlares.push( object ); - var geometry = getGeometry( data.geometry ); - var material = getMaterial( data.material ); + } else if ( (object && object.isImmediateRenderObject) ) { - if ( geometry.bones && geometry.bones.length > 0 ) { + if ( _this.sortObjects === true ) { - object = new THREE.SkinnedMesh( geometry, material ); + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _projScreenMatrix ); - } else { + } - object = new THREE.Mesh( geometry, material ); + pushRenderItem( object, null, object.material, _vector3.z, null ); - } + } else if ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) { - break; + if ( (object && object.isSkinnedMesh) ) { - case 'LOD': + object.skeleton.update(); - object = new THREE.LOD(); + } - break; + if ( object.frustumCulled === false || isObjectViewable( object ) === true ) { - case 'Line': + var material = object.material; - object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); + if ( material.visible === true ) { - break; + if ( _this.sortObjects === true ) { - case 'PointCloud': - case 'Points': + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _projScreenMatrix ); - object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + } - break; + var geometry = objects.update( object ); - case 'Sprite': + if ( (material && material.isMultiMaterial) ) { - object = new THREE.Sprite( getMaterial( data.material ) ); + var groups = geometry.groups; + var materials = material.materials; - break; + for ( var i = 0, l = groups.length; i < l; i ++ ) { - case 'Group': + var group = groups[ i ]; + var groupMaterial = materials[ group.materialIndex ]; - object = new THREE.Group(); + if ( groupMaterial.visible === true ) { - break; + pushRenderItem( object, geometry, groupMaterial, _vector3.z, group ); - default: + } - object = new THREE.Object3D(); + } - } + } else { - object.uuid = data.uuid; + pushRenderItem( object, geometry, material, _vector3.z, null ); - if ( data.name !== undefined ) object.name = data.name; - if ( data.matrix !== undefined ) { + } - matrix.fromArray( data.matrix ); - matrix.decompose( object.position, object.quaternion, object.scale ); + } - } else { + } - if ( data.position !== undefined ) object.position.fromArray( data.position ); - if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); - if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); + } - } + } - if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; - if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; + var children = object.children; - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.userData !== undefined ) object.userData = data.userData; + for ( var i = 0, l = children.length; i < l; i ++ ) { - if ( data.children !== undefined ) { + projectObject( children[ i ], camera ); - for ( var child in data.children ) { + } - object.add( this.parseObject( data.children[ child ], geometries, materials ) ); + } - } + function renderObjects( renderList, camera, fog, overrideMaterial ) { - } + for ( var i = 0, l = renderList.length; i < l; i ++ ) { - if ( data.type === 'LOD' ) { + var renderItem = renderList[ i ]; - var levels = data.levels; + var object = renderItem.object; + var geometry = renderItem.geometry; + var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; + var group = renderItem.group; - for ( var l = 0; l < levels.length; l ++ ) { + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); - var level = levels[ l ]; - var child = object.getObjectByProperty( 'uuid', level.object ); + if ( (object && object.isImmediateRenderObject) ) { - if ( child !== undefined ) { + setMaterial( material ); - object.addLevel( child, level.distance ); + var program = setProgram( camera, fog, material, object ); - } + _currentGeometryProgram = ''; - } + object.render( function ( object ) { - } + _this.renderBufferImmediate( object, program, material ); - return object; + } ); - }; + } else { - }() + _this.renderBufferDirect( camera, fog, geometry, material, object, group ); -} ); + } -// File:src/loaders/TextureLoader.js + } -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.TextureLoader = function ( manager ) { + function initMaterial( material, fog, object ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + var materialProperties = properties.get( material ); -}; + var parameters = programCache.getParameters( + material, _lights, fog, _clipping.numPlanes, object ); -Object.assign( THREE.TextureLoader.prototype, { + var code = programCache.getProgramCode( material, parameters ); - load: function ( url, onLoad, onProgress, onError ) { + var program = materialProperties.program; + var programChange = true; - var texture = new THREE.Texture(); + if ( program === undefined ) { - var loader = new THREE.ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); - loader.load( url, function ( image ) { + // new material + material.addEventListener( 'dispose', onMaterialDispose ); - // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. - var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; + } else if ( program.code !== code ) { - texture.format = isJPEG ? THREE.RGBFormat : THREE.RGBAFormat; - texture.image = image; - texture.needsUpdate = true; + // changed glsl or parameters + releaseMaterialProgramReference( material ); - if ( onLoad !== undefined ) { + } else if ( parameters.shaderID !== undefined ) { - onLoad( texture ); + // same glsl and uniform list + return; - } + } else { - }, onProgress, onError ); + // only rebuild uniform list + programChange = false; - return texture; + } - }, + if ( programChange ) { - setCrossOrigin: function ( value ) { + if ( parameters.shaderID ) { - this.crossOrigin = value; - return this; + var shader = exports.ShaderLib[ parameters.shaderID ]; - }, + materialProperties.__webglShader = { + name: material.type, + uniforms: exports.UniformsUtils.clone( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader + }; - setPath: function ( value ) { + } else { - this.path = value; - return this; + materialProperties.__webglShader = { + name: material.type, + uniforms: material.uniforms, + vertexShader: material.vertexShader, + fragmentShader: material.fragmentShader + }; - } + } -} ); + material.__webglShader = materialProperties.__webglShader; -// File:src/loaders/CubeTextureLoader.js + program = programCache.acquireProgram( material, parameters, code ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + materialProperties.program = program; + material.program = program; -THREE.CubeTextureLoader = function ( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + var attributes = program.getAttributes(); -}; + if ( material.morphTargets ) { -Object.assign( THREE.CubeTextureLoader.prototype, { + material.numSupportedMorphTargets = 0; - load: function ( urls, onLoad, onProgress, onError ) { + for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { - var texture = new THREE.CubeTexture(); + if ( attributes[ 'morphTarget' + i ] >= 0 ) { - var loader = new THREE.ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + material.numSupportedMorphTargets ++; - var loaded = 0; + } - function loadTexture( i ) { + } - loader.load( urls[ i ], function ( image ) { + } - texture.images[ i ] = image; + if ( material.morphNormals ) { - loaded ++; + material.numSupportedMorphNormals = 0; - if ( loaded === 6 ) { + for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { - texture.needsUpdate = true; + if ( attributes[ 'morphNormal' + i ] >= 0 ) { - if ( onLoad ) onLoad( texture ); + material.numSupportedMorphNormals ++; - } + } - }, undefined, onError ); + } - } + } - for ( var i = 0; i < urls.length; ++ i ) { + var uniforms = materialProperties.__webglShader.uniforms; - loadTexture( i ); + if ( ! ( (material && material.isShaderMaterial) ) && + ! ( (material && material.isRawShaderMaterial) ) || + material.clipping === true ) { - } + materialProperties.numClippingPlanes = _clipping.numPlanes; + uniforms.clippingPlanes = _clipping.uniform; - return texture; + } - }, + if ( material.lights ) { - setCrossOrigin: function ( value ) { + // store the light setup it was created for - this.crossOrigin = value; - return this; + materialProperties.lightsHash = _lights.hash; - }, + // wire up the material to this renderer's lighting state - setPath: function ( value ) { + uniforms.ambientLightColor.value = _lights.ambient; + uniforms.directionalLights.value = _lights.directional; + uniforms.spotLights.value = _lights.spot; + uniforms.pointLights.value = _lights.point; + uniforms.hemisphereLights.value = _lights.hemi; - this.path = value; - return this; + uniforms.directionalShadowMap.value = _lights.directionalShadowMap; + uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix; + uniforms.spotShadowMap.value = _lights.spotShadowMap; + uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix; + uniforms.pointShadowMap.value = _lights.pointShadowMap; + uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix; - } + } -} ); + var progUniforms = materialProperties.program.getUniforms(), + uniformsList = + exports.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); -// File:src/loaders/BinaryTextureLoader.js + materialProperties.uniformsList = uniformsList; + materialProperties.dynamicUniforms = + exports.WebGLUniforms.splitDynamic( uniformsList, uniforms ); -/** - * @author Nikos M. / https://github.com/foo123/ - * - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) - */ + } -THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) { + function setMaterial( material ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + if ( material.side !== DoubleSide ) + state.enable( _gl.CULL_FACE ); + else + state.disable( _gl.CULL_FACE ); - // override in sub classes - this._parser = null; + state.setFlipSided( material.side === BackSide ); -}; + if ( material.transparent === true ) { -Object.assign( THREE.BinaryTextureLoader.prototype, { + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); - load: function ( url, onLoad, onProgress, onError ) { + } else { - var scope = this; + state.setBlending( NoBlending ); - var texture = new THREE.DataTexture(); + } - var loader = new THREE.XHRLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); + state.setDepthFunc( material.depthFunc ); + state.setDepthTest( material.depthTest ); + state.setDepthWrite( material.depthWrite ); + state.setColorWrite( material.colorWrite ); + state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - loader.load( url, function ( buffer ) { + } - var texData = scope._parser( buffer ); + function setProgram( camera, fog, material, object ) { - if ( ! texData ) return; + _usedTextureUnits = 0; - if ( undefined !== texData.image ) { + var materialProperties = properties.get( material ); - texture.image = texData.image; + if ( _clippingEnabled ) { - } else if ( undefined !== texData.data ) { + if ( _localClippingEnabled || camera !== _currentCamera ) { - texture.image.width = texData.width; - texture.image.height = texData.height; - texture.image.data = texData.data; + var useCache = + camera === _currentCamera && + material.id === _currentMaterialId; - } + // we might want to call this function with some ClippingGroup + // object instead of the material, once it becomes feasible + // (#8465, #8379) + _clipping.setState( + material.clippingPlanes, material.clipShadows, + camera, materialProperties, useCache ); - texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping; - texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping; + } - texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter; - texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter; + if ( materialProperties.numClippingPlanes !== undefined && + materialProperties.numClippingPlanes !== _clipping.numPlanes ) { - texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; + material.needsUpdate = true; - if ( undefined !== texData.format ) { + } - texture.format = texData.format; + } - } - if ( undefined !== texData.type ) { + if ( materialProperties.program === undefined ) { - texture.type = texData.type; + material.needsUpdate = true; - } + } - if ( undefined !== texData.mipmaps ) { + if ( materialProperties.lightsHash !== undefined && + materialProperties.lightsHash !== _lights.hash ) { - texture.mipmaps = texData.mipmaps; + material.needsUpdate = true; - } + } - if ( 1 === texData.mipmapCount ) { + if ( material.needsUpdate ) { - texture.minFilter = THREE.LinearFilter; + initMaterial( material, fog, object ); + material.needsUpdate = false; - } + } - texture.needsUpdate = true; + var refreshProgram = false; + var refreshMaterial = false; + var refreshLights = false; - if ( onLoad ) onLoad( texture, texData ); + var program = materialProperties.program, + p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.__webglShader.uniforms; - }, onProgress, onError ); + if ( program.id !== _currentProgram ) { + _gl.useProgram( program.program ); + _currentProgram = program.id; - return texture; + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; - } + } -} ); + if ( material.id !== _currentMaterialId ) { -// File:src/loaders/CompressedTextureLoader.js + _currentMaterialId = material.id; -/** - * @author mrdoob / http://mrdoob.com/ - * - * Abstract Base class to block based textures loader (dds, pvr, ...) - */ + refreshMaterial = true; -THREE.CompressedTextureLoader = function ( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + if ( refreshProgram || camera !== _currentCamera ) { - // override in sub classes - this._parser = null; + p_uniforms.set( _gl, camera, 'projectionMatrix' ); -}; + if ( capabilities.logarithmicDepthBuffer ) { -Object.assign( THREE.CompressedTextureLoader.prototype, { + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); - load: function ( url, onLoad, onProgress, onError ) { + } - var scope = this; - var images = []; + if ( camera !== _currentCamera ) { - var texture = new THREE.CompressedTexture(); - texture.image = images; + _currentCamera = camera; - var loader = new THREE.XHRLoader( this.manager ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); + // lighting uniforms depend on the camera so enforce an update + // now, in case this material supports lights - or later, when + // the next material that does gets activated: - function loadTexture( i ) { + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done - loader.load( url[ i ], function ( buffer ) { + } - var texDatas = scope._parser( buffer, true ); + // load material specific uniforms + // (shader material also gets them for the sake of genericity) - images[ i ] = { - width: texDatas.width, - height: texDatas.height, - format: texDatas.format, - mipmaps: texDatas.mipmaps - }; + if ( (material && material.isShaderMaterial) || + (material && material.isMeshPhongMaterial) || + (material && material.isMeshStandardMaterial) || + material.envMap ) { - loaded += 1; + var uCamPos = p_uniforms.map.cameraPosition; - if ( loaded === 6 ) { + if ( uCamPos !== undefined ) { - if ( texDatas.mipmapCount === 1 ) - texture.minFilter = THREE.LinearFilter; + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); - texture.format = texDatas.format; - texture.needsUpdate = true; + } - if ( onLoad ) onLoad( texture ); + } - } + if ( (material && material.isMeshPhongMaterial) || + (material && material.isMeshLambertMaterial) || + (material && material.isMeshBasicMaterial) || + (material && material.isMeshStandardMaterial) || + (material && material.isShaderMaterial) || + material.skinning ) { - }, onProgress, onError ); + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); - } + } - if ( Array.isArray( url ) ) { + p_uniforms.set( _gl, _this, 'toneMappingExposure' ); + p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' ); - var loaded = 0; + } - for ( var i = 0, il = url.length; i < il; ++ i ) { + // skinning uniforms must be set even if material didn't change + // auto-setting of texture unit for bone texture must go before other textures + // not sure why, but otherwise weird things happen - loadTexture( i ); + if ( material.skinning ) { - } + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); - } else { + var skeleton = object.skeleton; - // compressed cubemap texture stored in a single DDS file + if ( skeleton ) { - loader.load( url, function ( buffer ) { + if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) { - var texDatas = scope._parser( buffer, true ); + p_uniforms.set( _gl, skeleton, 'boneTexture' ); + p_uniforms.set( _gl, skeleton, 'boneTextureWidth' ); + p_uniforms.set( _gl, skeleton, 'boneTextureHeight' ); - if ( texDatas.isCubemap ) { + } else { - var faces = texDatas.mipmaps.length / texDatas.mipmapCount; + p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); - for ( var f = 0; f < faces; f ++ ) { + } - images[ f ] = { mipmaps : [] }; + } - for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { + } - images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); - images[ f ].format = texDatas.format; - images[ f ].width = texDatas.width; - images[ f ].height = texDatas.height; + if ( refreshMaterial ) { - } + if ( material.lights ) { - } + // the current material requires lighting info - } else { + // note: all lighting uniforms are always set correctly + // they simply reference the renderer's state for their + // values + // + // use the current material's .needsUpdate flags to set + // the GL state when required - texture.image.width = texDatas.width; - texture.image.height = texDatas.height; - texture.mipmaps = texDatas.mipmaps; + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); - } + } - if ( texDatas.mipmapCount === 1 ) { + // refresh uniforms common to several materials - texture.minFilter = THREE.LinearFilter; + if ( fog && material.fog ) { - } + refreshUniformsFog( m_uniforms, fog ); - texture.format = texDatas.format; - texture.needsUpdate = true; + } - if ( onLoad ) onLoad( texture ); + if ( (material && material.isMeshBasicMaterial) || + (material && material.isMeshLambertMaterial) || + (material && material.isMeshPhongMaterial) || + (material && material.isMeshStandardMaterial) || + (material && material.isMeshDepthMaterial) ) { - }, onProgress, onError ); + refreshUniformsCommon( m_uniforms, material ); - } + } - return texture; + // refresh single material specific uniforms - }, + if ( (material && material.isLineBasicMaterial) ) { - setPath: function ( value ) { + refreshUniformsLine( m_uniforms, material ); - this.path = value; - return this; + } else if ( (material && material.isLineDashedMaterial) ) { - } + refreshUniformsLine( m_uniforms, material ); + refreshUniformsDash( m_uniforms, material ); -} ); + } else if ( (material && material.isPointsMaterial) ) { -// File:src/materials/Material.js + refreshUniformsPoints( m_uniforms, material ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + } else if ( (material && material.isMeshLambertMaterial) ) { -THREE.Material = function () { + refreshUniformsLambert( m_uniforms, material ); - Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } ); + } else if ( (material && material.isMeshPhongMaterial) ) { - this.uuid = THREE.Math.generateUUID(); + refreshUniformsPhong( m_uniforms, material ); - this.name = ''; - this.type = 'Material'; + } else if ( (material && material.isMeshPhysicalMaterial) ) { - this.fog = true; - this.lights = true; + refreshUniformsPhysical( m_uniforms, material ); - this.blending = THREE.NormalBlending; - this.side = THREE.FrontSide; - this.shading = THREE.SmoothShading; // THREE.FlatShading, THREE.SmoothShading - this.vertexColors = THREE.NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors + } else if ( (material && material.isMeshStandardMaterial) ) { - this.opacity = 1; - this.transparent = false; + refreshUniformsStandard( m_uniforms, material ); - this.blendSrc = THREE.SrcAlphaFactor; - this.blendDst = THREE.OneMinusSrcAlphaFactor; - this.blendEquation = THREE.AddEquation; - this.blendSrcAlpha = null; - this.blendDstAlpha = null; - this.blendEquationAlpha = null; + } else if ( (material && material.isMeshDepthMaterial) ) { - this.depthFunc = THREE.LessEqualDepth; - this.depthTest = true; - this.depthWrite = true; + if ( material.displacementMap ) { - this.clippingPlanes = null; - this.clipShadows = false; + m_uniforms.displacementMap.value = material.displacementMap; + m_uniforms.displacementScale.value = material.displacementScale; + m_uniforms.displacementBias.value = material.displacementBias; - this.colorWrite = true; + } - this.precision = null; // override the renderer's default precision for this material + } else if ( (material && material.isMeshNormalMaterial) ) { - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; + m_uniforms.opacity.value = material.opacity; - this.alphaTest = 0; - this.premultipliedAlpha = false; + } - this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer + exports.WebGLUniforms.upload( + _gl, materialProperties.uniformsList, m_uniforms, _this ); - this.visible = true; + } - this._needsUpdate = true; -}; + // common matrices -THREE.Material.prototype = { + p_uniforms.set( _gl, object, 'modelViewMatrix' ); + p_uniforms.set( _gl, object, 'normalMatrix' ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); - constructor: THREE.Material, - get needsUpdate() { + // dynamic uniforms - return this._needsUpdate; + var dynUniforms = materialProperties.dynamicUniforms; - }, + if ( dynUniforms !== null ) { - set needsUpdate( value ) { + exports.WebGLUniforms.evalDynamic( + dynUniforms, m_uniforms, object, camera ); - if ( value === true ) this.update(); - this._needsUpdate = value; + exports.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); - }, + } - setValues: function ( values ) { + return program; - if ( values === undefined ) return; + } - for ( var key in values ) { + // Uniforms (refresh uniforms objects) - var newValue = values[ key ]; + function refreshUniformsCommon ( uniforms, material ) { - if ( newValue === undefined ) { + uniforms.opacity.value = material.opacity; - console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); - continue; + uniforms.diffuse.value = material.color; - } + if ( material.emissive ) { - var currentValue = this[ key ]; + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); - if ( currentValue === undefined ) { + } - console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); - continue; + uniforms.map.value = material.map; + uniforms.specularMap.value = material.specularMap; + uniforms.alphaMap.value = material.alphaMap; - } + if ( material.aoMap ) { - if ( currentValue instanceof THREE.Color ) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; - currentValue.set( newValue ); + } - } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) { + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. normal map + // 4. bump map + // 5. alpha map + // 6. emissive map - currentValue.copy( newValue ); + var uvScaleMap; - } else if ( key === 'overdraw' ) { + if ( material.map ) { - // ensure overdraw is backwards-compatible with legacy boolean type - this[ key ] = Number( newValue ); + uvScaleMap = material.map; - } else { + } else if ( material.specularMap ) { - this[ key ] = newValue; + uvScaleMap = material.specularMap; - } + } else if ( material.displacementMap ) { - } + uvScaleMap = material.displacementMap; - }, + } else if ( material.normalMap ) { - toJSON: function ( meta ) { + uvScaleMap = material.normalMap; - var isRoot = meta === undefined; + } else if ( material.bumpMap ) { - if ( isRoot ) { + uvScaleMap = material.bumpMap; - meta = { - textures: {}, - images: {} - }; + } else if ( material.roughnessMap ) { - } + uvScaleMap = material.roughnessMap; - var data = { - metadata: { - version: 4.4, - type: 'Material', - generator: 'Material.toJSON' - } - }; + } else if ( material.metalnessMap ) { - // standard Material serialization - data.uuid = this.uuid; - data.type = this.type; + uvScaleMap = material.metalnessMap; - if ( this.name !== '' ) data.name = this.name; + } else if ( material.alphaMap ) { - if ( this.color instanceof THREE.Color ) data.color = this.color.getHex(); + uvScaleMap = material.alphaMap; - if ( this.roughness !== undefined ) data.roughness = this.roughness; - if ( this.metalness !== undefined ) data.metalness = this.metalness; + } else if ( material.emissiveMap ) { - if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex(); - if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex(); - if ( this.shininess !== undefined ) data.shininess = this.shininess; + uvScaleMap = material.emissiveMap; - if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid; - if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; - if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid; - if ( this.bumpMap instanceof THREE.Texture ) { + } - data.bumpMap = this.bumpMap.toJSON( meta ).uuid; - data.bumpScale = this.bumpScale; + if ( uvScaleMap !== undefined ) { - } - if ( this.normalMap instanceof THREE.Texture ) { + // backwards compatibility + if ( (uvScaleMap && uvScaleMap.isWebGLRenderTarget) ) { - data.normalMap = this.normalMap.toJSON( meta ).uuid; - data.normalScale = this.normalScale.toArray(); + uvScaleMap = uvScaleMap.texture; - } - if ( this.displacementMap instanceof THREE.Texture ) { + } - data.displacementMap = this.displacementMap.toJSON( meta ).uuid; - data.displacementScale = this.displacementScale; - data.displacementBias = this.displacementBias; + var offset = uvScaleMap.offset; + var repeat = uvScaleMap.repeat; - } - if ( this.roughnessMap instanceof THREE.Texture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; - if ( this.metalnessMap instanceof THREE.Texture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; + uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - if ( this.emissiveMap instanceof THREE.Texture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; - if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid; + } - if ( this.envMap instanceof THREE.Texture ) { + uniforms.envMap.value = material.envMap; - data.envMap = this.envMap.toJSON( meta ).uuid; - data.reflectivity = this.reflectivity; // Scale behind envMap + // don't flip CubeTexture envMaps, flip everything else: + // WebGLRenderTargetCube will be flipped for backwards compatibility + // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture + // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future + uniforms.flipEnvMap.value = ( ! ( (material.envMap && material.envMap.isCubeTexture) ) ) ? 1 : - 1; - } + uniforms.reflectivity.value = material.reflectivity; + uniforms.refractionRatio.value = material.refractionRatio; - if ( this.size !== undefined ) data.size = this.size; - if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + } - if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending; - if ( this.shading !== THREE.SmoothShading ) data.shading = this.shading; - if ( this.side !== THREE.FrontSide ) data.side = this.side; - if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors; + function refreshUniformsLine ( uniforms, material ) { - if ( this.opacity < 1 ) data.opacity = this.opacity; - if ( this.transparent === true ) data.transparent = this.transparent; - if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; - if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; - if ( this.wireframe === true ) data.wireframe = this.wireframe; - if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; - // TODO: Copied from Object3D.toJSON + } - function extractFromCache ( cache ) { + function refreshUniformsDash ( uniforms, material ) { - var values = []; + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; - for ( var key in cache ) { + } - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + function refreshUniformsPoints ( uniforms, material ) { - } + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * _pixelRatio; + uniforms.scale.value = _canvas.clientHeight * 0.5; - return values; + uniforms.map.value = material.map; - } + if ( material.map !== null ) { - if ( isRoot ) { + var offset = material.map.offset; + var repeat = material.map.repeat; - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - if ( textures.length > 0 ) data.textures = textures; - if ( images.length > 0 ) data.images = images; + } - } + } - return data; + function refreshUniformsFog ( uniforms, fog ) { - }, + uniforms.fogColor.value = fog.color; - clone: function () { + if ( (fog && fog.isFog) ) { - return new this.constructor().copy( this ); + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; - }, + } else if ( (fog && fog.isFogExp2) ) { - copy: function ( source ) { + uniforms.fogDensity.value = fog.density; - this.name = source.name; + } - this.fog = source.fog; - this.lights = source.lights; + } - this.blending = source.blending; - this.side = source.side; - this.shading = source.shading; - this.vertexColors = source.vertexColors; + function refreshUniformsLambert ( uniforms, material ) { - this.opacity = source.opacity; - this.transparent = source.transparent; + if ( material.lightMap ) { - this.blendSrc = source.blendSrc; - this.blendDst = source.blendDst; - this.blendEquation = source.blendEquation; - this.blendSrcAlpha = source.blendSrcAlpha; - this.blendDstAlpha = source.blendDstAlpha; - this.blendEquationAlpha = source.blendEquationAlpha; + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; - this.depthFunc = source.depthFunc; - this.depthTest = source.depthTest; - this.depthWrite = source.depthWrite; + } - this.colorWrite = source.colorWrite; + if ( material.emissiveMap ) { - this.precision = source.precision; + uniforms.emissiveMap.value = material.emissiveMap; - this.polygonOffset = source.polygonOffset; - this.polygonOffsetFactor = source.polygonOffsetFactor; - this.polygonOffsetUnits = source.polygonOffsetUnits; + } - this.alphaTest = source.alphaTest; + } - this.premultipliedAlpha = source.premultipliedAlpha; + function refreshUniformsPhong ( uniforms, material ) { - this.overdraw = source.overdraw; + uniforms.specular.value = material.specular; + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) - this.visible = source.visible; - this.clipShadows = source.clipShadows; + if ( material.lightMap ) { - var srcPlanes = source.clippingPlanes, - dstPlanes = null; + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; - if ( srcPlanes !== null ) { + } - var n = srcPlanes.length; - dstPlanes = new Array( n ); + if ( material.emissiveMap ) { - for ( var i = 0; i !== n; ++ i ) - dstPlanes[ i ] = srcPlanes[ i ].clone(); + uniforms.emissiveMap.value = material.emissiveMap; - } + } - this.clippingPlanes = dstPlanes; + if ( material.bumpMap ) { - return this; + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; - }, + } - update: function () { + if ( material.normalMap ) { - this.dispatchEvent( { type: 'update' } ); + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); - }, + } - dispose: function () { + if ( material.displacementMap ) { - this.dispatchEvent( { type: 'dispose' } ); + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - } + } -}; + } -Object.assign( THREE.Material.prototype, THREE.EventDispatcher.prototype ); + function refreshUniformsStandard ( uniforms, material ) { -THREE.MaterialIdCount = 0; + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; -// File:src/materials/LineBasicMaterial.js + if ( material.roughnessMap ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * linecap: "round", - * linejoin: "round" - * } - */ + uniforms.roughnessMap.value = material.roughnessMap; -THREE.LineBasicMaterial = function ( parameters ) { + } - THREE.Material.call( this ); + if ( material.metalnessMap ) { - this.type = 'LineBasicMaterial'; + uniforms.metalnessMap.value = material.metalnessMap; - this.color = new THREE.Color( 0xffffff ); + } - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; + if ( material.lightMap ) { - this.lights = false; + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; - this.setValues( parameters ); + } -}; + if ( material.emissiveMap ) { -THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial; + uniforms.emissiveMap.value = material.emissiveMap; -THREE.LineBasicMaterial.prototype.copy = function ( source ) { + } - THREE.Material.prototype.copy.call( this, source ); + if ( material.bumpMap ) { - this.color.copy( source.color ); + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; - this.linewidth = source.linewidth; - this.linecap = source.linecap; - this.linejoin = source.linejoin; + } - return this; + if ( material.normalMap ) { -}; + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); -// File:src/materials/LineDashedMaterial.js + } -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * - * scale: , - * dashSize: , - * gapSize: - * } - */ + if ( material.displacementMap ) { -THREE.LineDashedMaterial = function ( parameters ) { + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - THREE.Material.call( this ); + } - this.type = 'LineDashedMaterial'; + if ( material.envMap ) { - this.color = new THREE.Color( 0xffffff ); + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; - this.linewidth = 1; + } - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; + } - this.lights = false; + function refreshUniformsPhysical ( uniforms, material ) { - this.setValues( parameters ); + uniforms.clearCoat.value = material.clearCoat; + uniforms.clearCoatRoughness.value = material.clearCoatRoughness; -}; + refreshUniformsStandard( uniforms, material ); -THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial; + } -THREE.LineDashedMaterial.prototype.copy = function ( source ) { + // If uniforms are marked as clean, they don't need to be loaded to the GPU. - THREE.Material.prototype.copy.call( this, source ); + function markUniformsLightsNeedsUpdate ( uniforms, value ) { - this.color.copy( source.color ); + uniforms.ambientLightColor.needsUpdate = value; - this.linewidth = source.linewidth; + uniforms.directionalLights.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; - this.scale = source.scale; - this.dashSize = source.dashSize; - this.gapSize = source.gapSize; + } - return this; + // Lighting -}; + function setupShadows ( lights ) { -// File:src/materials/MeshBasicMaterial.js + var lightShadowsLength = 0; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * shading: THREE.SmoothShading, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: - * } - */ + for ( var i = 0, l = lights.length; i < l; i ++ ) { -THREE.MeshBasicMaterial = function ( parameters ) { + var light = lights[ i ]; - THREE.Material.call( this ); + if ( light.castShadow ) { - this.type = 'MeshBasicMaterial'; + _lights.shadows[ lightShadowsLength ++ ] = light; - this.color = new THREE.Color( 0xffffff ); // emissive + } - this.map = null; + } - this.aoMap = null; - this.aoMapIntensity = 1.0; + _lights.shadows.length = lightShadowsLength; - this.specularMap = null; + } - this.alphaMap = null; + function setupLights ( lights, camera ) { - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + var l, ll, light, + r = 0, g = 0, b = 0, + color, + intensity, + distance, + shadowMap, - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + viewMatrix = camera.matrixWorldInverse, - this.skinning = false; - this.morphTargets = false; + directionalLength = 0, + pointLength = 0, + spotLength = 0, + hemiLength = 0; - this.lights = false; + for ( l = 0, ll = lights.length; l < ll; l ++ ) { - this.setValues( parameters ); + light = lights[ l ]; -}; + color = light.color; + intensity = light.intensity; + distance = light.distance; -THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial; + shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; -THREE.MeshBasicMaterial.prototype.copy = function ( source ) { + if ( (light && light.isAmbientLight) ) { - THREE.Material.prototype.copy.call( this, source ); + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; - this.color.copy( source.color ); + } else if ( (light && light.isDirectionalLight) ) { - this.map = source.map; + var uniforms = lightCache.get( light ); - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( _vector3 ); + uniforms.direction.transformDirection( viewMatrix ); - this.specularMap = source.specularMap; + uniforms.shadow = light.castShadow; - this.alphaMap = source.alphaMap; + if ( light.castShadow ) { - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + } - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + _lights.directionalShadowMap[ directionalLength ] = shadowMap; + _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + _lights.directional[ directionalLength ++ ] = uniforms; - return this; + } else if ( (light && light.isSpotLight) ) { -}; + var uniforms = lightCache.get( light ); -// File:src/materials/MeshDepthMaterial.js + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / https://clara.io - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * - * opacity: , - * - * map: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ + uniforms.color.copy( color ).multiplyScalar( intensity ); + uniforms.distance = distance; -THREE.MeshDepthMaterial = function ( parameters ) { + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( _vector3 ); + uniforms.direction.transformDirection( viewMatrix ); - THREE.Material.call( this ); + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; - this.type = 'MeshDepthMaterial'; + uniforms.shadow = light.castShadow; - this.depthPacking = THREE.BasicDepthPacking; + if ( light.castShadow ) { - this.skinning = false; - this.morphTargets = false; + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - this.map = null; + } - this.alphaMap = null; + _lights.spotShadowMap[ spotLength ] = shadowMap; + _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; + _lights.spot[ spotLength ++ ] = uniforms; - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + } else if ( (light && light.isPointLight) ) { - this.wireframe = false; - this.wireframeLinewidth = 1; + var uniforms = lightCache.get( light ); - this.fog = false; - this.lights = false; + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - this.setValues( parameters ); + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.distance = light.distance; + uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; -}; + uniforms.shadow = light.castShadow; -THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial; + if ( light.castShadow ) { -THREE.MeshDepthMaterial.prototype.copy = function ( source ) { + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - THREE.Material.prototype.copy.call( this, source ); + } - this.depthPacking = source.depthPacking; + _lights.pointShadowMap[ pointLength ] = shadowMap; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) { - this.map = source.map; + _lights.pointShadowMatrix[ pointLength ] = new Matrix4(); - this.alphaMap = source.alphaMap; + } - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + // for point lights we set the shadow matrix to be a translation-only matrix + // equal to inverse of the light's position + _vector3.setFromMatrixPosition( light.matrixWorld ).negate(); + _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 ); - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + _lights.point[ pointLength ++ ] = uniforms; - return this; + } else if ( (light && light.isHemisphereLight) ) { -}; + var uniforms = lightCache.get( light ); -// File:src/materials/MeshLambertMaterial.js + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + uniforms.direction.normalize(); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); -THREE.MeshLambertMaterial = function ( parameters ) { + _lights.hemi[ hemiLength ++ ] = uniforms; - THREE.Material.call( this ); + } - this.type = 'MeshLambertMaterial'; + } - this.color = new THREE.Color( 0xffffff ); // diffuse + _lights.ambient[ 0 ] = r; + _lights.ambient[ 1 ] = g; + _lights.ambient[ 2 ] = b; - this.map = null; + _lights.directional.length = directionalLength; + _lights.spot.length = spotLength; + _lights.point.length = pointLength; + _lights.hemi.length = hemiLength; - this.lightMap = null; - this.lightMapIntensity = 1.0; + _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length; - this.aoMap = null; - this.aoMapIntensity = 1.0; + } - this.emissive = new THREE.Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + // GL state setting - this.specularMap = null; + this.setFaceCulling = function ( cullFace, frontFaceDirection ) { - this.alphaMap = null; + state.setCullFace( cullFace ); + state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW ); - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + }; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + // Textures - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + function allocTextureUnit() { - this.setValues( parameters ); + var textureUnit = _usedTextureUnits; -}; + if ( textureUnit >= capabilities.maxTextures ) { -THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial; + console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); -THREE.MeshLambertMaterial.prototype.copy = function ( source ) { + } - THREE.Material.prototype.copy.call( this, source ); + _usedTextureUnits += 1; - this.color.copy( source.color ); + return textureUnit; - this.map = source.map; + } - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + this.allocTextureUnit = allocTextureUnit; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + // this.setTexture2D = setTexture2D; + this.setTexture2D = ( function() { - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + var warned = false; - this.specularMap = source.specularMap; + // backwards compatibility: peel texture.texture + return function setTexture2D( texture, slot ) { - this.alphaMap = source.alphaMap; + if ( (texture && texture.isWebGLRenderTarget) ) { - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + if ( ! warned ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); + warned = true; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + } - return this; + texture = texture.texture; -}; + } -// File:src/materials/MeshNormalMaterial.js + textures.setTexture2D( texture, slot ); -/** - * @author mrdoob / http://mrdoob.com/ - * - * parameters = { - * opacity: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ + }; -THREE.MeshNormalMaterial = function ( parameters ) { + }() ); - THREE.Material.call( this, parameters ); + this.setTexture = ( function() { - this.type = 'MeshNormalMaterial'; + var warned = false; - this.wireframe = false; - this.wireframeLinewidth = 1; + return function setTexture( texture, slot ) { - this.fog = false; - this.lights = false; - this.morphTargets = false; + if ( ! warned ) { - this.setValues( parameters ); + console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); + warned = true; -}; + } -THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial; + textures.setTexture2D( texture, slot ); -THREE.MeshNormalMaterial.prototype.copy = function ( source ) { + }; - THREE.Material.prototype.copy.call( this, source ); + }() ); - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + this.setTextureCube = ( function() { - return this; + var warned = false; -}; + return function setTextureCube( texture, slot ) { -// File:src/materials/MeshPhongMaterial.js + // backwards compatibility: peel texture.texture + if ( (texture && texture.isWebGLRenderTargetCube) ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * specular: , - * shininess: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + if ( ! warned ) { -THREE.MeshPhongMaterial = function ( parameters ) { + console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); + warned = true; - THREE.Material.call( this ); + } - this.type = 'MeshPhongMaterial'; + texture = texture.texture; - this.color = new THREE.Color( 0xffffff ); // diffuse - this.specular = new THREE.Color( 0x111111 ); - this.shininess = 30; + } - this.map = null; + // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture + // TODO: unify these code paths + if ( (texture && texture.isCubeTexture) || + ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { - this.lightMap = null; - this.lightMapIntensity = 1.0; + // CompressedTexture can have Array in image :/ - this.aoMap = null; - this.aoMapIntensity = 1.0; + // this function alone should take care of cube textures + textures.setTextureCube( texture, slot ); - this.emissive = new THREE.Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + } else { - this.bumpMap = null; - this.bumpScale = 1; + // assumed: texture property of THREE.WebGLRenderTargetCube - this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); + textures.setTextureCubeDynamic( texture, slot ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + } - this.specularMap = null; + }; - this.alphaMap = null; + }() ); - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + this.getCurrentRenderTarget = function() { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + return _currentRenderTarget; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + }; - this.setValues( parameters ); + this.setRenderTarget = function ( renderTarget ) { -}; + _currentRenderTarget = renderTarget; -THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial; + if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { -THREE.MeshPhongMaterial.prototype.copy = function ( source ) { + textures.setupRenderTarget( renderTarget ); - THREE.Material.prototype.copy.call( this, source ); + } - this.color.copy( source.color ); - this.specular.copy( source.specular ); - this.shininess = source.shininess; + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + var framebuffer; - this.map = source.map; + if ( renderTarget ) { - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + var renderTargetProperties = properties.get( renderTarget ); - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + if ( isCube ) { - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ]; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + } else { - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + framebuffer = renderTargetProperties.__webglFramebuffer; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + } - this.specularMap = source.specularMap; + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; - this.alphaMap = source.alphaMap; + _currentViewport.copy( renderTarget.viewport ); - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + } else { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + framebuffer = null; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); + _currentScissorTest = _scissorTest; - return this; + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); -}; + } -// File:src/materials/MeshStandardMaterial.js + if ( _currentFramebuffer !== framebuffer ) { -/** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * color: , - * roughness: , - * metalness: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * roughnessMap: new THREE.Texture( ), - * - * metalnessMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * envMapIntensity: - * - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _currentFramebuffer = framebuffer; -THREE.MeshStandardMaterial = function ( parameters ) { + } - THREE.Material.call( this ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); - this.defines = { 'STANDARD': '' }; + state.viewport( _currentViewport ); - this.type = 'MeshStandardMaterial'; + if ( isCube ) { - this.color = new THREE.Color( 0xffffff ); // diffuse - this.roughness = 0.5; - this.metalness = 0.5; + var textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel ); - this.map = null; + } - this.lightMap = null; - this.lightMapIntensity = 1.0; + }; - this.aoMap = null; - this.aoMapIntensity = 1.0; + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { - this.emissive = new THREE.Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + if ( (renderTarget && renderTarget.isWebGLRenderTarget) === false ) { - this.bumpMap = null; - this.bumpScale = 1; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; - this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); + } - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + var framebuffer = properties.get( renderTarget ).__webglFramebuffer; - this.roughnessMap = null; + if ( framebuffer ) { - this.metalnessMap = null; + var restore = false; - this.alphaMap = null; + if ( framebuffer !== _currentFramebuffer ) { - this.envMap = null; - this.envMapIntensity = 1.0; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - this.refractionRatio = 0.98; + restore = true; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + } - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + try { - this.setValues( parameters ); + var texture = renderTarget.texture; -}; + if ( texture.format !== RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { -THREE.MeshStandardMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshStandardMaterial.prototype.constructor = THREE.MeshStandardMaterial; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; -THREE.MeshStandardMaterial.prototype.copy = function ( source ) { + } - THREE.Material.prototype.copy.call( this, source ); + if ( texture.type !== UnsignedByteType && + paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && + ! ( texture.type === FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) && + ! ( texture.type === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { - this.defines = { 'STANDARD': '' }; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; - this.color.copy( source.color ); - this.roughness = source.roughness; - this.metalness = source.metalness; + } - this.map = source.map; + if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer ); - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + } - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + } else { - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); - this.roughnessMap = source.roughnessMap; + } - this.metalnessMap = source.metalnessMap; + } finally { - this.alphaMap = source.alphaMap; + if ( restore ) { - this.envMap = source.envMap; - this.envMapIntensity = source.envMapIntensity; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); - this.refractionRatio = source.refractionRatio; + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + } - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + } - return this; + }; -}; + // Map three.js constants to WebGL constants -// File:src/materials/MeshPhysicalMaterial.js + function paramThreeToGL ( p ) { -/** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * reflectivity: - * } - */ + var extension; -THREE.MeshPhysicalMaterial = function ( parameters ) { + if ( p === RepeatWrapping ) return _gl.REPEAT; + if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; + if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; - THREE.MeshStandardMaterial.call( this ); + if ( p === NearestFilter ) return _gl.NEAREST; + if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; + if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; - this.defines = { 'PHYSICAL': '' }; + if ( p === LinearFilter ) return _gl.LINEAR; + if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; + if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; - this.type = 'MeshPhysicalMaterial'; + if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE; + if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; + if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; - this.reflectivity = 0.5; // maps to F0 = 0.04 + if ( p === ByteType ) return _gl.BYTE; + if ( p === ShortType ) return _gl.SHORT; + if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT; + if ( p === IntType ) return _gl.INT; + if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT; + if ( p === FloatType ) return _gl.FLOAT; - this.clearCoat = 0.0; - this.clearCoatRoughness = 0.0; + extension = extensions.get( 'OES_texture_half_float' ); - this.setValues( parameters ); + if ( extension !== null ) { -}; + if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES; -THREE.MeshPhysicalMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype ); -THREE.MeshPhysicalMaterial.prototype.constructor = THREE.MeshPhysicalMaterial; + } -THREE.MeshPhysicalMaterial.prototype.copy = function ( source ) { + if ( p === AlphaFormat ) return _gl.ALPHA; + if ( p === RGBFormat ) return _gl.RGB; + if ( p === RGBAFormat ) return _gl.RGBA; + if ( p === LuminanceFormat ) return _gl.LUMINANCE; + if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; + if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT; - THREE.MeshStandardMaterial.prototype.copy.call( this, source ); + if ( p === AddEquation ) return _gl.FUNC_ADD; + if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT; + if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; - this.defines = { 'PHYSICAL': '' }; + if ( p === ZeroFactor ) return _gl.ZERO; + if ( p === OneFactor ) return _gl.ONE; + if ( p === SrcColorFactor ) return _gl.SRC_COLOR; + if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; + if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA; + if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; + if ( p === DstAlphaFactor ) return _gl.DST_ALPHA; + if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; - this.reflectivity = source.reflectivity; + if ( p === DstColorFactor ) return _gl.DST_COLOR; + if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; + if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; - this.clearCoat = source.clearCoat; - this.clearCoatRoughness = source.clearCoatRoughness; + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); - return this; + if ( extension !== null ) { -}; + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; -// File:src/materials/MultiMaterial.js + } -/** - * @author mrdoob / http://mrdoob.com/ - */ + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); -THREE.MultiMaterial = function ( materials ) { + if ( extension !== null ) { - this.uuid = THREE.Math.generateUUID(); + if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - this.type = 'MultiMaterial'; + } - this.materials = materials instanceof Array ? materials : []; + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); - this.visible = true; + if ( extension !== null ) { -}; + if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; -THREE.MultiMaterial.prototype = { + } - constructor: THREE.MultiMaterial, + extension = extensions.get( 'EXT_blend_minmax' ); - toJSON: function ( meta ) { + if ( extension !== null ) { - var output = { - metadata: { - version: 4.2, - type: 'material', - generator: 'MaterialExporter' - }, - uuid: this.uuid, - type: this.type, - materials: [] - }; + if ( p === MinEquation ) return extension.MIN_EXT; + if ( p === MaxEquation ) return extension.MAX_EXT; - var materials = this.materials; + } - for ( var i = 0, l = materials.length; i < l; i ++ ) { + return 0; - var material = materials[ i ].toJSON( meta ); - delete material.metadata; + } - output.materials.push( material ); + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - output.visible = this.visible; + function FogExp2 ( color, density ) { + this.isFogExp2 = true; - return output; + this.name = ''; - }, + this.color = new Color( color ); + this.density = ( density !== undefined ) ? density : 0.00025; - clone: function () { + }; - var material = new this.constructor(); + FogExp2.prototype.clone = function () { - for ( var i = 0; i < this.materials.length; i ++ ) { + return new FogExp2( this.color.getHex(), this.density ); - material.materials.push( this.materials[ i ].clone() ); + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - material.visible = this.visible; + function Fog ( color, near, far ) { + this.isFog = true; - return material; + this.name = ''; - } + this.color = new Color( color ); -}; + this.near = ( near !== undefined ) ? near : 1; + this.far = ( far !== undefined ) ? far : 1000; -// File:src/materials/PointsMaterial.js + }; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * size: , - * sizeAttenuation: - * } - */ + Fog.prototype.clone = function () { -THREE.PointsMaterial = function ( parameters ) { + return new Fog( this.color.getHex(), this.near, this.far ); - THREE.Material.call( this ); + }; - this.type = 'PointsMaterial'; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.color = new THREE.Color( 0xffffff ); + function Scene () { + this.isScene = this.isObject3D = true; - this.map = null; + Object3D.call( this ); - this.size = 1; - this.sizeAttenuation = true; + this.type = 'Scene'; - this.lights = false; + this.background = null; + this.fog = null; + this.overrideMaterial = null; - this.setValues( parameters ); + this.autoUpdate = true; // checked by the renderer -}; + }; -THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial; + Scene.prototype = Object.create( Object3D.prototype ); + Scene.prototype.constructor = Scene; -THREE.PointsMaterial.prototype.copy = function ( source ) { + Scene.prototype.copy = function ( source, recursive ) { - THREE.Material.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source, recursive ); - this.color.copy( source.color ); + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); - this.map = source.map; + this.autoUpdate = source.autoUpdate; + this.matrixAutoUpdate = source.matrixAutoUpdate; - this.size = source.size; - this.sizeAttenuation = source.sizeAttenuation; + return this; - return this; + }; -}; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ -// File:src/materials/ShaderMaterial.js + function LensFlare ( texture, size, distance, blending, color ) { + this.isLensFlare = true; -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * defines: { "label" : "value" }, - * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, - * - * fragmentShader: , - * vertexShader: , - * - * wireframe: , - * wireframeLinewidth: , - * - * lights: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + Object3D.call( this ); -THREE.ShaderMaterial = function ( parameters ) { + this.lensFlares = []; - THREE.Material.call( this ); + this.positionScreen = new Vector3(); + this.customUpdateCallback = undefined; - this.type = 'ShaderMaterial'; + if ( texture !== undefined ) { - this.defines = {}; - this.uniforms = {}; + this.add( texture, size, distance, blending, color ); - this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; - this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; + } - this.linewidth = 1; + }; - this.wireframe = false; - this.wireframeLinewidth = 1; + LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), { - this.fog = false; // set to use scene fog - this.lights = false; // set to use scene lights - this.clipping = false; // set to use user-defined clipping planes + constructor: LensFlare, - this.skinning = false; // set to use skinning attribute streams - this.morphTargets = false; // set to use morph targets - this.morphNormals = false; // set to use morph normals + copy: function ( source ) { - this.extensions = { - derivatives: false, // set to use derivatives - fragDepth: false, // set to use fragment depth values - drawBuffers: false, // set to use draw buffers - shaderTextureLOD: false // set to use shader texture LOD - }; + Object3D.prototype.copy.call( this, source ); - // When rendered geometry doesn't include these attributes but the material does, - // use these default values in WebGL. This avoids errors when buffer data is missing. - this.defaultAttributeValues = { - 'color': [ 1, 1, 1 ], - 'uv': [ 0, 0 ], - 'uv2': [ 0, 0 ] - }; + this.positionScreen.copy( source.positionScreen ); + this.customUpdateCallback = source.customUpdateCallback; - this.index0AttributeName = undefined; + for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) { - if ( parameters !== undefined ) { + this.lensFlares.push( source.lensFlares[ i ] ); - if ( parameters.attributes !== undefined ) { + } - console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); + return this; - } + }, - this.setValues( parameters ); + add: function ( texture, size, distance, blending, color, opacity ) { - } + if ( size === undefined ) size = - 1; + if ( distance === undefined ) distance = 0; + if ( opacity === undefined ) opacity = 1; + if ( color === undefined ) color = new Color( 0xffffff ); + if ( blending === undefined ) blending = NormalBlending; -}; + distance = Math.min( distance, Math.max( 0, distance ) ); -THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial; + this.lensFlares.push( { + texture: texture, // THREE.Texture + size: size, // size in pixels (-1 = use texture.width) + distance: distance, // distance (0-1) from light source (0=at light source) + x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back + scale: 1, // scale + rotation: 0, // rotation + opacity: opacity, // opacity + color: color, // color + blending: blending // blending + } ); -THREE.ShaderMaterial.prototype.copy = function ( source ) { + }, - THREE.Material.prototype.copy.call( this, source ); + /* + * Update lens flares update positions on all flares based on the screen position + * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way. + */ - this.fragmentShader = source.fragmentShader; - this.vertexShader = source.vertexShader; + updateLensFlares: function () { - this.uniforms = THREE.UniformsUtils.clone( source.uniforms ); + var f, fl = this.lensFlares.length; + var flare; + var vecX = - this.positionScreen.x * 2; + var vecY = - this.positionScreen.y * 2; - this.defines = source.defines; + for ( f = 0; f < fl; f ++ ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + flare = this.lensFlares[ f ]; - this.lights = source.lights; - this.clipping = source.clipping; + flare.x = this.positionScreen.x + vecX * flare.distance; + flare.y = this.positionScreen.y + vecY * flare.distance; - this.skinning = source.skinning; + flare.wantedRotation = flare.x * Math.PI * 0.25; + flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + } - this.extensions = source.extensions; + } - return this; + } ); -}; + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * uvOffset: new THREE.Vector2(), + * uvScale: new THREE.Vector2() + * } + */ -THREE.ShaderMaterial.prototype.toJSON = function ( meta ) { + function SpriteMaterial ( parameters ) { + this.isSpriteMaterial = this.isMaterial = true; - var data = THREE.Material.prototype.toJSON.call( this, meta ); + Material.call( this ); - data.uniforms = this.uniforms; - data.vertexShader = this.vertexShader; - data.fragmentShader = this.fragmentShader; + this.type = 'SpriteMaterial'; - return data; + this.color = new Color( 0xffffff ); + this.map = null; -}; + this.rotation = 0; -// File:src/materials/RawShaderMaterial.js + this.fog = false; + this.lights = false; -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.setValues( parameters ); -THREE.RawShaderMaterial = function ( parameters ) { + }; - THREE.ShaderMaterial.call( this, parameters ); + SpriteMaterial.prototype = Object.create( Material.prototype ); + SpriteMaterial.prototype.constructor = SpriteMaterial; - this.type = 'RawShaderMaterial'; + SpriteMaterial.prototype.copy = function ( source ) { -}; + Material.prototype.copy.call( this, source ); -THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); -THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial; + this.color.copy( source.color ); + this.map = source.map; -// File:src/materials/SpriteMaterial.js + this.rotation = source.rotation; -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * uvOffset: new THREE.Vector2(), - * uvScale: new THREE.Vector2() - * } - */ + return this; -THREE.SpriteMaterial = function ( parameters ) { + }; - THREE.Material.call( this ); + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - this.type = 'SpriteMaterial'; + function Sprite ( material ) { + this.isSprite = true; - this.color = new THREE.Color( 0xffffff ); - this.map = null; + Object3D.call( this ); - this.rotation = 0; + this.type = 'Sprite'; - this.fog = false; - this.lights = false; + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); - this.setValues( parameters ); + }; -}; + Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { -THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial; + constructor: Sprite, -THREE.SpriteMaterial.prototype.copy = function ( source ) { + raycast: ( function () { - THREE.Material.prototype.copy.call( this, source ); + var matrixPosition = new Vector3(); - this.color.copy( source.color ); - this.map = source.map; + return function raycast( raycaster, intersects ) { - this.rotation = source.rotation; + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - return this; + var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition ); + var guessSizeSq = this.scale.x * this.scale.y / 4; -}; + if ( distanceSq > guessSizeSq ) { -// File:src/materials/ShadowMaterial.js + return; -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.ShadowMaterial = function () { - - THREE.ShaderMaterial.call( this, { - uniforms: THREE.UniformsUtils.merge( [ - THREE.UniformsLib[ "lights" ], - { - opacity: { value: 1.0 } - } - ] ), - vertexShader: THREE.ShaderChunk[ 'shadow_vert' ], - fragmentShader: THREE.ShaderChunk[ 'shadow_frag' ] - } ); - - this.lights = true; - this.transparent = true; - - Object.defineProperties( this, { - opacity: { - enumerable: true, - get: function () { - return this.uniforms.opacity.value; - }, - set: function ( value ) { - this.uniforms.opacity.value = value; - } - } - } ); + intersects.push( { -}; + distance: Math.sqrt( distanceSq ), + point: this.position, + face: null, + object: this -THREE.ShadowMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); -THREE.ShadowMaterial.prototype.constructor = THREE.ShadowMaterial; + } ); -// File:src/textures/Texture.js + }; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ + }() ), -THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + clone: function () { - Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } ); + return new this.constructor( this.material ).copy( this ); - this.uuid = THREE.Math.generateUUID(); + } - this.name = ''; - this.sourceFile = ''; + } ); - this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE; - this.mipmaps = []; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING; + function LOD () { + this.isLOD = true; - this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping; + Object3D.call( this ); - this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter; + this.type = 'LOD'; - this.anisotropy = anisotropy !== undefined ? anisotropy : 1; + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + } + } ); - this.format = format !== undefined ? format : THREE.RGBAFormat; - this.type = type !== undefined ? type : THREE.UnsignedByteType; + }; - this.offset = new THREE.Vector2( 0, 0 ); - this.repeat = new THREE.Vector2( 1, 1 ); - this.generateMipmaps = true; - this.premultiplyAlpha = false; - this.flipY = true; - this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) + LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { + constructor: LOD, - // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. - // - // Also changing the encoding after already used by a Material will not automatically make the Material - // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. - this.encoding = encoding !== undefined ? encoding : THREE.LinearEncoding; + copy: function ( source ) { - this.version = 0; - this.onUpdate = null; + Object3D.prototype.copy.call( this, source, false ); -}; + var levels = source.levels; -THREE.Texture.DEFAULT_IMAGE = undefined; -THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping; + for ( var i = 0, l = levels.length; i < l; i ++ ) { -THREE.Texture.prototype = { + var level = levels[ i ]; - constructor: THREE.Texture, + this.addLevel( level.object.clone(), level.distance ); - set needsUpdate( value ) { + } - if ( value === true ) this.version ++; + return this; - }, + }, - clone: function () { + addLevel: function ( object, distance ) { - return new this.constructor().copy( this ); + if ( distance === undefined ) distance = 0; - }, + distance = Math.abs( distance ); - copy: function ( source ) { + var levels = this.levels; - this.image = source.image; - this.mipmaps = source.mipmaps.slice( 0 ); + for ( var l = 0; l < levels.length; l ++ ) { - this.mapping = source.mapping; + if ( distance < levels[ l ].distance ) { - this.wrapS = source.wrapS; - this.wrapT = source.wrapT; + break; - this.magFilter = source.magFilter; - this.minFilter = source.minFilter; + } - this.anisotropy = source.anisotropy; + } - this.format = source.format; - this.type = source.type; + levels.splice( l, 0, { distance: distance, object: object } ); - this.offset.copy( source.offset ); - this.repeat.copy( source.repeat ); + this.add( object ); - this.generateMipmaps = source.generateMipmaps; - this.premultiplyAlpha = source.premultiplyAlpha; - this.flipY = source.flipY; - this.unpackAlignment = source.unpackAlignment; - this.encoding = source.encoding; + }, - return this; + getObjectForDistance: function ( distance ) { - }, + var levels = this.levels; - toJSON: function ( meta ) { + for ( var i = 1, l = levels.length; i < l; i ++ ) { - if ( meta.textures[ this.uuid ] !== undefined ) { + if ( distance < levels[ i ].distance ) { - return meta.textures[ this.uuid ]; + break; - } + } - function getDataURL( image ) { + } - var canvas; + return levels[ i - 1 ].object; - if ( image.toDataURL !== undefined ) { + }, - canvas = image; + raycast: ( function () { - } else { + var matrixPosition = new Vector3(); - canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = image.width; - canvas.height = image.height; + return function raycast( raycaster, intersects ) { - canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - } + var distance = raycaster.ray.origin.distanceTo( matrixPosition ); - if ( canvas.width > 2048 || canvas.height > 2048 ) { + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); - return canvas.toDataURL( 'image/jpeg', 0.6 ); + }; - } else { + }() ), - return canvas.toDataURL( 'image/png' ); + update: function () { - } + var v1 = new Vector3(); + var v2 = new Vector3(); - } + return function update( camera ) { - var output = { - metadata: { - version: 4.4, - type: 'Texture', - generator: 'Texture.toJSON' - }, + var levels = this.levels; - uuid: this.uuid, - name: this.name, + if ( levels.length > 1 ) { - mapping: this.mapping, + v1.setFromMatrixPosition( camera.matrixWorld ); + v2.setFromMatrixPosition( this.matrixWorld ); - repeat: [ this.repeat.x, this.repeat.y ], - offset: [ this.offset.x, this.offset.y ], - wrap: [ this.wrapS, this.wrapT ], + var distance = v1.distanceTo( v2 ); - minFilter: this.minFilter, - magFilter: this.magFilter, - anisotropy: this.anisotropy, + levels[ 0 ].object.visible = true; - flipY: this.flipY - }; + for ( var i = 1, l = levels.length; i < l; i ++ ) { - if ( this.image !== undefined ) { + if ( distance >= levels[ i ].distance ) { - // TODO: Move to THREE.Image + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; - var image = this.image; + } else { - if ( image.uuid === undefined ) { + break; - image.uuid = THREE.Math.generateUUID(); // UGH + } - } + } - if ( meta.images[ image.uuid ] === undefined ) { + for ( ; i < l; i ++ ) { - meta.images[ image.uuid ] = { - uuid: image.uuid, - url: getDataURL( image ) - }; + levels[ i ].object.visible = false; - } + } - output.image = image.uuid; + } - } + }; - meta.textures[ this.uuid ] = output; + }(), - return output; + toJSON: function ( meta ) { - }, + var data = Object3D.prototype.toJSON.call( this, meta ); - dispose: function () { + data.object.levels = []; - this.dispatchEvent( { type: 'dispose' } ); + var levels = this.levels; - }, + for ( var i = 0, l = levels.length; i < l; i ++ ) { - transformUv: function ( uv ) { + var level = levels[ i ]; - if ( this.mapping !== THREE.UVMapping ) return; + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance + } ); - uv.multiply( this.repeat ); - uv.add( this.offset ); + } - if ( uv.x < 0 || uv.x > 1 ) { + return data; - switch ( this.wrapS ) { + } - case THREE.RepeatWrapping: + } ); - uv.x = uv.x - Math.floor( uv.x ); - break; + /** + * @author alteredq / http://alteredqualia.com/ + */ - case THREE.ClampToEdgeWrapping: + function DataTexture ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.isDataTexture = this.isTexture = true; - uv.x = uv.x < 0 ? 0 : 1; - break; + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - case THREE.MirroredRepeatWrapping: + this.image = { data: data, width: width, height: height }; - if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - uv.x = Math.ceil( uv.x ) - uv.x; + this.flipY = false; + this.generateMipmaps = false; - } else { + }; - uv.x = uv.x - Math.floor( uv.x ); + DataTexture.prototype = Object.create( Texture.prototype ); + DataTexture.prototype.constructor = DataTexture; - } - break; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author michael guerrero / http://realitymeltdown.com + * @author ikerr / http://verold.com + */ - } + function Skeleton ( bones, boneInverses, useVertexTexture ) { + this.isSkeleton = true; - } + this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; - if ( uv.y < 0 || uv.y > 1 ) { + this.identityMatrix = new Matrix4(); - switch ( this.wrapT ) { + // copy the bone array - case THREE.RepeatWrapping: + bones = bones || []; - uv.y = uv.y - Math.floor( uv.y ); - break; + this.bones = bones.slice( 0 ); - case THREE.ClampToEdgeWrapping: + // create a bone texture or an array of floats - uv.y = uv.y < 0 ? 0 : 1; - break; + if ( this.useVertexTexture ) { - case THREE.MirroredRepeatWrapping: + // layout (1 matrix = 4 pixels) + // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) + // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) + // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) + // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) + // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) - if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { - uv.y = Math.ceil( uv.y ) - uv.y; + var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix + size = exports.Math.nextPowerOfTwo( Math.ceil( size ) ); + size = Math.max( size, 4 ); - } else { + this.boneTextureWidth = size; + this.boneTextureHeight = size; - uv.y = uv.y - Math.floor( uv.y ); + this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel + this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType ); - } - break; + } else { - } + this.boneMatrices = new Float32Array( 16 * this.bones.length ); - } + } - if ( this.flipY ) { + // use the supplied bone inverses or calculate the inverses - uv.y = 1 - uv.y; + if ( boneInverses === undefined ) { - } + this.calculateInverses(); - } + } else { -}; + if ( this.bones.length === boneInverses.length ) { -Object.assign( THREE.Texture.prototype, THREE.EventDispatcher.prototype ); + this.boneInverses = boneInverses.slice( 0 ); -THREE.TextureIdCount = 0; + } else { -// File:src/textures/DepthTexture.js + console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); -/** - * @author Matt DesLauriers / @mattdesl - */ + this.boneInverses = []; -THREE.DepthTexture = function ( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, THREE.DepthFormat, type, anisotropy ); + this.boneInverses.push( new Matrix4() ); - this.image = { width: width, height: height }; + } - this.type = type !== undefined ? type : THREE.UnsignedShortType; + } - this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter; + } - this.flipY = false; - this.generateMipmaps = false; + }; -}; + Object.assign( Skeleton.prototype, { -THREE.DepthTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.DepthTexture.prototype.constructor = THREE.DepthTexture; + calculateInverses: function () { -// File:src/textures/CanvasTexture.js + this.boneInverses = []; -/** - * @author mrdoob / http://mrdoob.com/ - */ + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { -THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + var inverse = new Matrix4(); - THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + if ( this.bones[ b ] ) { - this.needsUpdate = true; + inverse.getInverse( this.bones[ b ].matrixWorld ); -}; + } -THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture; + this.boneInverses.push( inverse ); -// File:src/textures/CubeTexture.js + } -/** - * @author mrdoob / http://mrdoob.com/ - */ + }, -THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + pose: function () { - images = images !== undefined ? images : []; - mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping; + var bone; - THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + // recover the bind-time world matrices - this.flipY = false; + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { -}; + bone = this.bones[ b ]; -THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CubeTexture.prototype.constructor = THREE.CubeTexture; + if ( bone ) { -Object.defineProperty( THREE.CubeTexture.prototype, 'images', { + bone.matrixWorld.getInverse( this.boneInverses[ b ] ); - get: function () { + } - return this.image; + } - }, + // compute the local matrices, positions, rotations and scales - set: function ( value ) { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - this.image = value; + bone = this.bones[ b ]; - } + if ( bone ) { -} ); + if ( (bone.parent && bone.parent.isBone) ) { -// File:src/textures/CompressedTexture.js + bone.matrix.getInverse( bone.parent.matrixWorld ); + bone.matrix.multiply( bone.matrixWorld ); -/** - * @author alteredq / http://alteredqualia.com/ - */ + } else { -THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + bone.matrix.copy( bone.matrixWorld ); - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + } - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) + } - this.flipY = false; + } - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + }, - this.generateMipmaps = false; + update: ( function () { -}; + var offsetMatrix = new Matrix4(); -THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture; + return function update() { -// File:src/textures/DataTexture.js + // flatten bone matrices to array -/** - * @author alteredq / http://alteredqualia.com/ - */ + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { -THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + // compute the offset between the current and the original transform - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; - this.image = { data: data, width: width, height: height }; + offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); + offsetMatrix.toArray( this.boneMatrices, b * 16 ); - this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter; + } - this.flipY = false; - this.generateMipmaps = false; + if ( this.useVertexTexture ) { -}; + this.boneTexture.needsUpdate = true; -THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.DataTexture.prototype.constructor = THREE.DataTexture; + } -// File:src/textures/VideoTexture.js + }; -/** - * @author mrdoob / http://mrdoob.com/ - */ + } )(), -THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + clone: function () { - THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); - this.generateMipmaps = false; + } - var scope = this; + } ); - function update() { + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - requestAnimationFrame( update ); + function Bone ( skin ) { + this.isBone = true; - if ( video.readyState >= video.HAVE_CURRENT_DATA ) { + Object3D.call( this ); - scope.needsUpdate = true; + this.type = 'Bone'; - } + this.skin = skin; - } + }; - update(); + Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { -}; + constructor: Bone, -THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.VideoTexture.prototype.constructor = THREE.VideoTexture; + copy: function ( source ) { -// File:src/objects/Group.js + Object3D.prototype.copy.call( this, source ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.skin = source.skin; -THREE.Group = function () { + return this; - THREE.Object3D.call( this ); + } - this.type = 'Group'; + } ); -}; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ -THREE.Group.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + function SkinnedMesh ( geometry, material, useVertexTexture ) { + this.isSkinnedMesh = true; - constructor: THREE.Group + Mesh.call( this, geometry, material ); -} ); + this.type = 'SkinnedMesh'; -// File:src/objects/Points.js + this.bindMode = "attached"; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); -/** - * @author alteredq / http://alteredqualia.com/ - */ + // init bones -THREE.Points = function ( geometry, material ) { + // TODO: remove bone creation as there is no reason (other than + // convenience) for THREE.SkinnedMesh to do this. - THREE.Object3D.call( this ); + var bones = []; - this.type = 'Points'; + if ( this.geometry && this.geometry.bones !== undefined ) { - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } ); + var bone, gbone; -}; + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { -THREE.Points.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + gbone = this.geometry.bones[ b ]; - constructor: THREE.Points, + bone = new Bone( this ); + bones.push( bone ); - raycast: ( function () { + bone.name = gbone.name; + bone.position.fromArray( gbone.pos ); + bone.quaternion.fromArray( gbone.rotq ); + if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + } - return function raycast( raycaster, intersects ) { + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { - var object = this; - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; - var threshold = raycaster.params.Points.threshold; + gbone = this.geometry.bones[ b ]; - // Checking boundingSphere distance to ray + if ( gbone.parent !== - 1 && gbone.parent !== null && + bones[ gbone.parent ] !== undefined ) { - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + bones[ gbone.parent ].add( bones[ b ] ); - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + } else { - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + this.add( bones[ b ] ); - // + } - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + } - var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - var localThresholdSq = localThreshold * localThreshold; - var position = new THREE.Vector3(); + } - function testPoint( point, index ) { + this.normalizeSkinWeights(); - var rayPointDistanceSq = ray.distanceSqToPoint( point ); + this.updateMatrixWorld( true ); + this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); - if ( rayPointDistanceSq < localThresholdSq ) { + }; - var intersectPoint = ray.closestPointToPoint( point ); - intersectPoint.applyMatrix4( matrixWorld ); - var distance = raycaster.ray.origin.distanceTo( intersectPoint ); + SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { - if ( distance < raycaster.near || distance > raycaster.far ) return; + constructor: SkinnedMesh, - intersects.push( { + bind: function( skeleton, bindMatrix ) { - distance: distance, - distanceToRay: Math.sqrt( rayPointDistanceSq ), - point: intersectPoint.clone(), - index: index, - face: null, - object: object + this.skeleton = skeleton; - } ); + if ( bindMatrix === undefined ) { - } + this.updateMatrixWorld( true ); - } + this.skeleton.calculateInverses(); - if ( geometry instanceof THREE.BufferGeometry ) { + bindMatrix = this.matrixWorld; - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + } - if ( index !== null ) { + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.getInverse( bindMatrix ); - var indices = index.array; + }, - for ( var i = 0, il = indices.length; i < il; i ++ ) { + pose: function () { - var a = indices[ i ]; + this.skeleton.pose(); - position.fromArray( positions, a * 3 ); + }, - testPoint( position, a ); + normalizeSkinWeights: function () { - } + if ( (this.geometry && this.geometry.isGeometry) ) { - } else { + for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) { - for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { + var sw = this.geometry.skinWeights[ i ]; - position.fromArray( positions, i * 3 ); + var scale = 1.0 / sw.lengthManhattan(); - testPoint( position, i ); + if ( scale !== Infinity ) { - } + sw.multiplyScalar( scale ); - } + } else { - } else { + sw.set( 1, 0, 0, 0 ); // do something reasonable - var vertices = geometry.vertices; + } - for ( var i = 0, l = vertices.length; i < l; i ++ ) { + } - testPoint( vertices[ i ], i ); + } else if ( (this.geometry && this.geometry.isBufferGeometry) ) { - } + var vec = new Vector4(); - } + var skinWeight = this.geometry.attributes.skinWeight; - }; + for ( var i = 0; i < skinWeight.count; i ++ ) { - }() ), + vec.x = skinWeight.getX( i ); + vec.y = skinWeight.getY( i ); + vec.z = skinWeight.getZ( i ); + vec.w = skinWeight.getW( i ); - clone: function () { + var scale = 1.0 / vec.lengthManhattan(); - return new this.constructor( this.geometry, this.material ).copy( this ); + if ( scale !== Infinity ) { - } + vec.multiplyScalar( scale ); -} ); + } else { -// File:src/objects/Line.js + vec.set( 1, 0, 0, 0 ); // do something reasonable -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.Line = function ( geometry, material, mode ) { + skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w ); - if ( mode === 1 ) { + } - console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); - return new THREE.LineSegments( geometry, material ); + } - } + }, - THREE.Object3D.call( this ); + updateMatrixWorld: function( force ) { - this.type = 'Line'; + Mesh.prototype.updateMatrixWorld.call( this, true ); - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } ); + if ( this.bindMode === "attached" ) { -}; + this.bindMatrixInverse.getInverse( this.matrixWorld ); -THREE.Line.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + } else if ( this.bindMode === "detached" ) { - constructor: THREE.Line, + this.bindMatrixInverse.getInverse( this.bindMatrix ); - raycast: ( function () { + } else { - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode ); - return function raycast( raycaster, intersects ) { + } - var precision = raycaster.linePrecision; - var precisionSq = precision * precision; + }, - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; + clone: function() { - // Checking boundingSphere distance to ray + return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this ); - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + } - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + } ); - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * linecap: "round", + * linejoin: "round" + * } + */ - // + function LineBasicMaterial ( parameters ) { + this.isLineBasicMaterial = this.isMaterial = true; - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + Material.call( this ); - var vStart = new THREE.Vector3(); - var vEnd = new THREE.Vector3(); - var interSegment = new THREE.Vector3(); - var interRay = new THREE.Vector3(); - var step = this instanceof THREE.LineSegments ? 2 : 1; + this.type = 'LineBasicMaterial'; - if ( geometry instanceof THREE.BufferGeometry ) { + this.color = new Color( 0xffffff ); - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; - if ( index !== null ) { + this.lights = false; - var indices = index.array; + this.setValues( parameters ); - for ( var i = 0, l = indices.length - 1; i < l; i += step ) { + }; - var a = indices[ i ]; - var b = indices[ i + 1 ]; + LineBasicMaterial.prototype = Object.create( Material.prototype ); + LineBasicMaterial.prototype.constructor = LineBasicMaterial; - vStart.fromArray( positions, a * 3 ); - vEnd.fromArray( positions, b * 3 ); + LineBasicMaterial.prototype.copy = function ( source ) { - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + Material.prototype.copy.call( this, source ); - if ( distSq > precisionSq ) continue; + this.color.copy( source.color ); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; - var distance = raycaster.ray.origin.distanceTo( interRay ); + return this; - if ( distance < raycaster.near || distance > raycaster.far ) continue; + }; - intersects.push( { + /** + * @author mrdoob / http://mrdoob.com/ + */ - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + function Line ( geometry, material, mode ) { + this.isLine = true; - } ); + if ( mode === 1 ) { - } + console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); + return new LineSegments( geometry, material ); - } else { + } - for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { + Object3D.call( this ); - vStart.fromArray( positions, 3 * i ); - vEnd.fromArray( positions, 3 * i + 3 ); + this.type = 'Line'; - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); - if ( distSq > precisionSq ) continue; + }; - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + Line.prototype = Object.assign( Object.create( Object3D.prototype ), { - var distance = raycaster.ray.origin.distanceTo( interRay ); + constructor: Line, - if ( distance < raycaster.near || distance > raycaster.far ) continue; + raycast: ( function () { - intersects.push( { + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + return function raycast( raycaster, intersects ) { - } ); + var precision = raycaster.linePrecision; + var precisionSq = precision * precision; - } + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; - } + // Checking boundingSphere distance to ray - } else if ( geometry instanceof THREE.Geometry ) { + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - var vertices = geometry.vertices; - var nbVertices = vertices.length; + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - for ( var i = 0; i < nbVertices - 1; i += step ) { + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); + // - if ( distSq > precisionSq ) continue; + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + var vStart = new Vector3(); + var vEnd = new Vector3(); + var interSegment = new Vector3(); + var interRay = new Vector3(); + var step = (this && this.isLineSegments) ? 2 : 1; - var distance = raycaster.ray.origin.distanceTo( interRay ); + if ( (geometry && geometry.isBufferGeometry) ) { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - intersects.push( { + if ( index !== null ) { - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + var indices = index.array; - } ); + for ( var i = 0, l = indices.length - 1; i < l; i += step ) { - } + var a = indices[ i ]; + var b = indices[ i + 1 ]; - } + vStart.fromArray( positions, a * 3 ); + vEnd.fromArray( positions, b * 3 ); - }; + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - }() ), + if ( distSq > precisionSq ) continue; - clone: function () { + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - return new this.constructor( this.geometry, this.material ).copy( this ); + var distance = raycaster.ray.origin.distanceTo( interRay ); - } + if ( distance < raycaster.near || distance > raycaster.far ) continue; -} ); + intersects.push( { -// File:src/objects/LineSegments.js + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this -/** - * @author mrdoob / http://mrdoob.com/ - */ + } ); -THREE.LineSegments = function ( geometry, material ) { + } - THREE.Line.call( this, geometry, material ); + } else { - this.type = 'LineSegments'; + for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { -}; + vStart.fromArray( positions, 3 * i ); + vEnd.fromArray( positions, 3 * i + 3 ); -THREE.LineSegments.prototype = Object.assign( Object.create( THREE.Line.prototype ), { + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - constructor: THREE.LineSegments + if ( distSq > precisionSq ) continue; -} ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation -// File:src/objects/Mesh.js + var distance = raycaster.ray.origin.distanceTo( interRay ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author jonobr1 / http://jonobr1.com/ - */ + if ( distance < raycaster.near || distance > raycaster.far ) continue; -THREE.Mesh = function ( geometry, material ) { + intersects.push( { - THREE.Object3D.call( this ); + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - this.type = 'Mesh'; + } ); - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ); + } - this.drawMode = THREE.TrianglesDrawMode; + } - this.updateMorphTargets(); + } else if ( (geometry && geometry.isGeometry) ) { -}; + var vertices = geometry.vertices; + var nbVertices = vertices.length; -THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + for ( var i = 0; i < nbVertices - 1; i += step ) { - constructor: THREE.Mesh, + var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); - setDrawMode: function ( value ) { + if ( distSq > precisionSq ) continue; - this.drawMode = value; + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - }, + var distance = raycaster.ray.origin.distanceTo( interRay ); - copy: function ( source ) { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - THREE.Object3D.prototype.copy.call( this, source ); + intersects.push( { - this.drawMode = source.drawMode; + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - return this; + } ); - }, + } - updateMorphTargets: function () { + } - if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { + }; - this.morphTargetBase = - 1; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + }() ), - for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { + clone: function () { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; + return new this.constructor( this.geometry, this.material ).copy( this ); - } + } - } + } ); - }, + /** + * @author mrdoob / http://mrdoob.com/ + */ - getMorphTargetIndexByName: function ( name ) { + function LineSegments ( geometry, material ) { + this.isLineSegments = true; - if ( this.morphTargetDictionary[ name ] !== undefined ) { + Line.call( this, geometry, material ); - return this.morphTargetDictionary[ name ]; + this.type = 'LineSegments'; - } + }; - console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); + LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { - return 0; + constructor: LineSegments - }, + } ); - raycast: ( function () { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * size: , + * sizeAttenuation: + * } + */ - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + function PointsMaterial ( parameters ) { + this.isPointsMaterial = this.isMaterial = true; - var vA = new THREE.Vector3(); - var vB = new THREE.Vector3(); - var vC = new THREE.Vector3(); + Material.call( this ); - var tempA = new THREE.Vector3(); - var tempB = new THREE.Vector3(); - var tempC = new THREE.Vector3(); + this.type = 'PointsMaterial'; - var uvA = new THREE.Vector2(); - var uvB = new THREE.Vector2(); - var uvC = new THREE.Vector2(); + this.color = new Color( 0xffffff ); - var barycoord = new THREE.Vector3(); + this.map = null; - var intersectionPoint = new THREE.Vector3(); - var intersectionPointWorld = new THREE.Vector3(); + this.size = 1; + this.sizeAttenuation = true; - function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { + this.lights = false; - THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); + this.setValues( parameters ); - uv1.multiplyScalar( barycoord.x ); - uv2.multiplyScalar( barycoord.y ); - uv3.multiplyScalar( barycoord.z ); + }; - uv1.add( uv2 ).add( uv3 ); + PointsMaterial.prototype = Object.create( Material.prototype ); + PointsMaterial.prototype.constructor = PointsMaterial; - return uv1.clone(); + PointsMaterial.prototype.copy = function ( source ) { - } + Material.prototype.copy.call( this, source ); - function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) { + this.color.copy( source.color ); - var intersect; - var material = object.material; + this.map = source.map; - if ( material.side === THREE.BackSide ) { + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; - intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + return this; - } else { + }; - intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point ); + /** + * @author alteredq / http://alteredqualia.com/ + */ - } + function Points ( geometry, material ) { + this.isPoints = true; - if ( intersect === null ) return null; + Object3D.call( this ); - intersectionPointWorld.copy( point ); - intersectionPointWorld.applyMatrix4( object.matrixWorld ); + this.type = 'Points'; - var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); - if ( distance < raycaster.near || distance > raycaster.far ) return null; + }; - return { - distance: distance, - point: intersectionPointWorld.clone(), - object: object - }; + Points.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Points, - function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) { + raycast: ( function () { - vA.fromArray( positions, a * 3 ); - vB.fromArray( positions, b * 3 ); - vC.fromArray( positions, c * 3 ); + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint ); + return function raycast( raycaster, intersects ) { - if ( intersection ) { + var object = this; + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; + var threshold = raycaster.params.Points.threshold; - if ( uvs ) { + // Checking boundingSphere distance to ray - uvA.fromArray( uvs, a * 2 ); - uvB.fromArray( uvs, b * 2 ); - uvC.fromArray( uvs, c * 2 ); + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - } + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ); - intersection.faceIndex = a; + // - } + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - return intersection; + var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + var localThresholdSq = localThreshold * localThreshold; + var position = new Vector3(); - } + function testPoint( point, index ) { - return function raycast( raycaster, intersects ) { + var rayPointDistanceSq = ray.distanceSqToPoint( point ); - var geometry = this.geometry; - var material = this.material; - var matrixWorld = this.matrixWorld; + if ( rayPointDistanceSq < localThresholdSq ) { - if ( material === undefined ) return; + var intersectPoint = ray.closestPointToPoint( point ); + intersectPoint.applyMatrix4( matrixWorld ); - // Checking boundingSphere distance to ray + var distance = raycaster.ray.origin.distanceTo( intersectPoint ); - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + if ( distance < raycaster.near || distance > raycaster.far ) return; - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + intersects.push( { - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint.clone(), + index: index, + face: null, + object: object - // + } ); - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + } - // Check boundingBox before continuing + } - if ( geometry.boundingBox !== null ) { + if ( (geometry && geometry.isBufferGeometry) ) { - if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - } + if ( index !== null ) { - var uvs, intersection; + var indices = index.array; - if ( geometry instanceof THREE.BufferGeometry ) { + for ( var i = 0, il = indices.length; i < il; i ++ ) { - var a, b, c; - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + var a = indices[ i ]; - if ( attributes.uv !== undefined ) { + position.fromArray( positions, a * 3 ); - uvs = attributes.uv.array; + testPoint( position, a ); - } + } - if ( index !== null ) { + } else { - var indices = index.array; + for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { - for ( var i = 0, l = indices.length; i < l; i += 3 ) { + position.fromArray( positions, i * 3 ); - a = indices[ i ]; - b = indices[ i + 1 ]; - c = indices[ i + 2 ]; + testPoint( position, i ); - intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); + } - if ( intersection ) { + } - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics - intersects.push( intersection ); + } else { - } + var vertices = geometry.vertices; - } + for ( var i = 0, l = vertices.length; i < l; i ++ ) { - } else { + testPoint( vertices[ i ], i ); + } - for ( var i = 0, l = positions.length; i < l; i += 9 ) { + } - a = i / 3; - b = a + 1; - c = a + 2; + }; - intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); + }() ), - if ( intersection ) { + clone: function () { - intersection.index = a; // triangle number in positions buffer semantics - intersects.push( intersection ); + return new this.constructor( this.geometry, this.material ).copy( this ); - } + } - } + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - } else if ( geometry instanceof THREE.Geometry ) { + function Group () { + this.isGroup = true; - var fvA, fvB, fvC; - var isFaceMaterial = material instanceof THREE.MultiMaterial; - var materials = isFaceMaterial === true ? material.materials : null; + Object3D.call( this ); - var vertices = geometry.vertices; - var faces = geometry.faces; - var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; - if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; + this.type = 'Group'; - for ( var f = 0, fl = faces.length; f < fl; f ++ ) { + }; - var face = faces[ f ]; - var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material; + Group.prototype = Object.assign( Object.create( Object3D.prototype ), { - if ( faceMaterial === undefined ) continue; + constructor: Group - fvA = vertices[ face.a ]; - fvB = vertices[ face.b ]; - fvC = vertices[ face.c ]; + } ); - if ( faceMaterial.morphTargets === true ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - var morphTargets = geometry.morphTargets; - var morphInfluences = this.morphTargetInfluences; + function VideoTexture ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + this.isVideoTexture = this.isTexture = true; - vA.set( 0, 0, 0 ); - vB.set( 0, 0, 0 ); - vC.set( 0, 0, 0 ); + Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { + this.generateMipmaps = false; - var influence = morphInfluences[ t ]; + var scope = this; - if ( influence === 0 ) continue; + function update() { - var targets = morphTargets[ t ].vertices; + requestAnimationFrame( update ); - vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence ); - vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence ); - vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence ); + if ( video.readyState >= video.HAVE_CURRENT_DATA ) { - } + scope.needsUpdate = true; - vA.add( fvA ); - vB.add( fvB ); - vC.add( fvC ); + } - fvA = vA; - fvB = vB; - fvC = vC; + } - } + update(); - intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); + }; - if ( intersection ) { + VideoTexture.prototype = Object.create( Texture.prototype ); + VideoTexture.prototype.constructor = VideoTexture; - if ( uvs ) { + /** + * @author alteredq / http://alteredqualia.com/ + */ - var uvs_f = uvs[ f ]; - uvA.copy( uvs_f[ 0 ] ); - uvB.copy( uvs_f[ 1 ] ); - uvC.copy( uvs_f[ 2 ] ); + function CompressedTexture ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.isCompressedTexture = this.isTexture = true; - intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - } + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; - intersection.face = face; - intersection.faceIndex = f; - intersects.push( intersection ); + // no flipping for cube textures + // (also flipping doesn't work for compressed textures ) - } + this.flipY = false; - } + // can't generate mipmaps for compressed textures + // mips must be embedded in DDS files - } + this.generateMipmaps = false; - }; + }; - }() ), + CompressedTexture.prototype = Object.create( Texture.prototype ); + CompressedTexture.prototype.constructor = CompressedTexture; - clone: function () { + /** + * @author mrdoob / http://mrdoob.com/ + */ - return new this.constructor( this.geometry, this.material ).copy( this ); + function CanvasTexture ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + this.isCanvasTexture = this.isTexture = true; - } + Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); -} ); + this.needsUpdate = true; -// File:src/objects/Bone.js + }; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + CanvasTexture.prototype = Object.create( Texture.prototype ); + CanvasTexture.prototype.constructor = CanvasTexture; -THREE.Bone = function ( skin ) { + /** + * @author Matt DesLauriers / @mattdesl + */ - THREE.Object3D.call( this ); + function DepthTexture ( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { + this.isDepthTexture = this.isTexture = true; - this.type = 'Bone'; + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, DepthFormat, type, anisotropy ); - this.skin = skin; + this.image = { width: width, height: height }; -}; + this.type = type !== undefined ? type : UnsignedShortType; -THREE.Bone.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - constructor: THREE.Bone, + this.flipY = false; + this.generateMipmaps = false; - copy: function ( source ) { + }; - THREE.Object3D.prototype.copy.call( this, source ); + DepthTexture.prototype = Object.create( Texture.prototype ); + DepthTexture.prototype.constructor = DepthTexture; - this.skin = source.skin; + /** + * @author mrdoob / http://mrdoob.com/ + */ - return this; + function ShadowMaterial () { + this.isShadowMaterial = this.isShaderMaterial = this.isMaterial = true; - } + ShaderMaterial.call( this, { + uniforms: exports.UniformsUtils.merge( [ + exports.UniformsLib[ "lights" ], + { + opacity: { value: 1.0 } + } + ] ), + vertexShader: exports.ShaderChunk[ 'shadow_vert' ], + fragmentShader: exports.ShaderChunk[ 'shadow_frag' ] + } ); -} ); + this.lights = true; + this.transparent = true; -// File:src/objects/Skeleton.js + Object.defineProperties( this, { + opacity: { + enumerable: true, + get: function () { + return this.uniforms.opacity.value; + }, + set: function ( value ) { + this.uniforms.opacity.value = value; + } + } + } ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author michael guerrero / http://realitymeltdown.com - * @author ikerr / http://verold.com - */ + }; -THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { + ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype ); + ShadowMaterial.prototype.constructor = ShadowMaterial; - this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.identityMatrix = new THREE.Matrix4(); + function RawShaderMaterial ( parameters ) { + this.isRawShaderMaterial = this.isShaderMaterial = this.isMaterial = true; - // copy the bone array + ShaderMaterial.call( this, parameters ); - bones = bones || []; + this.type = 'RawShaderMaterial'; - this.bones = bones.slice( 0 ); + }; - // create a bone texture or an array of floats + RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); + RawShaderMaterial.prototype.constructor = RawShaderMaterial; - if ( this.useVertexTexture ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - // layout (1 matrix = 4 pixels) - // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) - // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) - // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) - // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) - // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) + function MultiMaterial ( materials ) { + this.isMultiMaterial = true; + this.uuid = exports.Math.generateUUID(); - var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix - size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) ); - size = Math.max( size, 4 ); + this.type = 'MultiMaterial'; - this.boneTextureWidth = size; - this.boneTextureHeight = size; + this.materials = materials instanceof Array ? materials : []; - this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel - this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType ); + this.visible = true; - } else { + }; - this.boneMatrices = new Float32Array( 16 * this.bones.length ); + MultiMaterial.prototype = { - } + constructor: MultiMaterial, - // use the supplied bone inverses or calculate the inverses + toJSON: function ( meta ) { - if ( boneInverses === undefined ) { + var output = { + metadata: { + version: 4.2, + type: 'material', + generator: 'MaterialExporter' + }, + uuid: this.uuid, + type: this.type, + materials: [] + }; - this.calculateInverses(); + var materials = this.materials; - } else { + for ( var i = 0, l = materials.length; i < l; i ++ ) { - if ( this.bones.length === boneInverses.length ) { + var material = materials[ i ].toJSON( meta ); + delete material.metadata; - this.boneInverses = boneInverses.slice( 0 ); + output.materials.push( material ); - } else { + } - console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); + output.visible = this.visible; - this.boneInverses = []; + return output; - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + }, - this.boneInverses.push( new THREE.Matrix4() ); + clone: function () { - } + var material = new this.constructor(); - } + for ( var i = 0; i < this.materials.length; i ++ ) { - } + material.materials.push( this.materials[ i ].clone() ); -}; + } -Object.assign( THREE.Skeleton.prototype, { + material.visible = this.visible; - calculateInverses: function () { + return material; - this.boneInverses = []; + } - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + }; - var inverse = new THREE.Matrix4(); + /** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * color: , + * roughness: , + * metalness: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * roughnessMap: new THREE.Texture( ), + * + * metalnessMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * envMapIntensity: + * + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - if ( this.bones[ b ] ) { + function MeshStandardMaterial ( parameters ) { + this.isMeshStandardMaterial = this.isMaterial = true; - inverse.getInverse( this.bones[ b ].matrixWorld ); + Material.call( this ); - } + this.defines = { 'STANDARD': '' }; - this.boneInverses.push( inverse ); + this.type = 'MeshStandardMaterial'; - } + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 0.5; + this.metalness = 0.5; - }, + this.map = null; - pose: function () { + this.lightMap = null; + this.lightMapIntensity = 1.0; - var bone; + this.aoMap = null; + this.aoMapIntensity = 1.0; - // recover the bind-time world matrices + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + this.bumpMap = null; + this.bumpScale = 1; - bone = this.bones[ b ]; + this.normalMap = null; + this.normalScale = new Vector2( 1, 1 ); - if ( bone ) { + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - bone.matrixWorld.getInverse( this.boneInverses[ b ] ); + this.roughnessMap = null; - } + this.metalnessMap = null; - } + this.alphaMap = null; - // compute the local matrices, positions, rotations and scales + this.envMap = null; + this.envMapIntensity = 1.0; - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + this.refractionRatio = 0.98; - bone = this.bones[ b ]; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - if ( bone ) { + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - if ( bone.parent instanceof THREE.Bone ) { + this.setValues( parameters ); - bone.matrix.getInverse( bone.parent.matrixWorld ); - bone.matrix.multiply( bone.matrixWorld ); + }; - } else { + MeshStandardMaterial.prototype = Object.create( Material.prototype ); + MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; - bone.matrix.copy( bone.matrixWorld ); + MeshStandardMaterial.prototype.copy = function ( source ) { - } + Material.prototype.copy.call( this, source ); - bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + this.defines = { 'STANDARD': '' }; - } + this.color.copy( source.color ); + this.roughness = source.roughness; + this.metalness = source.metalness; - } + this.map = source.map; - }, + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - update: ( function () { + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - var offsetMatrix = new THREE.Matrix4(); + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - return function update() { + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - // flatten bone matrices to array + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - // compute the offset between the current and the original transform + this.roughnessMap = source.roughnessMap; - var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; + this.metalnessMap = source.metalnessMap; - offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); - offsetMatrix.toArray( this.boneMatrices, b * 16 ); + this.alphaMap = source.alphaMap; - } + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; - if ( this.useVertexTexture ) { + this.refractionRatio = source.refractionRatio; - this.boneTexture.needsUpdate = true; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - } + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - }; + return this; - } )(), + }; - clone: function () { + /** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * reflectivity: + * } + */ - return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); + function MeshPhysicalMaterial ( parameters ) { + this.isMeshPhysicalMaterial = this.isMeshStandardMaterial = this.isMaterial = true; - } + MeshStandardMaterial.call( this ); -} ); + this.defines = { 'PHYSICAL': '' }; -// File:src/objects/SkinnedMesh.js + this.type = 'MeshPhysicalMaterial'; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + this.reflectivity = 0.5; // maps to F0 = 0.04 -THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { + this.clearCoat = 0.0; + this.clearCoatRoughness = 0.0; - THREE.Mesh.call( this, geometry, material ); + this.setValues( parameters ); - this.type = 'SkinnedMesh'; + }; - this.bindMode = "attached"; - this.bindMatrix = new THREE.Matrix4(); - this.bindMatrixInverse = new THREE.Matrix4(); + MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); + MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; - // init bones + MeshPhysicalMaterial.prototype.copy = function ( source ) { - // TODO: remove bone creation as there is no reason (other than - // convenience) for THREE.SkinnedMesh to do this. + MeshStandardMaterial.prototype.copy.call( this, source ); - var bones = []; + this.defines = { 'PHYSICAL': '' }; - if ( this.geometry && this.geometry.bones !== undefined ) { + this.reflectivity = source.reflectivity; - var bone, gbone; + this.clearCoat = source.clearCoat; + this.clearCoatRoughness = source.clearCoatRoughness; - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + return this; - gbone = this.geometry.bones[ b ]; + }; - bone = new THREE.Bone( this ); - bones.push( bone ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * specular: , + * shininess: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - bone.name = gbone.name; - bone.position.fromArray( gbone.pos ); - bone.quaternion.fromArray( gbone.rotq ); - if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); + function MeshPhongMaterial ( parameters ) { + this.isMeshPhongMaterial = this.isMaterial = true; - } + Material.call( this ); - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + this.type = 'MeshPhongMaterial'; - gbone = this.geometry.bones[ b ]; + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; - if ( gbone.parent !== - 1 && gbone.parent !== null && - bones[ gbone.parent ] !== undefined ) { + this.map = null; - bones[ gbone.parent ].add( bones[ b ] ); + this.lightMap = null; + this.lightMapIntensity = 1.0; - } else { + this.aoMap = null; + this.aoMapIntensity = 1.0; - this.add( bones[ b ] ); + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - } + this.bumpMap = null; + this.bumpScale = 1; - } + this.normalMap = null; + this.normalScale = new Vector2( 1, 1 ); - } + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - this.normalizeSkinWeights(); + this.specularMap = null; - this.updateMatrixWorld( true ); - this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); + this.alphaMap = null; -}; + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; -THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype ), { + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - constructor: THREE.SkinnedMesh, + this.setValues( parameters ); - bind: function( skeleton, bindMatrix ) { + }; - this.skeleton = skeleton; + MeshPhongMaterial.prototype = Object.create( Material.prototype ); + MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; - if ( bindMatrix === undefined ) { + MeshPhongMaterial.prototype.copy = function ( source ) { - this.updateMatrixWorld( true ); + Material.prototype.copy.call( this, source ); - this.skeleton.calculateInverses(); + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; - bindMatrix = this.matrixWorld; + this.map = source.map; - } + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.bindMatrix.copy( bindMatrix ); - this.bindMatrixInverse.getInverse( bindMatrix ); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - }, + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - pose: function () { + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - this.skeleton.pose(); + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); - }, + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - normalizeSkinWeights: function () { + this.specularMap = source.specularMap; - if ( this.geometry instanceof THREE.Geometry ) { + this.alphaMap = source.alphaMap; - for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) { + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - var sw = this.geometry.skinWeights[ i ]; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - var scale = 1.0 / sw.lengthManhattan(); + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - if ( scale !== Infinity ) { + return this; - sw.multiplyScalar( scale ); + }; - } else { + /** + * @author mrdoob / http://mrdoob.com/ + * + * parameters = { + * opacity: , + * + * wireframe: , + * wireframeLinewidth: + * } + */ - sw.set( 1, 0, 0, 0 ); // do something reasonable + function MeshNormalMaterial ( parameters ) { + this.isMeshNormalMaterial = this.isMaterial = true; - } + Material.call( this, parameters ); - } + this.type = 'MeshNormalMaterial'; - } else if ( this.geometry instanceof THREE.BufferGeometry ) { + this.wireframe = false; + this.wireframeLinewidth = 1; - var vec = new THREE.Vector4(); + this.fog = false; + this.lights = false; + this.morphTargets = false; - var skinWeight = this.geometry.attributes.skinWeight; + this.setValues( parameters ); - for ( var i = 0; i < skinWeight.count; i ++ ) { + }; - vec.x = skinWeight.getX( i ); - vec.y = skinWeight.getY( i ); - vec.z = skinWeight.getZ( i ); - vec.w = skinWeight.getW( i ); + MeshNormalMaterial.prototype = Object.create( Material.prototype ); + MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; - var scale = 1.0 / vec.lengthManhattan(); + MeshNormalMaterial.prototype.copy = function ( source ) { - if ( scale !== Infinity ) { + Material.prototype.copy.call( this, source ); - vec.multiplyScalar( scale ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - } else { + return this; - vec.set( 1, 0, 0, 0 ); // do something reasonable + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w ); + function MeshLambertMaterial ( parameters ) { + this.isMeshLambertMaterial = this.isMaterial = true; - } + Material.call( this ); - } + this.type = 'MeshLambertMaterial'; - }, + this.color = new Color( 0xffffff ); // diffuse - updateMatrixWorld: function( force ) { + this.map = null; - THREE.Mesh.prototype.updateMatrixWorld.call( this, true ); + this.lightMap = null; + this.lightMapIntensity = 1.0; - if ( this.bindMode === "attached" ) { + this.aoMap = null; + this.aoMapIntensity = 1.0; - this.bindMatrixInverse.getInverse( this.matrixWorld ); + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - } else if ( this.bindMode === "detached" ) { + this.specularMap = null; - this.bindMatrixInverse.getInverse( this.bindMatrix ); + this.alphaMap = null; - } else { + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode ); + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - } + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - }, + this.setValues( parameters ); - clone: function() { + }; - return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this ); + MeshLambertMaterial.prototype = Object.create( Material.prototype ); + MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; - } + MeshLambertMaterial.prototype.copy = function ( source ) { -} ); + Material.prototype.copy.call( this, source ); -// File:src/objects/LOD.js + this.color.copy( source.color ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + this.map = source.map; -THREE.LOD = function () { + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - THREE.Object3D.call( this ); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - this.type = 'LOD'; + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - Object.defineProperties( this, { - levels: { - enumerable: true, - value: [] - } - } ); + this.specularMap = source.specularMap; -}; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; -THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - constructor: THREE.LOD, + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - copy: function ( source ) { + return this; - THREE.Object3D.prototype.copy.call( this, source, false ); + }; - var levels = source.levels; + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * + * scale: , + * dashSize: , + * gapSize: + * } + */ - for ( var i = 0, l = levels.length; i < l; i ++ ) { + function LineDashedMaterial ( parameters ) { + this.isLineDashedMaterial = this.isMaterial = true; - var level = levels[ i ]; + Material.call( this ); - this.addLevel( level.object.clone(), level.distance ); + this.type = 'LineDashedMaterial'; - } + this.color = new Color( 0xffffff ); - return this; + this.linewidth = 1; - }, + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; - addLevel: function ( object, distance ) { + this.lights = false; - if ( distance === undefined ) distance = 0; + this.setValues( parameters ); - distance = Math.abs( distance ); + }; - var levels = this.levels; + LineDashedMaterial.prototype = Object.create( Material.prototype ); + LineDashedMaterial.prototype.constructor = LineDashedMaterial; - for ( var l = 0; l < levels.length; l ++ ) { + LineDashedMaterial.prototype.copy = function ( source ) { - if ( distance < levels[ l ].distance ) { + Material.prototype.copy.call( this, source ); - break; + this.color.copy( source.color ); - } + this.linewidth = source.linewidth; - } + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; - levels.splice( l, 0, { distance: distance, object: object } ); + return this; - this.add( object ); + }; - }, + /** + * @author mrdoob / http://mrdoob.com/ + */ - getObjectForDistance: function ( distance ) { + exports.Cache = { - var levels = this.levels; + enabled: false, - for ( var i = 1, l = levels.length; i < l; i ++ ) { + files: {}, - if ( distance < levels[ i ].distance ) { + add: function ( key, file ) { - break; + if ( this.enabled === false ) return; - } + // console.log( 'THREE.Cache', 'Adding key:', key ); - } + this.files[ key ] = file; - return levels[ i - 1 ].object; + }, - }, + get: function ( key ) { - raycast: ( function () { + if ( this.enabled === false ) return; - var matrixPosition = new THREE.Vector3(); + // console.log( 'THREE.Cache', 'Checking key:', key ); - return function raycast( raycaster, intersects ) { + return this.files[ key ]; - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + }, - var distance = raycaster.ray.origin.distanceTo( matrixPosition ); + remove: function ( key ) { - this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + delete this.files[ key ]; - }; + }, - }() ), + clear: function () { - update: function () { + this.files = {}; - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + } - return function update( camera ) { + }; - var levels = this.levels; + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( levels.length > 1 ) { + function LoadingManager ( onLoad, onProgress, onError ) { + this.isLoadingManager = true; - v1.setFromMatrixPosition( camera.matrixWorld ); - v2.setFromMatrixPosition( this.matrixWorld ); + var scope = this; - var distance = v1.distanceTo( v2 ); + var isLoading = false, itemsLoaded = 0, itemsTotal = 0; - levels[ 0 ].object.visible = true; + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; - for ( var i = 1, l = levels.length; i < l; i ++ ) { + this.itemStart = function ( url ) { - if ( distance >= levels[ i ].distance ) { + itemsTotal ++; - levels[ i - 1 ].object.visible = false; - levels[ i ].object.visible = true; + if ( isLoading === false ) { - } else { + if ( scope.onStart !== undefined ) { - break; + scope.onStart( url, itemsLoaded, itemsTotal ); - } + } - } + } - for ( ; i < l; i ++ ) { + isLoading = true; - levels[ i ].object.visible = false; + }; - } + this.itemEnd = function ( url ) { - } + itemsLoaded ++; - }; + if ( scope.onProgress !== undefined ) { - }(), + scope.onProgress( url, itemsLoaded, itemsTotal ); - toJSON: function ( meta ) { + } - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + if ( itemsLoaded === itemsTotal ) { - data.object.levels = []; + isLoading = false; - var levels = this.levels; + if ( scope.onLoad !== undefined ) { - for ( var i = 0, l = levels.length; i < l; i ++ ) { + scope.onLoad(); - var level = levels[ i ]; + } - data.object.levels.push( { - object: level.object.uuid, - distance: level.distance - } ); + } - } + }; - return data; + this.itemError = function ( url ) { - } + if ( scope.onError !== undefined ) { -} ); + scope.onError( url ); -// File:src/objects/Sprite.js + } -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + }; -THREE.Sprite = function ( material ) { + }; - THREE.Object3D.call( this ); + exports.DefaultLoadingManager = new LoadingManager(); - this.type = 'Sprite'; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial(); + function XHRLoader ( manager ) { + this.isXHRLoader = true; -}; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; -THREE.Sprite.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + }; - constructor: THREE.Sprite, + Object.assign( XHRLoader.prototype, { - raycast: ( function () { + load: function ( url, onLoad, onProgress, onError ) { - var matrixPosition = new THREE.Vector3(); + if ( this.path !== undefined ) url = this.path + url; - return function raycast( raycaster, intersects ) { + var scope = this; - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + var cached = exports.Cache.get( url ); - var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition ); - var guessSizeSq = this.scale.x * this.scale.y / 4; + if ( cached !== undefined ) { - if ( distanceSq > guessSizeSq ) { + scope.manager.itemStart( url ); - return; + setTimeout( function () { - } + if ( onLoad ) onLoad( cached ); - intersects.push( { + scope.manager.itemEnd( url ); - distance: Math.sqrt( distanceSq ), - point: this.position, - face: null, - object: this + }, 0 ); - } ); + return cached; - }; + } - }() ), + var request = new XMLHttpRequest(); + request.overrideMimeType( 'text/plain' ); + request.open( 'GET', url, true ); - clone: function () { + request.addEventListener( 'load', function ( event ) { - return new this.constructor( this.material ).copy( this ); + var response = event.target.response; - } + exports.Cache.add( url, response ); -} ); + if ( this.status === 200 ) { -// File:src/objects/LensFlare.js + if ( onLoad ) onLoad( response ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + scope.manager.itemEnd( url ); -THREE.LensFlare = function ( texture, size, distance, blending, color ) { + } else if ( this.status === 0 ) { - THREE.Object3D.call( this ); + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. - this.lensFlares = []; + console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' ); - this.positionScreen = new THREE.Vector3(); - this.customUpdateCallback = undefined; + if ( onLoad ) onLoad( response ); - if ( texture !== undefined ) { + scope.manager.itemEnd( url ); - this.add( texture, size, distance, blending, color ); + } else { - } + if ( onError ) onError( event ); -}; + scope.manager.itemError( url ); -THREE.LensFlare.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + } - constructor: THREE.LensFlare, + }, false ); - copy: function ( source ) { + if ( onProgress !== undefined ) { - THREE.Object3D.prototype.copy.call( this, source ); + request.addEventListener( 'progress', function ( event ) { - this.positionScreen.copy( source.positionScreen ); - this.customUpdateCallback = source.customUpdateCallback; + onProgress( event ); - for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) { + }, false ); - this.lensFlares.push( source.lensFlares[ i ] ); + } - } + request.addEventListener( 'error', function ( event ) { - return this; + if ( onError ) onError( event ); - }, + scope.manager.itemError( url ); - add: function ( texture, size, distance, blending, color, opacity ) { - - if ( size === undefined ) size = - 1; - if ( distance === undefined ) distance = 0; - if ( opacity === undefined ) opacity = 1; - if ( color === undefined ) color = new THREE.Color( 0xffffff ); - if ( blending === undefined ) blending = THREE.NormalBlending; - - distance = Math.min( distance, Math.max( 0, distance ) ); - - this.lensFlares.push( { - texture: texture, // THREE.Texture - size: size, // size in pixels (-1 = use texture.width) - distance: distance, // distance (0-1) from light source (0=at light source) - x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back - scale: 1, // scale - rotation: 0, // rotation - opacity: opacity, // opacity - color: color, // color - blending: blending // blending - } ); + }, false ); - }, + if ( this.responseType !== undefined ) request.responseType = this.responseType; + if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; - /* - * Update lens flares update positions on all flares based on the screen position - * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way. - */ + request.send( null ); - updateLensFlares: function () { + scope.manager.itemStart( url ); - var f, fl = this.lensFlares.length; - var flare; - var vecX = - this.positionScreen.x * 2; - var vecY = - this.positionScreen.y * 2; + return request; - for ( f = 0; f < fl; f ++ ) { + }, - flare = this.lensFlares[ f ]; + setPath: function ( value ) { - flare.x = this.positionScreen.x + vecX * flare.distance; - flare.y = this.positionScreen.y + vecY * flare.distance; + this.path = value; + return this; - flare.wantedRotation = flare.x * Math.PI * 0.25; - flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; + }, - } + setResponseType: function ( value ) { - } + this.responseType = value; + return this; -} ); + }, -// File:src/scenes/Scene.js + setWithCredentials: function ( value ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.withCredentials = value; + return this; -THREE.Scene = function () { + } - THREE.Object3D.call( this ); + } ); - this.type = 'Scene'; + /** + * @author mrdoob / http://mrdoob.com/ + * + * Abstract Base class to block based textures loader (dds, pvr, ...) + */ - this.background = null; - this.fog = null; - this.overrideMaterial = null; + function CompressedTextureLoader ( manager ) { + this.isCompressedTextureLoader = true; - this.autoUpdate = true; // checked by the renderer + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; -}; + // override in sub classes + this._parser = null; -THREE.Scene.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Scene.prototype.constructor = THREE.Scene; + }; -THREE.Scene.prototype.copy = function ( source, recursive ) { + Object.assign( CompressedTextureLoader.prototype, { - THREE.Object3D.prototype.copy.call( this, source, recursive ); + load: function ( url, onLoad, onProgress, onError ) { - if ( source.background !== null ) this.background = source.background.clone(); - if ( source.fog !== null ) this.fog = source.fog.clone(); - if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + var scope = this; - this.autoUpdate = source.autoUpdate; - this.matrixAutoUpdate = source.matrixAutoUpdate; + var images = []; - return this; + var texture = new CompressedTexture(); + texture.image = images; -}; + var loader = new XHRLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); -// File:src/scenes/Fog.js + function loadTexture( i ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + loader.load( url[ i ], function ( buffer ) { -THREE.Fog = function ( color, near, far ) { + var texDatas = scope._parser( buffer, true ); - this.name = ''; + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; - this.color = new THREE.Color( color ); + loaded += 1; - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; + if ( loaded === 6 ) { -}; + if ( texDatas.mipmapCount === 1 ) + texture.minFilter = LinearFilter; -THREE.Fog.prototype.clone = function () { + texture.format = texDatas.format; + texture.needsUpdate = true; - return new THREE.Fog( this.color.getHex(), this.near, this.far ); + if ( onLoad ) onLoad( texture ); -}; + } -// File:src/scenes/FogExp2.js + }, onProgress, onError ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + } -THREE.FogExp2 = function ( color, density ) { + if ( Array.isArray( url ) ) { - this.name = ''; + var loaded = 0; - this.color = new THREE.Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; + for ( var i = 0, il = url.length; i < il; ++ i ) { -}; + loadTexture( i ); -THREE.FogExp2.prototype.clone = function () { + } - return new THREE.FogExp2( this.color.getHex(), this.density ); + } else { -}; + // compressed cubemap texture stored in a single DDS file -// File:src/renderers/shaders/ShaderChunk.js + loader.load( url, function ( buffer ) { -THREE.ShaderChunk = {}; + var texDatas = scope._parser( buffer, true ); -// File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl + if ( texDatas.isCubemap ) { -THREE.ShaderChunk[ 'alphamap_fragment' ] = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n"; + var faces = texDatas.mipmaps.length / texDatas.mipmapCount; -// File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl + for ( var f = 0; f < faces; f ++ ) { -THREE.ShaderChunk[ 'alphamap_pars_fragment' ] = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif\n"; + images[ f ] = { mipmaps : [] }; -// File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl + for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { -THREE.ShaderChunk[ 'alphatest_fragment' ] = "#ifdef ALPHATEST\n if ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n"; + images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); + images[ f ].format = texDatas.format; + images[ f ].width = texDatas.width; + images[ f ].height = texDatas.height; -// File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl + } -THREE.ShaderChunk[ 'aomap_fragment' ] = "#ifdef USE_AOMAP\n float ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n #if defined( USE_ENVMAP ) && defined( PHYSICAL )\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n #endif\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl + } else { -THREE.ShaderChunk[ 'aomap_pars_fragment' ] = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif"; + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; -// File:src/renderers/shaders/ShaderChunk/begin_vertex.glsl + } -THREE.ShaderChunk[ 'begin_vertex' ] = "\nvec3 transformed = vec3( position );\n"; + if ( texDatas.mipmapCount === 1 ) { -// File:src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl + texture.minFilter = LinearFilter; -THREE.ShaderChunk[ 'beginnormal_vertex' ] = "\nvec3 objectNormal = vec3( normal );\n"; + } -// File:src/renderers/shaders/ShaderChunk/bsdfs.glsl + texture.format = texDatas.format; + texture.needsUpdate = true; -THREE.ShaderChunk[ 'bsdfs' ] = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n return any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n if( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n float maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n return distanceFalloff * maxDistanceCutoffFactor;\n#else\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n }\n return 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n return ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = pow2( alpha );\n float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n return 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = pow2( alpha );\n float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n return 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = pow2( alpha );\n float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n return specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n return ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n return sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; + if ( onLoad ) onLoad( texture ); -// File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl + }, onProgress, onError ); -THREE.ShaderChunk[ 'bumpmap_pars_fragment' ] = "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 );\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl + return texture; -THREE.ShaderChunk[ 'clipping_planes_fragment' ] = "#if NUM_CLIPPING_PLANES > 0\n for ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n vec4 plane = clippingPlanes[ i ];\n if ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n }\n#endif\n"; + }, -// File:src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl + setPath: function ( value ) { -THREE.ShaderChunk[ 'clipping_planes_pars_fragment' ] = "#if NUM_CLIPPING_PLANES > 0\n #if ! defined( PHYSICAL ) && ! defined( PHONG )\n varying vec3 vViewPosition;\n #endif\n uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n"; + this.path = value; + return this; -// File:src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl + } -THREE.ShaderChunk[ 'clipping_planes_pars_vertex' ] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n varying vec3 vViewPosition;\n#endif\n"; + } ); -// File:src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl + /** + * @author Nikos M. / https://github.com/foo123/ + * + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + */ -THREE.ShaderChunk[ 'clipping_planes_vertex' ] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n vViewPosition = - mvPosition.xyz;\n#endif\n"; + var DataTextureLoader = BinaryTextureLoader; + function BinaryTextureLoader ( manager ) { -// File:src/renderers/shaders/ShaderChunk/color_fragment.glsl + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; -THREE.ShaderChunk[ 'color_fragment' ] = "#ifdef USE_COLOR\n diffuseColor.rgb *= vColor;\n#endif"; + // override in sub classes + this._parser = null; -// File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl + }; -THREE.ShaderChunk[ 'color_pars_fragment' ] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif\n"; + Object.assign( BinaryTextureLoader.prototype, { -// File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl + load: function ( url, onLoad, onProgress, onError ) { -THREE.ShaderChunk[ 'color_pars_vertex' ] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif"; + var scope = this; -// File:src/renderers/shaders/ShaderChunk/color_vertex.glsl + var texture = new DataTexture(); -THREE.ShaderChunk[ 'color_vertex' ] = "#ifdef USE_COLOR\n vColor.xyz = color.xyz;\n#endif"; + var loader = new XHRLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); -// File:src/renderers/shaders/ShaderChunk/common.glsl + loader.load( url, function ( buffer ) { -THREE.ShaderChunk[ 'common' ] = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n}\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n bool visible;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\nstruct GeometricContext {\n vec3 position;\n vec3 normal;\n vec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n float distance = dot( planeNormal, point - pointOnPlane );\n return - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\n"; + var texData = scope._parser( buffer ); -// File:src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl + if ( ! texData ) return; -THREE.ShaderChunk[ 'cube_uv_reflection_fragment' ] = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n vec3 absDirection = abs(direction);\n int face = -1;\n if( absDirection.x > absDirection.z ) {\n if(absDirection.x > absDirection.y )\n face = direction.x > 0.0 ? 0 : 3;\n else\n face = direction.y > 0.0 ? 1 : 4;\n }\n else {\n if(absDirection.z > absDirection.y )\n face = direction.z > 0.0 ? 2 : 5;\n else\n face = direction.y > 0.0 ? 1 : 4;\n }\n return face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n float scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n float dxRoughness = dFdx(roughness);\n float dyRoughness = dFdy(roughness);\n vec3 dx = dFdx( vec * scale * dxRoughness );\n vec3 dy = dFdy( vec * scale * dyRoughness );\n float d = max( dot( dx, dx ), dot( dy, dy ) );\n d = clamp(d, 1.0, cubeUV_rangeClamp);\n float mipLevel = 0.5 * log2(d);\n return vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n mipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n float a = 16.0 * cubeUV_rcpTextureSize;\n vec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n vec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n float powScale = exp2_packed.x * exp2_packed.y;\n float scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n float mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n bool bRes = mipLevel == 0.0;\n scale = bRes && (scale < a) ? a : scale;\n vec3 r;\n vec2 offset;\n int face = getFaceFromDirection(direction);\n float rcpPowScale = 1.0 / powScale;\n if( face == 0) {\n r = vec3(direction.x, -direction.z, direction.y);\n offset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n }\n else if( face == 1) {\n r = vec3(direction.y, direction.x, direction.z);\n offset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n }\n else if( face == 2) {\n r = vec3(direction.z, direction.x, direction.y);\n offset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n }\n else if( face == 3) {\n r = vec3(direction.x, direction.z, direction.y);\n offset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n }\n else if( face == 4) {\n r = vec3(direction.y, direction.x, -direction.z);\n offset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n }\n else {\n r = vec3(direction.z, -direction.x, direction.y);\n offset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n }\n r = normalize(r);\n float texelOffset = 0.5 * cubeUV_rcpTextureSize;\n vec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n vec2 base = offset + vec2( texelOffset );\n return base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n float roughnessVal = roughness* cubeUV_maxLods3;\n float r1 = floor(roughnessVal);\n float r2 = r1 + 1.0;\n float t = fract(roughnessVal);\n vec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n float s = mipInfo.y;\n float level0 = mipInfo.x;\n float level1 = level0 + 1.0;\n level1 = level1 > 5.0 ? 5.0 : level1;\n level0 += min( floor( s + 0.5 ), 5.0 );\n vec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n vec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n vec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n vec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n vec4 result = mix(color10, color20, t);\n return vec4(result.rgb, 1.0);\n}\n#endif\n"; + if ( undefined !== texData.image ) { -// File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl + texture.image = texData.image; -THREE.ShaderChunk[ 'defaultnormal_vertex' ] = "#ifdef FLIP_SIDED\n objectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; + } else if ( undefined !== texData.data ) { -// File:src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; -THREE.ShaderChunk[ 'displacementmap_vertex' ] = "#ifdef USE_DISPLACEMENTMAP\n transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl + texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping; -THREE.ShaderChunk[ 'displacementmap_pars_vertex' ] = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif\n"; + texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter; + texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter; -// File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl + texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; -THREE.ShaderChunk[ 'emissivemap_fragment' ] = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vUv );\n emissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n totalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n"; + if ( undefined !== texData.format ) { -// File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl + texture.format = texData.format; -THREE.ShaderChunk[ 'emissivemap_pars_fragment' ] = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif\n"; + } + if ( undefined !== texData.type ) { -// File:src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl + texture.type = texData.type; -THREE.ShaderChunk[ 'encodings_pars_fragment' ] = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n"; + } -// File:src/renderers/shaders/ShaderChunk/encodings_fragment.glsl + if ( undefined !== texData.mipmaps ) { -THREE.ShaderChunk[ 'encodings_fragment' ] = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; + texture.mipmaps = texData.mipmaps; -// File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl + } -THREE.ShaderChunk[ 'envmap_fragment' ] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n envColor = envMapTexelToLinear( envColor );\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n#endif\n"; + if ( 1 === texData.mipmapCount ) { -// File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl + texture.minFilter = LinearFilter; -THREE.ShaderChunk[ 'envmap_pars_fragment' ] = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n uniform float reflectivity;\n uniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n #if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n varying vec3 vWorldPosition;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl + texture.needsUpdate = true; -THREE.ShaderChunk[ 'envmap_pars_vertex' ] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n varying vec3 vWorldPosition;\n #else\n varying vec3 vReflect;\n uniform float refractionRatio;\n #endif\n#endif\n"; + if ( onLoad ) onLoad( texture, texData ); -// File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl + }, onProgress, onError ); -THREE.ShaderChunk[ 'envmap_vertex' ] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n vWorldPosition = worldPosition.xyz;\n #else\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #endif\n#endif\n"; -// File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl + return texture; -THREE.ShaderChunk[ 'fog_fragment' ] = "#ifdef USE_FOG\n #ifdef USE_LOGDEPTHBUF_EXT\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n #else\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n #endif\n #ifdef FOG_EXP2\n float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n #endif\n gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl + } ); -THREE.ShaderChunk[ 'fog_pars_fragment' ] = "#ifdef USE_FOG\n uniform vec3 fogColor;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif"; + /** + * @author mrdoob / http://mrdoob.com/ + */ -// File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl + function ImageLoader ( manager ) { + this.isImageLoader = true; -THREE.ShaderChunk[ 'lightmap_fragment' ] = "#ifdef USE_LIGHTMAP\n reflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n"; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; -// File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl + }; -THREE.ShaderChunk[ 'lightmap_pars_fragment' ] = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif"; + Object.assign( ImageLoader.prototype, { -// File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl + load: function ( url, onLoad, onProgress, onError ) { -THREE.ShaderChunk[ 'lights_lambert_vertex' ] = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n vLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n getPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n dotNL = dot( geometry.normal, directLight.direction );\n directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n getSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n dotNL = dot( geometry.normal, directLight.direction );\n directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_DIR_LIGHTS > 0\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n getDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n dotNL = dot( geometry.normal, directLight.direction );\n directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_HEMI_LIGHTS > 0\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n vLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n #ifdef DOUBLE_SIDED\n vLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n #endif\n }\n#endif\n"; + var scope = this; -// File:src/renderers/shaders/ShaderChunk/lights_pars.glsl + var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); + image.onload = function () { -THREE.ShaderChunk[ 'lights_pars' ] = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n vec3 irradiance = ambientLightColor;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n return irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n int shadow;\n float shadowBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n void getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n directLight.color = directionalLight.color;\n directLight.direction = directionalLight.direction;\n directLight.visible = true;\n }\n#endif\n#if NUM_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n int shadow;\n float shadowBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n void getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n vec3 lVector = pointLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n float lightDistance = length( lVector );\n if ( testLightInRange( lightDistance, pointLight.distance ) ) {\n directLight.color = pointLight.color;\n directLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n directLight.visible = true;\n } else {\n directLight.color = vec3( 0.0 );\n directLight.visible = false;\n }\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float coneCos;\n float penumbraCos;\n int shadow;\n float shadowBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n void getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n vec3 lVector = spotLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n float lightDistance = length( lVector );\n float angleCos = dot( directLight.direction, spotLight.direction );\n if ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n float spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n directLight.color = spotLight.color;\n directLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n directLight.visible = true;\n } else {\n directLight.color = vec3( 0.0 );\n directLight.visible = false;\n }\n }\n#endif\n#if NUM_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n float dotNL = dot( geometry.normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n return irradiance;\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n vec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n #include \n vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n #ifdef ENVMAP_TYPE_CUBE\n vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n #else\n vec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n vec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n #else\n vec4 envMapColor = vec4( 0.0 );\n #endif\n return PI * envMapColor.rgb * envMapIntensity;\n }\n float getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n float maxMIPLevelScalar = float( maxMIPLevel );\n float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n }\n vec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n #else\n vec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n #endif\n #include \n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n float specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n #ifdef ENVMAP_TYPE_CUBE\n vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n #else\n vec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n vec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n #else\n vec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n #else\n vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n #endif\n return envMapColor.rgb * envMapIntensity;\n }\n#endif\n"; + URL.revokeObjectURL( image.src ); -// File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl + if ( onLoad ) onLoad( image ); -THREE.ShaderChunk[ 'lights_phong_fragment' ] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; + scope.manager.itemEnd( url ); -// File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl + }; -THREE.ShaderChunk[ 'lights_phong_pars_fragment' ] = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_BlinnPhong\n#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material ) (0)\n"; + if ( url.indexOf( 'data:' ) === 0 ) { -// File:src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl + image.src = url; -THREE.ShaderChunk[ 'lights_physical_fragment' ] = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n material.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n material.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n material.clearCoat = saturate( clearCoat ); material.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; + } else { -// File:src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl + var loader = new XHRLoader(); + loader.setPath( this.path ); + loader.setResponseType( 'blob' ); + loader.load( url, function ( blob ) { -THREE.ShaderChunk[ 'lights_physical_pars_fragment' ] = "struct PhysicalMaterial {\n vec3 diffuseColor;\n float specularRoughness;\n vec3 specularColor;\n #ifndef STANDARD\n float clearCoat;\n float clearCoatRoughness;\n #endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n return DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n #ifndef STANDARD\n float clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n #else\n float clearCoatDHR = 0.0;\n #endif\n reflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n reflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n #ifndef STANDARD\n reflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n #endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n #ifndef STANDARD\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n float dotNL = dotNV;\n float clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n #else\n float clearCoatDHR = 0.0;\n #endif\n reflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n #ifndef STANDARD\n reflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n #endif\n}\n#define RE_Direct RE_Direct_Physical\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular RE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n"; + image.src = URL.createObjectURL( blob ); -// File:src/renderers/shaders/ShaderChunk/lights_template.glsl + }, onProgress, onError ); -THREE.ShaderChunk[ 'lights_template' ] = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n PointLight pointLight;\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n getPointDirectLightIrradiance( pointLight, geometry, directLight );\n #ifdef USE_SHADOWMAP\n directLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n SpotLight spotLight;\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n getSpotDirectLightIrradiance( spotLight, geometry, directLight );\n #ifdef USE_SHADOWMAP\n directLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n DirectionalLight directionalLight;\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n #ifdef USE_SHADOWMAP\n directLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if defined( RE_IndirectDiffuse )\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #ifdef USE_LIGHTMAP\n vec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lightMapIrradiance *= PI;\n #endif\n irradiance += lightMapIrradiance;\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n }\n #endif\n #if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n irradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n #endif\n RE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n vec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n #ifndef STANDARD\n vec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n #else\n vec3 clearCoatRadiance = vec3( 0.0 );\n #endif\n \n RE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl + scope.manager.itemStart( url ); -THREE.ShaderChunk[ 'logdepthbuf_fragment' ] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif"; + return image; -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl + }, -THREE.ShaderChunk[ 'logdepthbuf_pars_fragment' ] = "#ifdef USE_LOGDEPTHBUF\n uniform float logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n#endif\n"; + setCrossOrigin: function ( value ) { -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl + this.crossOrigin = value; + return this; -THREE.ShaderChunk[ 'logdepthbuf_pars_vertex' ] = "#ifdef USE_LOGDEPTHBUF\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n uniform float logDepthBufFC;\n#endif"; + }, -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl + setPath: function ( value ) { -THREE.ShaderChunk[ 'logdepthbuf_vertex' ] = "#ifdef USE_LOGDEPTHBUF\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n vFragDepth = 1.0 + gl_Position.w;\n #else\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n #endif\n#endif\n"; + this.path = value; + return this; -// File:src/renderers/shaders/ShaderChunk/map_fragment.glsl + } -THREE.ShaderChunk[ 'map_fragment' ] = "#ifdef USE_MAP\n vec4 texelColor = texture2D( map, vUv );\n texelColor = mapTexelToLinear( texelColor );\n diffuseColor *= texelColor;\n#endif\n"; + } ); -// File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.ShaderChunk[ 'map_pars_fragment' ] = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif\n"; + function CubeTextureLoader ( manager ) { + this.isCubeTextureLoader = true; -// File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; -THREE.ShaderChunk[ 'map_particle_fragment' ] = "#ifdef USE_MAP\n vec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n diffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n"; + }; -// File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl + Object.assign( CubeTextureLoader.prototype, { -THREE.ShaderChunk[ 'map_particle_pars_fragment' ] = "#ifdef USE_MAP\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n#endif\n"; + load: function ( urls, onLoad, onProgress, onError ) { -// File:src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl + var texture = new CubeTexture(); -THREE.ShaderChunk[ 'metalnessmap_fragment' ] = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vUv );\n metalnessFactor *= texelMetalness.r;\n#endif\n"; + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); -// File:src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl + var loaded = 0; -THREE.ShaderChunk[ 'metalnessmap_pars_fragment' ] = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif"; + function loadTexture( i ) { -// File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl + loader.load( urls[ i ], function ( image ) { -THREE.ShaderChunk[ 'morphnormal_vertex' ] = "#ifdef USE_MORPHNORMALS\n objectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n objectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n objectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n objectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n"; + texture.images[ i ] = image; -// File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl + loaded ++; -THREE.ShaderChunk[ 'morphtarget_pars_vertex' ] = "#ifdef USE_MORPHTARGETS\n #ifndef USE_MORPHNORMALS\n uniform float morphTargetInfluences[ 8 ];\n #else\n uniform float morphTargetInfluences[ 4 ];\n #endif\n#endif"; + if ( loaded === 6 ) { -// File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl + texture.needsUpdate = true; -THREE.ShaderChunk[ 'morphtarget_vertex' ] = "#ifdef USE_MORPHTARGETS\n transformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n transformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n transformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n transformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n #ifndef USE_MORPHNORMALS\n transformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n transformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n transformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n transformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n #endif\n#endif\n"; + if ( onLoad ) onLoad( texture ); -// File:src/renderers/shaders/ShaderChunk/normal_flip.glsl + } -THREE.ShaderChunk[ 'normal_flip' ] = "#ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n float flipNormal = 1.0;\n#endif\n"; + }, undefined, onError ); -// File:src/renderers/shaders/ShaderChunk/normal_fragment.glsl + } -THREE.ShaderChunk[ 'normal_fragment' ] = "#ifdef FLAT_SHADED\n vec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n vec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#else\n vec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n normal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n"; + for ( var i = 0; i < urls.length; ++ i ) { -// File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl + loadTexture( i ); -THREE.ShaderChunk[ 'normalmap_pars_fragment' ] = "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/packing.glsl + return texture; -THREE.ShaderChunk[ 'packing' ] = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * PackFactors ), v );\n r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; + }, -// File:src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl + setCrossOrigin: function ( value ) { -THREE.ShaderChunk[ 'premultiplied_alpha_fragment' ] = "#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif\n"; + this.crossOrigin = value; + return this; -// File:src/renderers/shaders/ShaderChunk/project_vertex.glsl + }, -THREE.ShaderChunk[ 'project_vertex' ] = "#ifdef USE_SKINNING\n vec4 mvPosition = modelViewMatrix * skinned;\n#else\n vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n"; + setPath: function ( value ) { -// File:src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl + this.path = value; + return this; -THREE.ShaderChunk[ 'roughnessmap_fragment' ] = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vUv );\n roughnessFactor *= texelRoughness.r;\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl + } ); -THREE.ShaderChunk[ 'roughnessmap_pars_fragment' ] = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif"; + /** + * @author mrdoob / http://mrdoob.com/ + */ -// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl + function TextureLoader ( manager ) { + this.isTextureLoader = true; -THREE.ShaderChunk[ 'shadowmap_pars_fragment' ] = "#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n #endif\n #if NUM_SPOT_LIGHTS > 0\n uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n #endif\n #if NUM_POINT_LIGHTS > 0\n uniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n #endif\n float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n }\n float texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n const vec2 offset = vec2( 0.0, 1.0 );\n vec2 texelSize = vec2( 1.0 ) / size;\n vec2 centroidUV = floor( uv * size + 0.5 ) / size;\n float lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n float lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n float rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n float rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n vec2 f = fract( uv * size + 0.5 );\n float a = mix( lb, lt, f.y );\n float b = mix( rb, rt, f.y );\n float c = mix( a, b, f.x );\n return c;\n }\n float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n shadowCoord.xyz /= shadowCoord.w;\n shadowCoord.z += shadowBias;\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n bool frustumTest = all( frustumTestVec );\n if ( frustumTest ) {\n #if defined( SHADOWMAP_TYPE_PCF )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx0 = - texelSize.x * shadowRadius;\n float dy0 = - texelSize.y * shadowRadius;\n float dx1 = + texelSize.x * shadowRadius;\n float dy1 = + texelSize.y * shadowRadius;\n return (\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n ) * ( 1.0 / 9.0 );\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx0 = - texelSize.x * shadowRadius;\n float dy0 = - texelSize.y * shadowRadius;\n float dx1 = + texelSize.x * shadowRadius;\n float dy1 = + texelSize.y * shadowRadius;\n return (\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n ) * ( 1.0 / 9.0 );\n #else\n return texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n #endif\n }\n return 1.0;\n }\n vec2 cubeToUV( vec3 v, float texelSizeY ) {\n vec3 absV = abs( v );\n float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n absV *= scaleToCube;\n v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n vec2 planar = v.xy;\n float almostATexel = 1.5 * texelSizeY;\n float almostOne = 1.0 - almostATexel;\n if ( absV.z >= almostOne ) {\n if ( v.z > 0.0 )\n planar.x = 4.0 - v.x;\n } else if ( absV.x >= almostOne ) {\n float signX = sign( v.x );\n planar.x = v.z * signX + 2.0 * signX;\n } else if ( absV.y >= almostOne ) {\n float signY = sign( v.y );\n planar.x = v.x + 2.0 * signY + 2.0;\n planar.y = v.z * signY - 2.0;\n }\n return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n }\n float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n vec3 lightToPosition = shadowCoord.xyz;\n vec3 bd3D = normalize( lightToPosition );\n float dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n return (\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n ) * ( 1.0 / 9.0 );\n #else\n return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n #endif\n }\n#endif\n"; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; -// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl + }; -THREE.ShaderChunk[ 'shadowmap_pars_vertex' ] = "#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n #endif\n #if NUM_SPOT_LIGHTS > 0\n uniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n #endif\n #if NUM_POINT_LIGHTS > 0\n uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n #endif\n#endif\n"; + Object.assign( TextureLoader.prototype, { -// File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl + load: function ( url, onLoad, onProgress, onError ) { -THREE.ShaderChunk[ 'shadowmap_vertex' ] = "#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n }\n #endif\n #if NUM_SPOT_LIGHTS > 0\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n vSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n }\n #endif\n #if NUM_POINT_LIGHTS > 0\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n }\n #endif\n#endif\n"; + var texture = new Texture(); -// File:src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + loader.load( url, function ( image ) { -THREE.ShaderChunk[ 'shadowmask_pars_fragment' ] = "float getShadowMask() {\n float shadow = 1.0;\n #ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n DirectionalLight directionalLight;\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n shadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n }\n #endif\n #if NUM_SPOT_LIGHTS > 0\n SpotLight spotLight;\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n shadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n }\n #endif\n #if NUM_POINT_LIGHTS > 0\n PointLight pointLight;\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n shadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n }\n #endif\n #endif\n return shadow;\n}\n"; + // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. + var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; -// File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl + texture.format = isJPEG ? RGBFormat : RGBAFormat; + texture.image = image; + texture.needsUpdate = true; -THREE.ShaderChunk[ 'skinbase_vertex' ] = "#ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; + if ( onLoad !== undefined ) { -// File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl + onLoad( texture ); -THREE.ShaderChunk[ 'skinning_pars_vertex' ] = "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n #ifdef BONE_TEXTURE\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n mat4 getBoneMatrix( const in float i ) {\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n y = dy * ( y + 0.5 );\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n mat4 bone = mat4( v1, v2, v3, v4 );\n return bone;\n }\n #else\n uniform mat4 boneMatrices[ MAX_BONES ];\n mat4 getBoneMatrix( const in float i ) {\n mat4 bone = boneMatrices[ int(i) ];\n return bone;\n }\n #endif\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl + }, onProgress, onError ); -THREE.ShaderChunk[ 'skinning_vertex' ] = "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n#endif\n"; + return texture; -// File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl + }, -THREE.ShaderChunk[ 'skinnormal_vertex' ] = "#ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n"; + setCrossOrigin: function ( value ) { -// File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl + this.crossOrigin = value; + return this; -THREE.ShaderChunk[ 'specularmap_fragment' ] = "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif"; + }, -// File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl + setPath: function ( value ) { -THREE.ShaderChunk[ 'specularmap_pars_fragment' ] = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif"; + this.path = value; + return this; -// File:src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl + } -THREE.ShaderChunk[ 'tonemapping_fragment' ] = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n"; + } ); -// File:src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ -THREE.ShaderChunk[ 'tonemapping_pars_fragment' ] = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n"; + function Light ( color, intensity ) { + this.isLight = true; -// File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl + Object3D.call( this ); -THREE.ShaderChunk[ 'uv2_pars_fragment' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n#endif"; + this.type = 'Light'; -// File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl + this.color = new Color( color ); + this.intensity = intensity !== undefined ? intensity : 1; -THREE.ShaderChunk[ 'uv2_pars_vertex' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n#endif"; + this.receiveShadow = undefined; -// File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl + }; -THREE.ShaderChunk[ 'uv2_vertex' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = uv2;\n#endif"; + Light.prototype = Object.assign( Object.create( Object3D.prototype ), { -// File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl + constructor: Light, -THREE.ShaderChunk[ 'uv_pars_fragment' ] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n varying vec2 vUv;\n#endif"; + copy: function ( source ) { -// File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl + Object3D.prototype.copy.call( this, source ); -THREE.ShaderChunk[ 'uv_pars_vertex' ] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n#endif\n"; + this.color.copy( source.color ); + this.intensity = source.intensity; -// File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl + return this; -THREE.ShaderChunk[ 'uv_vertex' ] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif"; + }, -// File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl + toJSON: function ( meta ) { -THREE.ShaderChunk[ 'worldpos_vertex' ] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n #ifdef USE_SKINNING\n vec4 worldPosition = modelMatrix * skinned;\n #else\n vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n #endif\n#endif\n"; + var data = Object3D.prototype.toJSON.call( this, meta ); -// File:src/renderers/shaders/UniformsUtils.js + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; -/** - * Uniform Utilities - */ + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); -THREE.UniformsUtils = { + if ( this.distance !== undefined ) data.object.distance = this.distance; + if ( this.angle !== undefined ) data.object.angle = this.angle; + if ( this.decay !== undefined ) data.object.decay = this.decay; + if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra; - merge: function ( uniforms ) { + return data; - var merged = {}; + } - for ( var u = 0; u < uniforms.length; u ++ ) { + } ); - var tmp = this.clone( uniforms[ u ] ); + /** + * @author alteredq / http://alteredqualia.com/ + */ - for ( var p in tmp ) { + function HemisphereLight ( skyColor, groundColor, intensity ) { + this.isHemisphereLight = true; - merged[ p ] = tmp[ p ]; + Light.call( this, skyColor, intensity ); - } + this.type = 'HemisphereLight'; - } + this.castShadow = undefined; - return merged; + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - }, + this.groundColor = new Color( groundColor ); - clone: function ( uniforms_src ) { + }; - var uniforms_dst = {}; + HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { - for ( var u in uniforms_src ) { + constructor: HemisphereLight, - uniforms_dst[ u ] = {}; + copy: function ( source ) { - for ( var p in uniforms_src[ u ] ) { + Light.prototype.copy.call( this, source ); - var parameter_src = uniforms_src[ u ][ p ]; + this.groundColor.copy( source.groundColor ); - if ( parameter_src instanceof THREE.Color || - parameter_src instanceof THREE.Vector2 || - parameter_src instanceof THREE.Vector3 || - parameter_src instanceof THREE.Vector4 || - parameter_src instanceof THREE.Matrix3 || - parameter_src instanceof THREE.Matrix4 || - parameter_src instanceof THREE.Texture ) { + return this; - uniforms_dst[ u ][ p ] = parameter_src.clone(); + } - } else if ( Array.isArray( parameter_src ) ) { + } ); - uniforms_dst[ u ][ p ] = parameter_src.slice(); + /** + * @author mrdoob / http://mrdoob.com/ + */ - } else { + function LightShadow ( camera ) { + this.isLightShadow = true; - uniforms_dst[ u ][ p ] = parameter_src; + this.camera = camera; - } + this.bias = 0; + this.radius = 1; - } + this.mapSize = new Vector2( 512, 512 ); - } + this.map = null; + this.matrix = new Matrix4(); - return uniforms_dst; + }; - } + Object.assign( LightShadow.prototype, { -}; + copy: function ( source ) { -// File:src/renderers/shaders/UniformsLib.js + this.camera = source.camera.clone(); -/** - * Uniforms library for shared webgl shaders - */ + this.bias = source.bias; + this.radius = source.radius; -THREE.UniformsLib = { + this.mapSize.copy( source.mapSize ); - common: { + return this; - "diffuse": { value: new THREE.Color( 0xeeeeee ) }, - "opacity": { value: 1.0 }, + }, - "map": { value: null }, - "offsetRepeat": { value: new THREE.Vector4( 0, 0, 1, 1 ) }, + clone: function () { - "specularMap": { value: null }, - "alphaMap": { value: null }, + return new this.constructor().copy( this ); - "envMap": { value: null }, - "flipEnvMap": { value: - 1 }, - "reflectivity": { value: 1.0 }, - "refractionRatio": { value: 0.98 } + } - }, + } ); - aomap: { + /** + * @author mrdoob / http://mrdoob.com/ + */ - "aoMap": { value: null }, - "aoMapIntensity": { value: 1 } + function SpotLightShadow () { + this.isSpotLightShadow = true; - }, + LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); - lightmap: { + }; - "lightMap": { value: null }, - "lightMapIntensity": { value: 1 } + SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - }, + constructor: SpotLightShadow, - emissivemap: { + update: function ( light ) { - "emissiveMap": { value: null } + var fov = exports.Math.RAD2DEG * 2 * light.angle; + var aspect = this.mapSize.width / this.mapSize.height; + var far = light.distance || 500; - }, + var camera = this.camera; - bumpmap: { + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { - "bumpMap": { value: null }, - "bumpScale": { value: 1 } + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); - }, + } - normalmap: { + } - "normalMap": { value: null }, - "normalScale": { value: new THREE.Vector2( 1, 1 ) } + } ); - }, + /** + * @author alteredq / http://alteredqualia.com/ + */ - displacementmap: { + function SpotLight ( color, intensity, distance, angle, penumbra, decay ) { + this.isSpotLight = true; - "displacementMap": { value: null }, - "displacementScale": { value: 1 }, - "displacementBias": { value: 0 } + Light.call( this, color, intensity ); - }, + this.type = 'SpotLight'; - roughnessmap: { + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - "roughnessMap": { value: null } + this.target = new Object3D(); - }, + Object.defineProperty( this, 'power', { + get: function () { + // intensity = power per solid angle. + // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + return this.intensity * Math.PI; + }, + set: function ( power ) { + // intensity = power per solid angle. + // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + this.intensity = power / Math.PI; + } + } ); - metalnessmap: { + this.distance = ( distance !== undefined ) ? distance : 0; + this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; + this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - "metalnessMap": { value: null } + this.shadow = new SpotLightShadow(); - }, + }; - fog: { + SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { - "fogDensity": { value: 0.00025 }, - "fogNear": { value: 1 }, - "fogFar": { value: 2000 }, - "fogColor": { value: new THREE.Color( 0xffffff ) } + constructor: SpotLight, - }, + copy: function ( source ) { - lights: { - - "ambientLightColor": { value: [] }, - - "directionalLights": { value: [], properties: { - "direction": {}, - "color": {}, - - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, - - "directionalShadowMap": { value: [] }, - "directionalShadowMatrix": { value: [] }, - - "spotLights": { value: [], properties: { - "color": {}, - "position": {}, - "direction": {}, - "distance": {}, - "coneCos": {}, - "penumbraCos": {}, - "decay": {}, - - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, - - "spotShadowMap": { value: [] }, - "spotShadowMatrix": { value: [] }, - - "pointLights": { value: [], properties: { - "color": {}, - "position": {}, - "decay": {}, - "distance": {}, - - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, - - "pointShadowMap": { value: [] }, - "pointShadowMatrix": { value: [] }, - - "hemisphereLights": { value: [], properties: { - "direction": {}, - "skyColor": {}, - "groundColor": {} - } } + Light.prototype.copy.call( this, source ); - }, + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; - points: { + this.target = source.target.clone(); - "diffuse": { value: new THREE.Color( 0xeeeeee ) }, - "opacity": { value: 1.0 }, - "size": { value: 1.0 }, - "scale": { value: 1.0 }, - "map": { value: null }, - "offsetRepeat": { value: new THREE.Vector4( 0, 0, 1, 1 ) } + this.shadow = source.shadow.clone(); - } + return this; -}; + } -// File:src/renderers/shaders/ShaderLib/cube_frag.glsl + } ); -THREE.ShaderChunk[ 'cube_frag' ] = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n gl_FragColor.a *= opacity;\n}\n"; + /** + * @author mrdoob / http://mrdoob.com/ + */ -// File:src/renderers/shaders/ShaderLib/cube_vert.glsl -THREE.ShaderChunk[ 'cube_vert' ] = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n vWorldPosition = transformDirection( position, modelMatrix );\n #include \n #include \n}\n"; + function PointLight ( color, intensity, distance, decay ) { + this.isPointLight = true; -// File:src/renderers/shaders/ShaderLib/depth_frag.glsl + Light.call( this, color, intensity ); -THREE.ShaderChunk[ 'depth_frag' ] = "#if DEPTH_PACKING == 3200\n uniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( 1.0 );\n #if DEPTH_PACKING == 3200\n diffuseColor.a = opacity;\n #endif\n #include \n #include \n #include \n #include \n #if DEPTH_PACKING == 3200\n gl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n #elif DEPTH_PACKING == 3201\n gl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n #endif\n}\n"; + this.type = 'PointLight'; -// File:src/renderers/shaders/ShaderLib/depth_vert.glsl + Object.defineProperty( this, 'power', { + get: function () { + // intensity = power per solid angle. + // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + return this.intensity * 4 * Math.PI; -THREE.ShaderChunk[ 'depth_vert' ] = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}\n"; + }, + set: function ( power ) { + // intensity = power per solid angle. + // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + this.intensity = power / ( 4 * Math.PI ); + } + } ); -// File:src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl + this.distance = ( distance !== undefined ) ? distance : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. -THREE.ShaderChunk[ 'distanceRGBA_frag' ] = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include \n#include \n#include \nvoid main () {\n #include \n gl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n"; + this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); -// File:src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl + }; -THREE.ShaderChunk[ 'distanceRGBA_vert' ] = "varying vec4 vWorldPosition;\n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vWorldPosition = worldPosition;\n}\n"; + PointLight.prototype = Object.assign( Object.create( Light.prototype ), { -// File:src/renderers/shaders/ShaderLib/equirect_frag.glsl + constructor: PointLight, -THREE.ShaderChunk[ 'equirect_frag' ] = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n vec3 direction = normalize( vWorldPosition );\n vec2 sampleUV;\n sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n gl_FragColor = texture2D( tEquirect, sampleUV );\n}\n"; + copy: function ( source ) { -// File:src/renderers/shaders/ShaderLib/equirect_vert.glsl + Light.prototype.copy.call( this, source ); -THREE.ShaderChunk[ 'equirect_vert' ] = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n vWorldPosition = transformDirection( position, modelMatrix );\n #include \n #include \n}\n"; + this.distance = source.distance; + this.decay = source.decay; -// File:src/renderers/shaders/ShaderLib/linedashed_frag.glsl + this.shadow = source.shadow.clone(); -THREE.ShaderChunk[ 'linedashed_frag' ] = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n if ( mod( vLineDistance, totalSize ) > dashSize ) {\n discard;\n }\n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n outgoingLight = diffuseColor.rgb;\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + return this; -// File:src/renderers/shaders/ShaderLib/linedashed_vert.glsl + } -THREE.ShaderChunk[ 'linedashed_vert' ] = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vLineDistance = scale * lineDistance;\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n gl_Position = projectionMatrix * mvPosition;\n #include \n #include \n}\n"; + } ); -// File:src/renderers/shaders/ShaderLib/meshbasic_frag.glsl + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.ShaderChunk[ 'meshbasic_frag' ] = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n #include \n ReflectedLight reflectedLight;\n reflectedLight.directDiffuse = vec3( 0.0 );\n reflectedLight.directSpecular = vec3( 0.0 );\n reflectedLight.indirectDiffuse = diffuseColor.rgb;\n reflectedLight.indirectSpecular = vec3( 0.0 );\n #include \n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n #include \n #include \n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + function DirectionalLightShadow ( light ) { + this.isDirectionalLightShadow = true; -// File:src/renderers/shaders/ShaderLib/meshbasic_vert.glsl + LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); -THREE.ShaderChunk[ 'meshbasic_vert' ] = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #ifdef USE_ENVMAP\n #include \n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}\n"; + }; -// File:src/renderers/shaders/ShaderLib/meshlambert_frag.glsl + DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { -THREE.ShaderChunk[ 'meshlambert_frag' ] = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n varying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n reflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n #include \n reflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n #ifdef DOUBLE_SIDED\n reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n #else\n reflectedLight.directDiffuse = vLightFront;\n #endif\n reflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include \n #include \n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + constructor: DirectionalLightShadow -// File:src/renderers/shaders/ShaderLib/meshlambert_vert.glsl + } ); -THREE.ShaderChunk[ 'meshlambert_vert' ] = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n varying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}\n"; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ -// File:src/renderers/shaders/ShaderLib/meshphong_frag.glsl + function DirectionalLight ( color, intensity ) { + this.isDirectionalLight = true; -THREE.ShaderChunk[ 'meshphong_frag' ] = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n #include \n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + Light.call( this, color, intensity ); -// File:src/renderers/shaders/ShaderLib/meshphong_vert.glsl + this.type = 'DirectionalLight'; -THREE.ShaderChunk[ 'meshphong_vert' ] = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n#endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n}\n"; + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); -// File:src/renderers/shaders/ShaderLib/meshphysical_frag.glsl + this.target = new Object3D(); -THREE.ShaderChunk[ 'meshphysical_frag' ] = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n uniform float clearCoat;\n uniform float clearCoatRoughness;\n#endif\nuniform float envMapIntensity;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + this.shadow = new DirectionalLightShadow(); -// File:src/renderers/shaders/ShaderLib/meshphysical_vert.glsl + }; -THREE.ShaderChunk[ 'meshphysical_vert' ] = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n#endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n}\n"; + DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { -// File:src/renderers/shaders/ShaderLib/normal_frag.glsl + constructor: DirectionalLight, -THREE.ShaderChunk[ 'normal_frag' ] = "uniform float opacity;\nvarying vec3 vNormal;\n#include \n#include \n#include \n#include \nvoid main() {\n #include \n gl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n #include \n}\n"; + copy: function ( source ) { -// File:src/renderers/shaders/ShaderLib/normal_vert.glsl + Light.prototype.copy.call( this, source ); -THREE.ShaderChunk[ 'normal_vert' ] = "varying vec3 vNormal;\n#include \n#include \n#include \n#include \nvoid main() {\n vNormal = normalize( normalMatrix * normal );\n #include \n #include \n #include \n #include \n #include \n}\n"; + this.target = source.target.clone(); -// File:src/renderers/shaders/ShaderLib/points_frag.glsl + this.shadow = source.shadow.clone(); -THREE.ShaderChunk[ 'points_frag' ] = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + return this; -// File:src/renderers/shaders/ShaderLib/points_vert.glsl + } -THREE.ShaderChunk[ 'points_vert' ] = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #ifdef USE_SIZEATTENUATION\n gl_PointSize = size * ( scale / - mvPosition.z );\n #else\n gl_PointSize = size;\n #endif\n #include \n #include \n #include \n #include \n}\n"; + } ); -// File:src/renderers/shaders/ShaderLib/shadow_frag.glsl + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.ShaderChunk[ 'shadow_frag' ] = "uniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n gl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n"; + function AmbientLight ( color, intensity ) { + this.isAmbientLight = true; -// File:src/renderers/shaders/ShaderLib/shadow_vert.glsl + Light.call( this, color, intensity ); -THREE.ShaderChunk[ 'shadow_vert' ] = "#include \nvoid main() {\n #include \n #include \n #include \n #include \n}\n"; + this.type = 'AmbientLight'; -// File:src/renderers/shaders/ShaderLib.js + this.castShadow = undefined; -/** - * Webgl Shader Library for three.js - * - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ + }; + AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { -THREE.ShaderLib = { + constructor: AmbientLight - 'basic': { + } ); - uniforms: THREE.UniformsUtils.merge( [ + /** + * @author tschw + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'fog' ] + exports.AnimationUtils = { - ] ), + // same as Array.prototype.slice, but also works on typed arrays + arraySlice: function( array, from, to ) { - vertexShader: THREE.ShaderChunk[ 'meshbasic_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshbasic_frag' ] + if ( exports.AnimationUtils.isTypedArray( array ) ) { - }, + return new array.constructor( array.subarray( from, to ) ); - 'lambert': { + } - uniforms: THREE.UniformsUtils.merge( [ + return array.slice( from, to ); - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + }, - { - "emissive" : { value: new THREE.Color( 0x000000 ) } - } + // converts an array to a specific type + convertArray: function( array, type, forceClone ) { - ] ), + if ( ! array || // let 'undefined' and 'null' pass + ! forceClone && array.constructor === type ) return array; - vertexShader: THREE.ShaderChunk[ 'meshlambert_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshlambert_frag' ] + if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { - }, + return new type( array ); // create typed array - 'phong': { + } - uniforms: THREE.UniformsUtils.merge( [ + return Array.prototype.slice.call( array ); // create Array - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'bumpmap' ], - THREE.UniformsLib[ 'normalmap' ], - THREE.UniformsLib[ 'displacementmap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + }, - { - "emissive" : { value: new THREE.Color( 0x000000 ) }, - "specular" : { value: new THREE.Color( 0x111111 ) }, - "shininess": { value: 30 } - } + isTypedArray: function( object ) { - ] ), + return ArrayBuffer.isView( object ) && + ! ( object instanceof DataView ); - vertexShader: THREE.ShaderChunk[ 'meshphong_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ] + }, - }, + // returns an array by which times and values can be sorted + getKeyframeOrder: function( times ) { - 'standard': { + function compareTime( i, j ) { - uniforms: THREE.UniformsUtils.merge( [ + return times[ i ] - times[ j ]; - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'bumpmap' ], - THREE.UniformsLib[ 'normalmap' ], - THREE.UniformsLib[ 'displacementmap' ], - THREE.UniformsLib[ 'roughnessmap' ], - THREE.UniformsLib[ 'metalnessmap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + } - { - "emissive" : { value: new THREE.Color( 0x000000 ) }, - "roughness": { value: 0.5 }, - "metalness": { value: 0 }, - "envMapIntensity" : { value: 1 }, // temporary - } + var n = times.length; + var result = new Array( n ); + for ( var i = 0; i !== n; ++ i ) result[ i ] = i; - ] ), + result.sort( compareTime ); - vertexShader: THREE.ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphysical_frag' ] + return result; - }, + }, - 'points': { + // uses the array previously returned by 'getKeyframeOrder' to sort data + sortedArray: function( values, stride, order ) { - uniforms: THREE.UniformsUtils.merge( [ + var nValues = values.length; + var result = new values.constructor( nValues ); - THREE.UniformsLib[ 'points' ], - THREE.UniformsLib[ 'fog' ] + for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { - ] ), + var srcOffset = order[ i ] * stride; - vertexShader: THREE.ShaderChunk[ 'points_vert' ], - fragmentShader: THREE.ShaderChunk[ 'points_frag' ] + for ( var j = 0; j !== stride; ++ j ) { - }, + result[ dstOffset ++ ] = values[ srcOffset + j ]; - 'dashed': { + } - uniforms: THREE.UniformsUtils.merge( [ + } - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'fog' ], + return result; - { - "scale" : { value: 1 }, - "dashSize" : { value: 1 }, - "totalSize": { value: 2 } - } + }, - ] ), + // function for parsing AOS keyframe formats + flattenJSON: function( jsonKeys, times, values, valuePropertyName ) { - vertexShader: THREE.ShaderChunk[ 'linedashed_vert' ], - fragmentShader: THREE.ShaderChunk[ 'linedashed_frag' ] + var i = 1, key = jsonKeys[ 0 ]; - }, + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { - 'depth': { + key = jsonKeys[ i ++ ]; - uniforms: THREE.UniformsUtils.merge( [ + } - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'displacementmap' ] + if ( key === undefined ) return; // no data - ] ), + var value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data - vertexShader: THREE.ShaderChunk[ 'depth_vert' ], - fragmentShader: THREE.ShaderChunk[ 'depth_frag' ] + if ( Array.isArray( value ) ) { - }, + do { - 'normal': { + value = key[ valuePropertyName ]; - uniforms: { + if ( value !== undefined ) { - "opacity" : { value: 1.0 } + times.push( key.time ); + values.push.apply( values, value ); // push all elements - }, + } - vertexShader: THREE.ShaderChunk[ 'normal_vert' ], - fragmentShader: THREE.ShaderChunk[ 'normal_frag' ] + key = jsonKeys[ i ++ ]; - }, + } while ( key !== undefined ); - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + } else if ( value.toArray !== undefined ) { + // ...assume THREE.Math-ish - 'cube': { + do { - uniforms: { - "tCube": { value: null }, - "tFlip": { value: - 1 }, - "opacity": { value: 1.0 } - }, + value = key[ valuePropertyName ]; - vertexShader: THREE.ShaderChunk[ 'cube_vert' ], - fragmentShader: THREE.ShaderChunk[ 'cube_frag' ] + if ( value !== undefined ) { - }, + times.push( key.time ); + value.toArray( values, values.length ); - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + } - 'equirect': { + key = jsonKeys[ i ++ ]; - uniforms: { - "tEquirect": { value: null }, - "tFlip": { value: - 1 } - }, + } while ( key !== undefined ); - vertexShader: THREE.ShaderChunk[ 'equirect_vert' ], - fragmentShader: THREE.ShaderChunk[ 'equirect_frag' ] + } else { + // otherwise push as-is - }, + do { - 'distanceRGBA': { + value = key[ valuePropertyName ]; - uniforms: { + if ( value !== undefined ) { - "lightPos": { value: new THREE.Vector3() } + times.push( key.time ); + values.push( value ); - }, + } - vertexShader: THREE.ShaderChunk[ 'distanceRGBA_vert' ], - fragmentShader: THREE.ShaderChunk[ 'distanceRGBA_frag' ] + key = jsonKeys[ i ++ ]; - } + } while ( key !== undefined ); -}; + } -THREE.ShaderLib[ 'physical' ] = { + } - uniforms: THREE.UniformsUtils.merge( [ + }; - THREE.ShaderLib[ 'standard' ].uniforms, + /** + * Abstract base class of interpolants over parametric samples. + * + * The parameter domain is one dimensional, typically the time or a path + * along a curve defined by the data. + * + * The sample values can have any dimensionality and derived classes may + * apply special interpretations to the data. + * + * This class provides the interval seek in a Template Method, deferring + * the actual interpolation to derived classes. + * + * Time complexity is O(1) for linear access crossing at most two points + * and O(log N) for random access, where N is the number of positions. + * + * References: + * + * http://www.oodesign.com/template-method-pattern.html + * + * @author tschw + */ - { - "clearCoat": { value: 0 }, - "clearCoatRoughness": { value: 0 } - } + function Interpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isInterpolant = true; - ] ), + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; - vertexShader: THREE.ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphysical_frag' ] + this.resultBuffer = resultBuffer !== undefined ? + resultBuffer : new sampleValues.constructor( sampleSize ); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; -}; + }; -// File:src/renderers/WebGLRenderer.js + Interpolant.prototype = { -/** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - * @author tschw - */ + constructor: Interpolant, -THREE.WebGLRenderer = function ( parameters ) { + evaluate: function( t ) { - console.log( 'THREE.WebGLRenderer', THREE.REVISION ); + var pp = this.parameterPositions, + i1 = this._cachedIndex, - parameters = parameters || {}; + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; - var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), - _context = parameters.context !== undefined ? parameters.context : null, + validate_interval: { - _alpha = parameters.alpha !== undefined ? parameters.alpha : false, - _depth = parameters.depth !== undefined ? parameters.depth : true, - _stencil = parameters.stencil !== undefined ? parameters.stencil : true, - _antialias = parameters.antialias !== undefined ? parameters.antialias : false, - _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, - _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false; + seek: { - var lights = []; + var right; - var opaqueObjects = []; - var opaqueObjectsLastIndex = - 1; - var transparentObjects = []; - var transparentObjectsLastIndex = - 1; + linear_scan: { + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { - var morphInfluences = new Float32Array( 8 ); + for ( var giveUpAt = i1 + 2; ;) { - var sprites = []; - var lensFlares = []; + if ( t1 === undefined ) { - // public properties + if ( t < t0 ) break forward_scan; - this.domElement = _canvas; - this.context = null; + // after end - // clearing + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t, t0 ); - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; + } - // scene graph + if ( i1 === giveUpAt ) break; // this loop - this.sortObjects = true; + t0 = t1; + t1 = pp[ ++ i1 ]; - // user-defined clipping + if ( t < t1 ) { - this.clippingPlanes = []; - this.localClippingEnabled = false; + // we have arrived at the sought interval + break seek; - // physically based shading + } - this.gammaFactor = 2.0; // for backwards compatibility - this.gammaInput = false; - this.gammaOutput = false; + } - // physical lights + // prepare binary search on the right side of the index + right = pp.length; + break linear_scan; - this.physicallyCorrectLights = false; + } - // tone mapping + //- slower code: + //- if ( t < t0 || t0 === undefined ) { + if ( ! ( t >= t0 ) ) { - this.toneMapping = THREE.LinearToneMapping; - this.toneMappingExposure = 1.0; - this.toneMappingWhitePoint = 1.0; + // looping? - // morphs + var t1global = pp[ 1 ]; - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; + if ( t < t1global ) { - // internal properties + i1 = 2; // + 1, using the scan for the details + t0 = t1global; - var _this = this, + } - // internal state cache + // linear reverse scan - _currentProgram = null, - _currentRenderTarget = null, - _currentFramebuffer = null, - _currentMaterialId = - 1, - _currentGeometryProgram = '', - _currentCamera = null, + for ( var giveUpAt = i1 - 2; ;) { - _currentScissor = new THREE.Vector4(), - _currentScissorTest = null, + if ( t0 === undefined ) { - _currentViewport = new THREE.Vector4(), + // before start - // + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - _usedTextureUnits = 0, + } - // + if ( i1 === giveUpAt ) break; // this loop - _clearColor = new THREE.Color( 0x000000 ), - _clearAlpha = 0, + t1 = t0; + t0 = pp[ -- i1 - 1 ]; - _width = _canvas.width, - _height = _canvas.height, + if ( t >= t0 ) { - _pixelRatio = 1, + // we have arrived at the sought interval + break seek; - _scissor = new THREE.Vector4( 0, 0, _width, _height ), - _scissorTest = false, + } - _viewport = new THREE.Vector4( 0, 0, _width, _height ), + } - // frustum + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; - _frustum = new THREE.Frustum(), + } - // clipping + // the interval is valid - _clipping = new THREE.WebGLClipping(), - _clippingEnabled = false, - _localClippingEnabled = false, + break validate_interval; - _sphere = new THREE.Sphere(), + } // linear scan - // camera matrices cache + // binary search - _projScreenMatrix = new THREE.Matrix4(), + while ( i1 < right ) { - _vector3 = new THREE.Vector3(), + var mid = ( i1 + right ) >>> 1; - // light arrays cache + if ( t < pp[ mid ] ) { - _lights = { + right = mid; - hash: '', + } else { - ambient: [ 0, 0, 0 ], - directional: [], - directionalShadowMap: [], - directionalShadowMatrix: [], - spot: [], - spotShadowMap: [], - spotShadowMatrix: [], - point: [], - pointShadowMap: [], - pointShadowMatrix: [], - hemi: [], + i1 = mid + 1; - shadows: [] + } - }, + } - // info + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; - _infoRender = { + // check boundary cases, again - calls: 0, - vertices: 0, - faces: 0, - points: 0 + if ( t0 === undefined ) { - }; + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - this.info = { + } - render: _infoRender, - memory: { + if ( t1 === undefined ) { - geometries: 0, - textures: 0 + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t0, t ); - }, - programs: null + } - }; + } // seek + this._cachedIndex = i1; - // initialize + this.intervalChanged_( i1, t0, t1 ); - var _gl; + } // validate_interval - try { + return this.interpolate_( i1, t0, t, t1 ); - var attributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer - }; + }, - _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); + settings: null, // optional, subclass-specific settings structure + // Note: The indirection allows central control of many interpolants. - if ( _gl === null ) { + // --- Protected interface - if ( _canvas.getContext( 'webgl' ) !== null ) { + DefaultSettings_: {}, - throw 'Error creating WebGL context with your selected attributes.'; + getSettings_: function() { - } else { + return this.settings || this.DefaultSettings_; - throw 'Error creating WebGL context.'; + }, - } + copySampleValue_: function( index ) { - } + // copies a sample value to the result buffer - // Some experimental-webgl implementations do not have getShaderPrecisionFormat + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; - if ( _gl.getShaderPrecisionFormat === undefined ) { + for ( var i = 0; i !== stride; ++ i ) { - _gl.getShaderPrecisionFormat = function () { + result[ i ] = values[ offset + i ]; - return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + } - }; + return result; - } + }, - _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + // Template methods for derived classes: - } catch ( error ) { + interpolate_: function( i1, t0, t, t1 ) { - console.error( 'THREE.WebGLRenderer: ' + error ); + throw new Error( "call to abstract method" ); + // implementations shall return this.resultBuffer - } + }, - var extensions = new THREE.WebGLExtensions( _gl ); + intervalChanged_: function( i1, t0, t1 ) { - extensions.get( 'WEBGL_depth_texture' ); - extensions.get( 'OES_texture_float' ); - extensions.get( 'OES_texture_float_linear' ); - extensions.get( 'OES_texture_half_float' ); - extensions.get( 'OES_texture_half_float_linear' ); - extensions.get( 'OES_standard_derivatives' ); - extensions.get( 'ANGLE_instanced_arrays' ); + // empty - if ( extensions.get( 'OES_element_index_uint' ) ) { + } - THREE.BufferGeometry.MaxIndex = 4294967296; + }; - } + Object.assign( Interpolant.prototype, { - var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters ); + beforeStart_: //( 0, t, t0 ), returns this.resultBuffer + Interpolant.prototype.copySampleValue_, - var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL ); - var properties = new THREE.WebGLProperties(); - var textures = new THREE.WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info ); - var objects = new THREE.WebGLObjects( _gl, properties, this.info ); - var programCache = new THREE.WebGLPrograms( this, capabilities ); - var lightCache = new THREE.WebGLLights(); + afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer + Interpolant.prototype.copySampleValue_ - this.info.programs = programCache.programs; + } ); - var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender ); - var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); + /** + * Fast and simple cubic spline interpolant. + * + * It was derived from a Hermitian construction setting the first derivative + * at each sample position to the linear slope between neighboring positions + * over their parameter interval. + * + * @author tschw + */ - // + function CubicInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isCubicInterpolant = true; - var backgroundCamera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); - var backgroundCamera2 = new THREE.PerspectiveCamera(); - var backgroundPlaneMesh = new THREE.Mesh( - new THREE.PlaneBufferGeometry( 2, 2 ), - new THREE.MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) - ); - var backgroundBoxShader = THREE.ShaderLib[ 'cube' ]; - var backgroundBoxMesh = new THREE.Mesh( - new THREE.BoxBufferGeometry( 5, 5, 5 ), - new THREE.ShaderMaterial( { - uniforms: backgroundBoxShader.uniforms, - vertexShader: backgroundBoxShader.vertexShader, - fragmentShader: backgroundBoxShader.fragmentShader, - side: THREE.BackSide, - depthTest: false, - depthWrite: false, - fog: false - } ) - ); + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - // + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; - function getTargetPixelRatio() { + }; - return _currentRenderTarget === null ? _pixelRatio : 1; + CubicInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - } + constructor: CubicInterpolant, - function glClearColor( r, g, b, a ) { + DefaultSettings_: { - if ( _premultipliedAlpha === true ) { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding - r *= a; g *= a; b *= a; + }, - } + intervalChanged_: function( i1, t0, t1 ) { - state.clearColor( r, g, b, a ); + var pp = this.parameterPositions, + iPrev = i1 - 2, + iNext = i1 + 1, - } + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; - function setDefaultGLState() { + if ( tPrev === undefined ) { - state.init(); + switch ( this.getSettings_().endingStart ) { - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); + case ZeroSlopeEnding: - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; - } + break; - function resetGLState() { + case WrapAroundEnding: - _currentProgram = null; - _currentCamera = null; + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; - _currentGeometryProgram = ''; - _currentMaterialId = - 1; + break; - state.reset(); + default: // ZeroCurvatureEnding - } + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; - setDefaultGLState(); + } - this.context = _gl; - this.capabilities = capabilities; - this.extensions = extensions; - this.properties = properties; - this.state = state; + } - // shadow map + if ( tNext === undefined ) { - var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects, capabilities ); + switch ( this.getSettings_().endingEnd ) { - this.shadowMap = shadowMap; + case ZeroSlopeEnding: + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; - // Plugins + break; - var spritePlugin = new THREE.SpritePlugin( this, sprites ); - var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares ); + case WrapAroundEnding: - // API + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; - this.getContext = function () { + break; - return _gl; + default: // ZeroCurvatureEnding - }; + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; - this.getContextAttributes = function () { + } - return _gl.getContextAttributes(); + } - }; + var halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; - this.forceContextLoss = function () { + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; - extensions.get( 'WEBGL_lose_context' ).loseContext(); + }, - }; + interpolate_: function( i1, t0, t, t1 ) { - this.getMaxAnisotropy = function () { + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - return capabilities.getMaxAnisotropy(); + o1 = i1 * stride, o0 = o1 - stride, + oP = this._offsetPrev, oN = this._offsetNext, + wP = this._weightPrev, wN = this._weightNext, - }; + p = ( t - t0 ) / ( t1 - t0 ), + pp = p * p, + ppp = pp * p; - this.getPrecision = function () { + // evaluate polynomials - return capabilities.precision; + var sP = - wP * ppp + 2 * wP * pp - wP * p; + var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1; + var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + var sN = wN * ppp - wN * pp; - }; + // combine data linearly - this.getPixelRatio = function () { + for ( var i = 0; i !== stride; ++ i ) { - return _pixelRatio; + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; - }; + } - this.setPixelRatio = function ( value ) { + return result; - if ( value === undefined ) return; + } - _pixelRatio = value; + } ); - this.setSize( _viewport.z, _viewport.w, false ); + /** + * @author tschw + */ - }; + function LinearInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isLinearInterpolant = true; - this.getSize = function () { + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - return { - width: _width, - height: _height - }; + }; - }; + LinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - this.setSize = function ( width, height, updateStyle ) { + constructor: LinearInterpolant, - _width = width; - _height = height; + interpolate_: function( i1, t0, t, t1 ) { - _canvas.width = width * _pixelRatio; - _canvas.height = height * _pixelRatio; + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - if ( updateStyle !== false ) { + offset1 = i1 * stride, + offset0 = offset1 - stride, - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; - } + for ( var i = 0; i !== stride; ++ i ) { - this.setViewport( 0, 0, width, height ); + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; - }; + } - this.setViewport = function ( x, y, width, height ) { + return result; - state.viewport( _viewport.set( x, y, width, height ) ); + } - }; + } ); - this.setScissor = function ( x, y, width, height ) { + /** + * + * Interpolant that evaluates to the sample value at the position preceeding + * the parameter. + * + * @author tschw + */ - state.scissor( _scissor.set( x, y, width, height ) ); + function DiscreteInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isDiscreteInterpolant = true; - }; + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - this.setScissorTest = function ( boolean ) { + }; - state.setScissorTest( _scissorTest = boolean ); + DiscreteInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - }; + constructor: DiscreteInterpolant, - // Clearing + interpolate_: function( i1, t0, t, t1 ) { - this.getClearColor = function () { + return this.copySampleValue_( i1 - 1 ); - return _clearColor; + } - }; + } ); - this.setClearColor = function ( color, alpha ) { + var KeyframeTrackPrototype; - _clearColor.set( color ); + KeyframeTrackPrototype = { - _clearAlpha = alpha !== undefined ? alpha : 1; + TimeBufferType: Float32Array, + ValueBufferType: Float32Array, - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + DefaultInterpolation: InterpolateLinear, - }; + InterpolantFactoryMethodDiscrete: function( result ) { - this.getClearAlpha = function () { + return new DiscreteInterpolant( + this.times, this.values, this.getValueSize(), result ); - return _clearAlpha; + }, - }; + InterpolantFactoryMethodLinear: function( result ) { - this.setClearAlpha = function ( alpha ) { + return new LinearInterpolant( + this.times, this.values, this.getValueSize(), result ); - _clearAlpha = alpha; + }, - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + InterpolantFactoryMethodSmooth: function( result ) { - }; + return new CubicInterpolant( + this.times, this.values, this.getValueSize(), result ); - this.clear = function ( color, depth, stencil ) { + }, - var bits = 0; + setInterpolation: function( interpolation ) { - if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; - if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; - if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; + var factoryMethod; - _gl.clear( bits ); + switch ( interpolation ) { - }; + case InterpolateDiscrete: - this.clearColor = function () { + factoryMethod = this.InterpolantFactoryMethodDiscrete; - this.clear( true, false, false ); + break; - }; + case InterpolateLinear: - this.clearDepth = function () { + factoryMethod = this.InterpolantFactoryMethodLinear; - this.clear( false, true, false ); + break; - }; + case InterpolateSmooth: - this.clearStencil = function () { + factoryMethod = this.InterpolantFactoryMethodSmooth; - this.clear( false, false, true ); + break; - }; + } - this.clearTarget = function ( renderTarget, color, depth, stencil ) { + if ( factoryMethod === undefined ) { - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); + var message = "unsupported interpolation for " + + this.ValueTypeName + " keyframe track named " + this.name; - }; + if ( this.createInterpolant === undefined ) { - // Reset + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { - this.resetGLState = resetGLState; + this.setInterpolation( this.DefaultInterpolation ); - this.dispose = function() { + } else { - transparentObjects = []; - transparentObjectsLastIndex = -1; - opaqueObjects = []; - opaqueObjectsLastIndex = -1; + throw new Error( message ); // fatal, in this case - _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + } - }; + } - // Events + console.warn( message ); + return; - function onContextLost( event ) { + } - event.preventDefault(); + this.createInterpolant = factoryMethod; - resetGLState(); - setDefaultGLState(); + }, - properties.clear(); + getInterpolation: function() { - } + switch ( this.createInterpolant ) { - function onMaterialDispose( event ) { + case this.InterpolantFactoryMethodDiscrete: - var material = event.target; + return InterpolateDiscrete; - material.removeEventListener( 'dispose', onMaterialDispose ); + case this.InterpolantFactoryMethodLinear: - deallocateMaterial( material ); + return InterpolateLinear; - } + case this.InterpolantFactoryMethodSmooth: - // Buffer deallocation + return InterpolateSmooth; - function deallocateMaterial( material ) { + } - releaseMaterialProgramReference( material ); + }, - properties.delete( material ); + getValueSize: function() { - } + return this.values.length / this.times.length; + }, - function releaseMaterialProgramReference( material ) { + // move all keyframes either forwards or backwards in time + shift: function( timeOffset ) { - var programInfo = properties.get( material ).program; + if( timeOffset !== 0.0 ) { - material.program = undefined; + var times = this.times; - if ( programInfo !== undefined ) { + for( var i = 0, n = times.length; i !== n; ++ i ) { - programCache.releaseProgram( programInfo ); + times[ i ] += timeOffset; - } + } - } + } - // Buffer rendering + return this; - this.renderBufferImmediate = function ( object, program, material ) { + }, - state.initAttributes(); + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale: function( timeScale ) { - var buffers = properties.get( object ); + if( timeScale !== 1.0 ) { - if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); - if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); - if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); - if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); + var times = this.times; - var attributes = program.getAttributes(); + for( var i = 0, n = times.length; i !== n; ++ i ) { - if ( object.hasPositions ) { + times[ i ] *= timeScale; - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); + } - state.enableAttribute( attributes.position ); - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); + } - } + return this; - if ( object.hasNormals ) { + }, - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); + // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. + // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values + trim: function( startTime, endTime ) { - if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) { + var times = this.times, + nKeys = times.length, + from = 0, + to = nKeys - 1; - for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { + while ( from !== nKeys && times[ from ] < startTime ) ++ from; + while ( to !== -1 && times[ to ] > endTime ) -- to; - var array = object.normalArray; + ++ to; // inclusive -> exclusive bound - var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3; - var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3; - var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3; + if( from !== 0 || to !== nKeys ) { - array[ i + 0 ] = nx; - array[ i + 1 ] = ny; - array[ i + 2 ] = nz; + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; - array[ i + 3 ] = nx; - array[ i + 4 ] = ny; - array[ i + 5 ] = nz; + var stride = this.getValueSize(); + this.times = exports.AnimationUtils.arraySlice( times, from, to ); + this.values = exports.AnimationUtils. + arraySlice( this.values, from * stride, to * stride ); - array[ i + 6 ] = nx; - array[ i + 7 ] = ny; - array[ i + 8 ] = nz; + } - } + return this; - } + }, - _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate: function() { - state.enableAttribute( attributes.normal ); + var valid = true; - _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); + var valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { - } + console.error( "invalid value size in track", this ); + valid = false; - if ( object.hasUvs && material.map ) { + } - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); + var times = this.times, + values = this.values, - state.enableAttribute( attributes.uv ); + nKeys = times.length; - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); + if( nKeys === 0 ) { - } + console.error( "track is empty", this ); + valid = false; - if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { + } - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); + var prevTime = null; - state.enableAttribute( attributes.color ); + for( var i = 0; i !== nKeys; i ++ ) { - _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); + var currTime = times[ i ]; - } + if ( typeof currTime === 'number' && isNaN( currTime ) ) { - state.disableUnusedAttributes(); + console.error( "time is not a valid number", this, i, currTime ); + valid = false; + break; - _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); + } - object.count = 0; + if( prevTime !== null && prevTime > currTime ) { - }; + console.error( "out of order keys", this, i, currTime, prevTime ); + valid = false; + break; - this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { + } - setMaterial( material ); + prevTime = currTime; - var program = setProgram( camera, fog, material, object ); + } - var updateBuffers = false; - var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe; + if ( values !== undefined ) { - if ( geometryProgram !== _currentGeometryProgram ) { + if ( exports.AnimationUtils.isTypedArray( values ) ) { - _currentGeometryProgram = geometryProgram; - updateBuffers = true; + for ( var i = 0, n = values.length; i !== n; ++ i ) { - } + var value = values[ i ]; - // morph targets + if ( isNaN( value ) ) { - var morphTargetInfluences = object.morphTargetInfluences; + console.error( "value is not a valid number", this, i, value ); + valid = false; + break; - if ( morphTargetInfluences !== undefined ) { + } - var activeInfluences = []; + } - for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { + } - var influence = morphTargetInfluences[ i ]; - activeInfluences.push( [ influence, i ] ); + } - } + return valid; - activeInfluences.sort( absNumericalSort ); + }, - if ( activeInfluences.length > 8 ) { + // removes equivalent sequential keys as common in morph target sequences + // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) + optimize: function() { - activeInfluences.length = 8; + var times = this.times, + values = this.values, + stride = this.getValueSize(), - } + writeIndex = 1; - var morphAttributes = geometry.morphAttributes; + for( var i = 1, n = times.length - 1; i <= n; ++ i ) { - for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { + var keep = false; - var influence = activeInfluences[ i ]; - morphInfluences[ i ] = influence[ 0 ]; + var time = times[ i ]; + var timeNext = times[ i + 1 ]; - if ( influence[ 0 ] !== 0 ) { + // remove adjacent keyframes scheduled at the same time - var index = influence[ 1 ]; + if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { - if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] ); - if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] ); + // remove unnecessary keyframes same as their neighbors + var offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; - } else { + for ( var j = 0; j !== stride; ++ j ) { - if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); - if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); + var value = values[ offset + j ]; - } + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { - } + keep = true; + break; - program.getUniforms().setValue( - _gl, 'morphTargetInfluences', morphInfluences ); + } - updateBuffers = true; + } - } + } - // + // in-place compaction - var index = geometry.index; - var position = geometry.attributes.position; + if ( keep ) { - if ( material.wireframe === true ) { + if ( i !== writeIndex ) { - index = objects.getWireframeAttribute( geometry ); + times[ writeIndex ] = times[ i ]; - } + var readOffset = i * stride, + writeOffset = writeIndex * stride; - var renderer; + for ( var j = 0; j !== stride; ++ j ) { - if ( index !== null ) { + values[ writeOffset + j ] = values[ readOffset + j ]; - renderer = indexedBufferRenderer; - renderer.setIndex( index ); + } - } else { - renderer = bufferRenderer; + } - } + ++ writeIndex; - if ( updateBuffers ) { + } - setupVertexAttributes( material, program, geometry ); + } - if ( index !== null ) { + if ( writeIndex !== times.length ) { - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) ); + this.times = exports.AnimationUtils.arraySlice( times, 0, writeIndex ); + this.values = exports.AnimationUtils.arraySlice( values, 0, writeIndex * stride ); - } + } - } + return this; - // + } - var dataStart = 0; - var dataCount = Infinity; + } - if ( index !== null ) { + function KeyframeTrackConstructor ( name, times, values, interpolation ) { + this.isKeyframeTrack = true; - dataCount = index.count; + if( name === undefined ) throw new Error( "track name is undefined" ); - } else if ( position !== undefined ) { + if( times === undefined || times.length === 0 ) { - dataCount = position.count; + throw new Error( "no keyframes in track named " + name ); - } + } - var rangeStart = geometry.drawRange.start; - var rangeCount = geometry.drawRange.count; + this.name = name; - var groupStart = group !== null ? group.start : 0; - var groupCount = group !== null ? group.count : Infinity; + this.times = exports.AnimationUtils.convertArray( times, this.TimeBufferType ); + this.values = exports.AnimationUtils.convertArray( values, this.ValueBufferType ); - var drawStart = Math.max( dataStart, rangeStart, groupStart ); - var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; + this.setInterpolation( interpolation || this.DefaultInterpolation ); - var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); + this.validate(); + this.optimize(); - // + } - if ( object instanceof THREE.Mesh ) { + /** + * + * A Track of vectored keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - if ( material.wireframe === true ) { + function VectorKeyframeTrack ( name, times, values, interpolation ) { + this.isVectorKeyframeTrack = true; - state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); - renderer.setMode( _gl.LINES ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - } else { + }; - switch ( object.drawMode ) { + VectorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - case THREE.TrianglesDrawMode: - renderer.setMode( _gl.TRIANGLES ); - break; + constructor: VectorKeyframeTrack, - case THREE.TriangleStripDrawMode: - renderer.setMode( _gl.TRIANGLE_STRIP ); - break; + ValueTypeName: 'vector' - case THREE.TriangleFanDrawMode: - renderer.setMode( _gl.TRIANGLE_FAN ); - break; + // ValueBufferType is inherited - } + // DefaultInterpolation is inherited - } + } ); + /** + * Spherical linear unit quaternion interpolant. + * + * @author tschw + */ - } else if ( object instanceof THREE.Line ) { + function QuaternionLinearInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isQuaternionLinearInterpolant = true; - var lineWidth = material.linewidth; + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + }; - state.setLineWidth( lineWidth * getTargetPixelRatio() ); + QuaternionLinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - if ( object instanceof THREE.LineSegments ) { + constructor: QuaternionLinearInterpolant, - renderer.setMode( _gl.LINES ); + interpolate_: function( i1, t0, t, t1 ) { - } else { + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - renderer.setMode( _gl.LINE_STRIP ); + offset = i1 * stride, - } + alpha = ( t - t0 ) / ( t1 - t0 ); - } else if ( object instanceof THREE.Points ) { + for ( var end = offset + stride; offset !== end; offset += 4 ) { - renderer.setMode( _gl.POINTS ); + Quaternion.slerpFlat( result, 0, + values, offset - stride, values, offset, alpha ); - } + } - if ( geometry instanceof THREE.InstancedBufferGeometry ) { + return result; - if ( geometry.maxInstancedCount > 0 ) { + } - renderer.renderInstances( geometry, drawStart, drawCount ); + } ); - } + /** + * + * A Track of quaternion keyframe values. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } else { + function QuaternionKeyframeTrack ( name, times, values, interpolation ) { + this.isQuaternionKeyframeTrack = true; - renderer.render( drawStart, drawCount ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - } + }; - }; + QuaternionKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - function setupVertexAttributes( material, program, geometry, startIndex ) { + constructor: QuaternionKeyframeTrack, - var extension; + ValueTypeName: 'quaternion', - if ( geometry instanceof THREE.InstancedBufferGeometry ) { + // ValueBufferType is inherited - extension = extensions.get( 'ANGLE_instanced_arrays' ); + DefaultInterpolation: InterpolateLinear, - if ( extension === null ) { + InterpolantFactoryMethodLinear: function( result ) { - console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + return new QuaternionLinearInterpolant( + this.times, this.values, this.getValueSize(), result ); - } + }, - } + InterpolantFactoryMethodSmooth: undefined // not yet implemented - if ( startIndex === undefined ) startIndex = 0; + } ); - state.initAttributes(); + /** + * + * A Track of numeric keyframe values. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - var geometryAttributes = geometry.attributes; + function NumberKeyframeTrack ( name, times, values, interpolation ) { + this.isNumberKeyframeTrack = true; - var programAttributes = program.getAttributes(); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - var materialDefaultAttributeValues = material.defaultAttributeValues; + }; - for ( var name in programAttributes ) { + NumberKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - var programAttribute = programAttributes[ name ]; + constructor: NumberKeyframeTrack, - if ( programAttribute >= 0 ) { + ValueTypeName: 'number', - var geometryAttribute = geometryAttributes[ name ]; + // ValueBufferType is inherited - if ( geometryAttribute !== undefined ) { + // DefaultInterpolation is inherited - var type = _gl.FLOAT; - var array = geometryAttribute.array; - var normalized = geometryAttribute.normalized; + } ); - if ( array instanceof Float32Array ) { + /** + * + * A Track that interpolates Strings + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - type = _gl.FLOAT; + function StringKeyframeTrack ( name, times, values, interpolation ) { + this.isStringKeyframeTrack = true; - } else if ( array instanceof Float64Array ) { + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - console.warn("Unsupported data buffer format: Float64Array"); + }; - } else if ( array instanceof Uint16Array ) { + StringKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - type = _gl.UNSIGNED_SHORT; + constructor: StringKeyframeTrack, - } else if ( array instanceof Int16Array ) { + ValueTypeName: 'string', + ValueBufferType: Array, - type = _gl.SHORT; + DefaultInterpolation: InterpolateDiscrete, - } else if ( array instanceof Uint32Array ) { + InterpolantFactoryMethodLinear: undefined, - type = _gl.UNSIGNED_INT; + InterpolantFactoryMethodSmooth: undefined - } else if ( array instanceof Int32Array ) { + } ); - type = _gl.INT; + /** + * + * A Track of Boolean keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } else if ( array instanceof Int8Array ) { + function BooleanKeyframeTrack ( name, times, values ) { + this.isBooleanKeyframeTrack = true; - type = _gl.BYTE; + KeyframeTrackConstructor.call( this, name, times, values ); - } else if ( array instanceof Uint8Array ) { + }; - type = _gl.UNSIGNED_BYTE; + BooleanKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - } + constructor: BooleanKeyframeTrack, - var size = geometryAttribute.itemSize; - var buffer = objects.getAttributeBuffer( geometryAttribute ); + ValueTypeName: 'bool', + ValueBufferType: Array, - if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) { + DefaultInterpolation: InterpolateDiscrete, - var data = geometryAttribute.data; - var stride = data.stride; - var offset = geometryAttribute.offset; + InterpolantFactoryMethodLinear: undefined, + InterpolantFactoryMethodSmooth: undefined - if ( data instanceof THREE.InstancedInterleavedBuffer ) { + // Note: Actually this track could have a optimized / compressed + // representation of a single value and a custom interpolant that + // computes "firstValue ^ isOdd( index )". - state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); + } ); - if ( geometry.maxInstancedCount === undefined ) { + /** + * + * A Track of keyframe values that represent color. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - geometry.maxInstancedCount = data.meshPerAttribute * data.count; + function ColorKeyframeTrack ( name, times, values, interpolation ) { + this.isColorKeyframeTrack = true; - } + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - } else { + }; - state.enableAttribute( programAttribute ); + ColorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - } + constructor: ColorKeyframeTrack, - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT ); + ValueTypeName: 'color' - } else { + // ValueBufferType is inherited - if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) { + // DefaultInterpolation is inherited - state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); - if ( geometry.maxInstancedCount === undefined ) { + // Note: Very basic implementation and nothing special yet. + // However, this is the place for color space parameterization. - geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } ); - } + /** + * + * A timed sequence of keyframes for a specific property. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } else { + function KeyframeTrack ( name, times, values, interpolation ) { + KeyframeTrackConstructor.apply( this, arguments ); + }; - state.enableAttribute( programAttribute ); + KeyframeTrack.prototype = KeyframeTrackPrototype; + KeyframeTrackPrototype.constructor = KeyframeTrack; - } + // Static methods: - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT ); + Object.assign( KeyframeTrack, { - } + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): - } else if ( materialDefaultAttributeValues !== undefined ) { + parse: function( json ) { - var value = materialDefaultAttributeValues[ name ]; + if( json.type === undefined ) { - if ( value !== undefined ) { + throw new Error( "track type undefined, can not parse" ); - switch ( value.length ) { + } - case 2: - _gl.vertexAttrib2fv( programAttribute, value ); - break; + var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type ); - case 3: - _gl.vertexAttrib3fv( programAttribute, value ); - break; + if ( json.times === undefined ) { - case 4: - _gl.vertexAttrib4fv( programAttribute, value ); - break; + var times = [], values = []; - default: - _gl.vertexAttrib1fv( programAttribute, value ); + exports.AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); - } + json.times = times; + json.values = values; - } + } - } + // derived classes can define a static parse method + if ( trackType.parse !== undefined ) { - } + return trackType.parse( json ); - } + } else { - state.disableUnusedAttributes(); + // by default, we asssume a constructor compatible with the base + return new trackType( + json.name, json.times, json.values, json.interpolation ); - } + } - // Sorting + }, - function absNumericalSort( a, b ) { + toJSON: function( track ) { - return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] ); + var trackType = track.constructor; - } + var json; - function painterSortStable ( a, b ) { + // derived classes can define a static toJSON method + if ( trackType.toJSON !== undefined ) { - if ( a.object.renderOrder !== b.object.renderOrder ) { + json = trackType.toJSON( track ); - return a.object.renderOrder - b.object.renderOrder; + } else { - } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) { + // by default, we assume the data can be serialized as-is + json = { - return a.material.program.id - b.material.program.id; + 'name': track.name, + 'times': exports.AnimationUtils.convertArray( track.times, Array ), + 'values': exports.AnimationUtils.convertArray( track.values, Array ) - } else if ( a.material.id !== b.material.id ) { + }; - return a.material.id - b.material.id; + var interpolation = track.getInterpolation(); - } else if ( a.z !== b.z ) { + if ( interpolation !== track.DefaultInterpolation ) { - return a.z - b.z; + json.interpolation = interpolation; - } else { + } - return a.id - b.id; + } - } + json.type = track.ValueTypeName; // mandatory - } + return json; - function reversePainterSortStable ( a, b ) { + }, - if ( a.object.renderOrder !== b.object.renderOrder ) { + _getTrackTypeForValueTypeName: function( typeName ) { - return a.object.renderOrder - b.object.renderOrder; + switch( typeName.toLowerCase() ) { - } if ( a.z !== b.z ) { + case "scalar": + case "double": + case "float": + case "number": + case "integer": - return b.z - a.z; + return NumberKeyframeTrack; - } else { + case "vector": + case "vector2": + case "vector3": + case "vector4": - return a.id - b.id; + return VectorKeyframeTrack; - } + case "color": - } + return ColorKeyframeTrack; - // Rendering + case "quaternion": - this.render = function ( scene, camera, renderTarget, forceClear ) { + return QuaternionKeyframeTrack; - if ( camera instanceof THREE.Camera === false ) { + case "bool": + case "boolean": - console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); - return; + return BooleanKeyframeTrack; - } + case "string": - var fog = scene.fog; + return StringKeyframeTrack; - // reset caching for this frame + } - _currentGeometryProgram = ''; - _currentMaterialId = - 1; - _currentCamera = null; + throw new Error( "Unsupported typeName: " + typeName ); - // update scene graph + } - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); + } ); - // update camera matrices and frustum + /** + * + * Reusable set of Tracks that represent an animation. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - if ( camera.parent === null ) camera.updateMatrixWorld(); + function AnimationClip ( name, duration, tracks ) { + this.isAnimationClip = true; - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); + this.name = name; + this.tracks = tracks; + this.duration = ( duration !== undefined ) ? duration : -1; - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + this.uuid = exports.Math.generateUUID(); - lights.length = 0; + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { - opaqueObjectsLastIndex = - 1; - transparentObjectsLastIndex = - 1; + this.resetDuration(); - sprites.length = 0; - lensFlares.length = 0; + } - _localClippingEnabled = this.localClippingEnabled; - _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); + // maybe only do these on demand, as doing them here could potentially slow down loading + // but leaving these here during development as this ensures a lot of testing of these functions + this.trim(); + this.optimize(); - projectObject( scene, camera ); + }; - opaqueObjects.length = opaqueObjectsLastIndex + 1; - transparentObjects.length = transparentObjectsLastIndex + 1; + AnimationClip.prototype = { - if ( _this.sortObjects === true ) { + constructor: AnimationClip, - opaqueObjects.sort( painterSortStable ); - transparentObjects.sort( reversePainterSortStable ); + resetDuration: function() { - } + var tracks = this.tracks, + duration = 0; - // + for ( var i = 0, n = tracks.length; i !== n; ++ i ) { - if ( _clippingEnabled ) _clipping.beginShadows(); + var track = this.tracks[ i ]; - setupShadows( lights ); + duration = Math.max( + duration, track.times[ track.times.length - 1 ] ); - shadowMap.render( scene, camera ); + } - setupLights( lights, camera ); + this.duration = duration; - if ( _clippingEnabled ) _clipping.endShadows(); + }, - // + trim: function() { - _infoRender.calls = 0; - _infoRender.vertices = 0; - _infoRender.faces = 0; - _infoRender.points = 0; + for ( var i = 0; i < this.tracks.length; i ++ ) { - if ( renderTarget === undefined ) { + this.tracks[ i ].trim( 0, this.duration ); - renderTarget = null; + } - } + return this; - this.setRenderTarget( renderTarget ); + }, - // + optimize: function() { - var background = scene.background; + for ( var i = 0; i < this.tracks.length; i ++ ) { - if ( background === null ) { + this.tracks[ i ].optimize(); - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + } - } else if ( background instanceof THREE.Color ) { + return this; - glClearColor( background.r, background.g, background.b, 1 ); + } - } + }; - if ( this.autoClear || forceClear ) { + // Static methods: - this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); + Object.assign( AnimationClip, { - } + parse: function( json ) { - if ( background instanceof THREE.CubeTexture ) { + var tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); - backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); + for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { - backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld ); - backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld ); + tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); - backgroundBoxMesh.material.uniforms[ "tCube" ].value = background; - backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld ); + } - objects.update( backgroundBoxMesh ); + return new AnimationClip( json.name, json.duration, tracks ); - _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); + }, - } else if ( background instanceof THREE.Texture ) { - backgroundPlaneMesh.material.map = background; + toJSON: function( clip ) { - objects.update( backgroundPlaneMesh ); + var tracks = [], + clipTracks = clip.tracks; - _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null ); + var json = { - } + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks - // + }; - if ( scene.overrideMaterial ) { + for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { - var overrideMaterial = scene.overrideMaterial; + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); - renderObjects( opaqueObjects, camera, fog, overrideMaterial ); - renderObjects( transparentObjects, camera, fog, overrideMaterial ); + } - } else { + return json; - // opaque pass (front-to-back order) + }, - state.setBlending( THREE.NoBlending ); - renderObjects( opaqueObjects, camera, fog ); - // transparent pass (back-to-front order) + CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) { - renderObjects( transparentObjects, camera, fog ); + var numMorphTargets = morphTargetSequence.length; + var tracks = []; - } + for ( var i = 0; i < numMorphTargets; i ++ ) { - // custom render plugins (post pass) + var times = []; + var values = []; - spritePlugin.render( scene, camera ); - lensFlarePlugin.render( scene, camera, _currentViewport ); + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); - // Generate mipmap if we're using any kind of mipmap filtering + values.push( 0, 1, 0 ); - if ( renderTarget ) { + var order = exports.AnimationUtils.getKeyframeOrder( times ); + times = exports.AnimationUtils.sortedArray( times, 1, order ); + values = exports.AnimationUtils.sortedArray( values, 1, order ); - textures.updateRenderTargetMipmap( renderTarget ); + // if there is a key at the first frame, duplicate it as the + // last frame as well for perfect loop. + if ( ! noLoop && times[ 0 ] === 0 ) { - } + times.push( numMorphTargets ); + values.push( values[ 0 ] ); - // Ensure depth buffer writing is enabled so it can be cleared on next render + } - state.setDepthTest( true ); - state.setDepthWrite( true ); - state.setColorWrite( true ); + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); + } - // _gl.finish(); + return new AnimationClip( name, -1, tracks ); - }; + }, - function pushRenderItem( object, geometry, material, z, group ) { + findByName: function( objectOrClipArray, name ) { - var array, index; + var clipArray = objectOrClipArray; - // allocate the next position in the appropriate array + if ( ! Array.isArray( objectOrClipArray ) ) { - if ( material.transparent ) { + var o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; - array = transparentObjects; - index = ++ transparentObjectsLastIndex; + } - } else { + for ( var i = 0; i < clipArray.length; i ++ ) { - array = opaqueObjects; - index = ++ opaqueObjectsLastIndex; + if ( clipArray[ i ].name === name ) { - } + return clipArray[ i ]; - // recycle existing render item or grow the array + } + } - var renderItem = array[ index ]; + return null; - if ( renderItem !== undefined ) { + }, - renderItem.id = object.id; - renderItem.object = object; - renderItem.geometry = geometry; - renderItem.material = material; - renderItem.z = _vector3.z; - renderItem.group = group; + CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) { - } else { + var animationToMorphTargets = {}; - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - z: _vector3.z, - group: group - }; + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + var pattern = /^([\w-]*?)([\d]+)$/; - // assert( index === array.length ); - array.push( renderItem ); + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { - } + var morphTarget = morphTargets[ i ]; + var parts = morphTarget.name.match( pattern ); - } + if ( parts && parts.length > 1 ) { - // TODO Duplicated code (Frustum) + var name = parts[ 1 ]; - function isObjectViewable( object ) { + var animationMorphTargets = animationToMorphTargets[ name ]; + if ( ! animationMorphTargets ) { - var geometry = object.geometry; + animationToMorphTargets[ name ] = animationMorphTargets = []; - if ( geometry.boundingSphere === null ) - geometry.computeBoundingSphere(); + } - _sphere.copy( geometry.boundingSphere ). - applyMatrix4( object.matrixWorld ); + animationMorphTargets.push( morphTarget ); - return isSphereViewable( _sphere ); + } - } + } - function isSpriteViewable( sprite ) { + var clips = []; - _sphere.center.set( 0, 0, 0 ); - _sphere.radius = 0.7071067811865476; - _sphere.applyMatrix4( sprite.matrixWorld ); + for ( var name in animationToMorphTargets ) { - return isSphereViewable( _sphere ); + clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); - } + } - function isSphereViewable( sphere ) { + return clips; - if ( ! _frustum.intersectsSphere( sphere ) ) return false; + }, - var numPlanes = _clipping.numPlanes; + // parse the animation.hierarchy format + parseAnimation: function( animation, bones, nodeName ) { - if ( numPlanes === 0 ) return true; + if ( ! animation ) { - var planes = _this.clippingPlanes, + console.error( " no animation in JSONLoader data" ); + return null; - center = sphere.center, - negRad = - sphere.radius, - i = 0; + } - do { + var addNonemptyTrack = function( + trackType, trackName, animationKeys, propertyName, destTracks ) { - // out when deeper than radius in the negative halfspace - if ( planes[ i ].distanceToPoint( center ) < negRad ) return false; + // only return track if there are actually keys. + if ( animationKeys.length !== 0 ) { - } while ( ++ i !== numPlanes ); + var times = []; + var values = []; - return true; + exports.AnimationUtils.flattenJSON( + animationKeys, times, values, propertyName ); - } + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { - function projectObject( object, camera ) { + destTracks.push( new trackType( trackName, times, values ) ); - if ( object.visible === false ) return; + } - if ( object.layers.test( camera.layers ) ) { + } - if ( object instanceof THREE.Light ) { + }; - lights.push( object ); + var tracks = []; - } else if ( object instanceof THREE.Sprite ) { + var clipName = animation.name || 'default'; + // automatic length determination in AnimationClip. + var duration = animation.length || -1; + var fps = animation.fps || 30; - if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) { + var hierarchyTracks = animation.hierarchy || []; - sprites.push( object ); + for ( var h = 0; h < hierarchyTracks.length; h ++ ) { - } + var animationKeys = hierarchyTracks[ h ].keys; - } else if ( object instanceof THREE.LensFlare ) { + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; - lensFlares.push( object ); + // process morph targets in a way exactly compatible + // with AnimationHandler.init( animation ) + if ( animationKeys[0].morphTargets ) { - } else if ( object instanceof THREE.ImmediateRenderObject ) { + // figure out all morph targets used in this track + var morphTargetNames = {}; + for ( var k = 0; k < animationKeys.length; k ++ ) { - if ( _this.sortObjects === true ) { + if ( animationKeys[k].morphTargets ) { - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); + for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) { - } + morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1; + } - pushRenderItem( object, null, object.material, _vector3.z, null ); + } - } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) { + } - if ( object instanceof THREE.SkinnedMesh ) { + // create a track for each morph target with all zero + // morphTargetInfluences except for the keys in which + // the morphTarget is named. + for ( var morphTargetName in morphTargetNames ) { - object.skeleton.update(); + var times = []; + var values = []; - } + for ( var m = 0; + m !== animationKeys[k].morphTargets.length; ++ m ) { - if ( object.frustumCulled === false || isObjectViewable( object ) === true ) { + var animationKey = animationKeys[k]; - var material = object.material; + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); - if ( material.visible === true ) { + } - if ( _this.sortObjects === true ) { + tracks.push( new NumberKeyframeTrack( + '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); + } - } + duration = morphTargetNames.length * ( fps || 1.0 ); - var geometry = objects.update( object ); + } else { + // ...assume skeletal animation - if ( material instanceof THREE.MultiMaterial ) { + var boneName = '.bones[' + bones[ h ].name + ']'; - var groups = geometry.groups; - var materials = material.materials; + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); - for ( var i = 0, l = groups.length; i < l; i ++ ) { + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); - var group = groups[ i ]; - var groupMaterial = materials[ group.materialIndex ]; + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); - if ( groupMaterial.visible === true ) { + } - pushRenderItem( object, geometry, groupMaterial, _vector3.z, group ); + } - } + if ( tracks.length === 0 ) { - } + return null; - } else { + } - pushRenderItem( object, geometry, material, _vector3.z, null ); + var clip = new AnimationClip( clipName, duration, tracks ); - } + return clip; - } + } - } + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function MaterialLoader ( manager ) { + this.isMaterialLoader = true; - var children = object.children; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + this.textures = {}; - for ( var i = 0, l = children.length; i < l; i ++ ) { + }; - projectObject( children[ i ], camera ); + Object.assign( MaterialLoader.prototype, { - } + load: function ( url, onLoad, onProgress, onError ) { - } + var scope = this; - function renderObjects( renderList, camera, fog, overrideMaterial ) { + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - for ( var i = 0, l = renderList.length; i < l; i ++ ) { + onLoad( scope.parse( JSON.parse( text ) ) ); - var renderItem = renderList[ i ]; + }, onProgress, onError ); - var object = renderItem.object; - var geometry = renderItem.geometry; - var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; - var group = renderItem.group; + }, - object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + setTextures: function ( value ) { - if ( object instanceof THREE.ImmediateRenderObject ) { + this.textures = value; - setMaterial( material ); + }, - var program = setProgram( camera, fog, material, object ); + getTexture: function ( name ) { - _currentGeometryProgram = ''; + var textures = this.textures; - object.render( function ( object ) { + if ( textures[ name ] === undefined ) { - _this.renderBufferImmediate( object, program, material ); + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); - } ); + } - } else { + return textures[ name ]; - _this.renderBufferDirect( camera, fog, geometry, material, object, group ); + }, - } + parse: function ( json ) { - } + var material = new THREE[ json.type ]; - } + if ( json.uuid !== undefined ) material.uuid = json.uuid; + if ( json.name !== undefined ) material.name = json.name; + if ( json.color !== undefined ) material.color.setHex( json.color ); + if ( json.roughness !== undefined ) material.roughness = json.roughness; + if ( json.metalness !== undefined ) material.metalness = json.metalness; + if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.uniforms !== undefined ) material.uniforms = json.uniforms; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; + if ( json.shading !== undefined ) material.shading = json.shading; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.side !== undefined ) material.side = json.side; + if ( json.opacity !== undefined ) material.opacity = json.opacity; + if ( json.transparent !== undefined ) material.transparent = json.transparent; + if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest; + if ( json.depthTest !== undefined ) material.depthTest = json.depthTest; + if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite; + if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite; + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; - function initMaterial( material, fog, object ) { + // for PointsMaterial + if ( json.size !== undefined ) material.size = json.size; + if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; - var materialProperties = properties.get( material ); + // maps - var parameters = programCache.getParameters( - material, _lights, fog, _clipping.numPlanes, object ); + if ( json.map !== undefined ) material.map = this.getTexture( json.map ); - var code = programCache.getProgramCode( material, parameters ); + if ( json.alphaMap !== undefined ) { - var program = materialProperties.program; - var programChange = true; + material.alphaMap = this.getTexture( json.alphaMap ); + material.transparent = true; - if ( program === undefined ) { + } - // new material - material.addEventListener( 'dispose', onMaterialDispose ); + if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; - } else if ( program.code !== code ) { + if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap ); + if ( json.normalScale !== undefined ) { - // changed glsl or parameters - releaseMaterialProgramReference( material ); + var normalScale = json.normalScale; - } else if ( parameters.shaderID !== undefined ) { + if ( Array.isArray( normalScale ) === false ) { - // same glsl and uniform list - return; + // Blender exporter used to export a scalar. See #7459 - } else { + normalScale = [ normalScale, normalScale ]; - // only rebuild uniform list - programChange = false; + } - } + material.normalScale = new Vector2().fromArray( normalScale ); - if ( programChange ) { + } - if ( parameters.shaderID ) { + if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap ); + if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; + if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; - var shader = THREE.ShaderLib[ parameters.shaderID ]; + if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap ); - materialProperties.__webglShader = { - name: material.type, - uniforms: THREE.UniformsUtils.clone( shader.uniforms ), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader - }; + if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; - } else { + if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap ); - materialProperties.__webglShader = { - name: material.type, - uniforms: material.uniforms, - vertexShader: material.vertexShader, - fragmentShader: material.fragmentShader - }; + if ( json.envMap !== undefined ) { - } + material.envMap = this.getTexture( json.envMap ); + material.combine = MultiplyOperation; - material.__webglShader = materialProperties.__webglShader; + } - program = programCache.acquireProgram( material, parameters, code ); + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; - materialProperties.program = program; - material.program = program; + if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; - } + if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; - var attributes = program.getAttributes(); + // MultiMaterial - if ( material.morphTargets ) { + if ( json.materials !== undefined ) { - material.numSupportedMorphTargets = 0; + for ( var i = 0, l = json.materials.length; i < l; i ++ ) { - for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { + material.materials.push( this.parse( json.materials[ i ] ) ); - if ( attributes[ 'morphTarget' + i ] >= 0 ) { + } - material.numSupportedMorphTargets ++; + } - } + return material; - } + } - } + } ); - if ( material.morphNormals ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - material.numSupportedMorphNormals = 0; + function BufferGeometryLoader ( manager ) { + this.isBufferGeometryLoader = true; - for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - if ( attributes[ 'morphNormal' + i ] >= 0 ) { + }; - material.numSupportedMorphNormals ++; + Object.assign( BufferGeometryLoader.prototype, { - } + load: function ( url, onLoad, onProgress, onError ) { - } + var scope = this; - } + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - var uniforms = materialProperties.__webglShader.uniforms; + onLoad( scope.parse( JSON.parse( text ) ) ); - if ( ! ( material instanceof THREE.ShaderMaterial ) && - ! ( material instanceof THREE.RawShaderMaterial ) || - material.clipping === true ) { + }, onProgress, onError ); - materialProperties.numClippingPlanes = _clipping.numPlanes; - uniforms.clippingPlanes = _clipping.uniform; + }, - } + parse: function ( json ) { - if ( material.lights ) { + var geometry = new BufferGeometry(); - // store the light setup it was created for + var index = json.data.index; - materialProperties.lightsHash = _lights.hash; + var TYPED_ARRAYS = { + 'Int8Array': Int8Array, + 'Uint8Array': Uint8Array, + 'Uint8ClampedArray': Uint8ClampedArray, + 'Int16Array': Int16Array, + 'Uint16Array': Uint16Array, + 'Int32Array': Int32Array, + 'Uint32Array': Uint32Array, + 'Float32Array': Float32Array, + 'Float64Array': Float64Array + }; - // wire up the material to this renderer's lighting state + if ( index !== undefined ) { - uniforms.ambientLightColor.value = _lights.ambient; - uniforms.directionalLights.value = _lights.directional; - uniforms.spotLights.value = _lights.spot; - uniforms.pointLights.value = _lights.point; - uniforms.hemisphereLights.value = _lights.hemi; + var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); - uniforms.directionalShadowMap.value = _lights.directionalShadowMap; - uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix; - uniforms.spotShadowMap.value = _lights.spotShadowMap; - uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix; - uniforms.pointShadowMap.value = _lights.pointShadowMap; - uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix; + } - } + var attributes = json.data.attributes; - var progUniforms = materialProperties.program.getUniforms(), - uniformsList = - THREE.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + for ( var key in attributes ) { - materialProperties.uniformsList = uniformsList; - materialProperties.dynamicUniforms = - THREE.WebGLUniforms.splitDynamic( uniformsList, uniforms ); + var attribute = attributes[ key ]; + var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); - } + geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); - function setMaterial( material ) { + } - if ( material.side !== THREE.DoubleSide ) - state.enable( _gl.CULL_FACE ); - else - state.disable( _gl.CULL_FACE ); + var groups = json.data.groups || json.data.drawcalls || json.data.offsets; - state.setFlipSided( material.side === THREE.BackSide ); + if ( groups !== undefined ) { - if ( material.transparent === true ) { + for ( var i = 0, n = groups.length; i !== n; ++ i ) { - state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); + var group = groups[ i ]; - } else { + geometry.addGroup( group.start, group.count, group.materialIndex ); - state.setBlending( THREE.NoBlending ); + } - } + } - state.setDepthFunc( material.depthFunc ); - state.setDepthTest( material.depthTest ); - state.setDepthWrite( material.depthWrite ); - state.setColorWrite( material.colorWrite ); - state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + var boundingSphere = json.data.boundingSphere; - } + if ( boundingSphere !== undefined ) { - function setProgram( camera, fog, material, object ) { + var center = new Vector3(); - _usedTextureUnits = 0; + if ( boundingSphere.center !== undefined ) { - var materialProperties = properties.get( material ); + center.fromArray( boundingSphere.center ); - if ( _clippingEnabled ) { + } - if ( _localClippingEnabled || camera !== _currentCamera ) { + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); - var useCache = - camera === _currentCamera && - material.id === _currentMaterialId; + } - // we might want to call this function with some ClippingGroup - // object instead of the material, once it becomes feasible - // (#8465, #8379) - _clipping.setState( - material.clippingPlanes, material.clipShadows, - camera, materialProperties, useCache ); + return geometry; - } + } - if ( materialProperties.numClippingPlanes !== undefined && - materialProperties.numClippingPlanes !== _clipping.numPlanes ) { + } ); - material.needsUpdate = true; + /** + * @author alteredq / http://alteredqualia.com/ + */ - } + function Loader () { + this.isLoader = true; - } + this.onLoadStart = function () {}; + this.onLoadProgress = function () {}; + this.onLoadComplete = function () {}; - if ( materialProperties.program === undefined ) { + }; - material.needsUpdate = true; + Loader.prototype = { - } + constructor: Loader, - if ( materialProperties.lightsHash !== undefined && - materialProperties.lightsHash !== _lights.hash ) { + crossOrigin: undefined, - material.needsUpdate = true; + extractUrlBase: function ( url ) { - } + var parts = url.split( '/' ); - if ( material.needsUpdate ) { + if ( parts.length === 1 ) return './'; - initMaterial( material, fog, object ); - material.needsUpdate = false; + parts.pop(); - } + return parts.join( '/' ) + '/'; - var refreshProgram = false; - var refreshMaterial = false; - var refreshLights = false; + }, - var program = materialProperties.program, - p_uniforms = program.getUniforms(), - m_uniforms = materialProperties.__webglShader.uniforms; + initMaterials: function ( materials, texturePath, crossOrigin ) { - if ( program.id !== _currentProgram ) { + var array = []; - _gl.useProgram( program.program ); - _currentProgram = program.id; + for ( var i = 0; i < materials.length; ++ i ) { - refreshProgram = true; - refreshMaterial = true; - refreshLights = true; + array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); - } + } - if ( material.id !== _currentMaterialId ) { + return array; - _currentMaterialId = material.id; + }, - refreshMaterial = true; + createMaterial: ( function () { - } + var color, textureLoader, materialLoader; - if ( refreshProgram || camera !== _currentCamera ) { + return function createMaterial( m, texturePath, crossOrigin ) { - p_uniforms.set( _gl, camera, 'projectionMatrix' ); + if ( color === undefined ) color = new Color(); + if ( textureLoader === undefined ) textureLoader = new TextureLoader(); + if ( materialLoader === undefined ) materialLoader = new MaterialLoader(); - if ( capabilities.logarithmicDepthBuffer ) { + // convert from old material format - p_uniforms.setValue( _gl, 'logDepthBufFC', - 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + var textures = {}; - } + function loadTexture( path, repeat, offset, wrap, anisotropy ) { + var fullPath = texturePath + path; + var loader = Loader.Handlers.get( fullPath ); - if ( camera !== _currentCamera ) { + var texture; - _currentCamera = camera; + if ( loader !== null ) { - // lighting uniforms depend on the camera so enforce an update - // now, in case this material supports lights - or later, when - // the next material that does gets activated: + texture = loader.load( fullPath ); - refreshMaterial = true; // set to true on material change - refreshLights = true; // remains set until update done + } else { - } + textureLoader.setCrossOrigin( crossOrigin ); + texture = textureLoader.load( fullPath ); - // load material specific uniforms - // (shader material also gets them for the sake of genericity) + } - if ( material instanceof THREE.ShaderMaterial || - material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshStandardMaterial || - material.envMap ) { + if ( repeat !== undefined ) { - var uCamPos = p_uniforms.map.cameraPosition; + texture.repeat.fromArray( repeat ); - if ( uCamPos !== undefined ) { + if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping; + if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping; - uCamPos.setValue( _gl, - _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + } - } + if ( offset !== undefined ) { - } + texture.offset.fromArray( offset ); - if ( material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshStandardMaterial || - material instanceof THREE.ShaderMaterial || - material.skinning ) { + } - p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + if ( wrap !== undefined ) { - } + if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping; + if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping; - p_uniforms.set( _gl, _this, 'toneMappingExposure' ); - p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' ); + if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping; + if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping; - } + } - // skinning uniforms must be set even if material didn't change - // auto-setting of texture unit for bone texture must go before other textures - // not sure why, but otherwise weird things happen + if ( anisotropy !== undefined ) { - if ( material.skinning ) { + texture.anisotropy = anisotropy; - p_uniforms.setOptional( _gl, object, 'bindMatrix' ); - p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + } - var skeleton = object.skeleton; + var uuid = exports.Math.generateUUID(); - if ( skeleton ) { + textures[ uuid ] = texture; - if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) { + return uuid; - p_uniforms.set( _gl, skeleton, 'boneTexture' ); - p_uniforms.set( _gl, skeleton, 'boneTextureWidth' ); - p_uniforms.set( _gl, skeleton, 'boneTextureHeight' ); + } - } else { + // - p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); + var json = { + uuid: exports.Math.generateUUID(), + type: 'MeshLambertMaterial' + }; + + for ( var name in m ) { + + var value = m[ name ]; + + switch ( name ) { + case 'DbgColor': + case 'DbgIndex': + case 'opticalDensity': + case 'illumination': + break; + case 'DbgName': + json.name = value; + break; + case 'blending': + json.blending = THREE[ value ]; + break; + case 'colorAmbient': + case 'mapAmbient': + console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' ); + break; + case 'colorDiffuse': + json.color = color.fromArray( value ).getHex(); + break; + case 'colorSpecular': + json.specular = color.fromArray( value ).getHex(); + break; + case 'colorEmissive': + json.emissive = color.fromArray( value ).getHex(); + break; + case 'specularCoef': + json.shininess = value; + break; + case 'shading': + if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial'; + if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial'; + if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial'; + break; + case 'mapDiffuse': + json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); + break; + case 'mapDiffuseRepeat': + case 'mapDiffuseOffset': + case 'mapDiffuseWrap': + case 'mapDiffuseAnisotropy': + break; + case 'mapEmissive': + json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy ); + break; + case 'mapEmissiveRepeat': + case 'mapEmissiveOffset': + case 'mapEmissiveWrap': + case 'mapEmissiveAnisotropy': + break; + case 'mapLight': + json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); + break; + case 'mapLightRepeat': + case 'mapLightOffset': + case 'mapLightWrap': + case 'mapLightAnisotropy': + break; + case 'mapAO': + json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy ); + break; + case 'mapAORepeat': + case 'mapAOOffset': + case 'mapAOWrap': + case 'mapAOAnisotropy': + break; + case 'mapBump': + json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); + break; + case 'mapBumpScale': + json.bumpScale = value; + break; + case 'mapBumpRepeat': + case 'mapBumpOffset': + case 'mapBumpWrap': + case 'mapBumpAnisotropy': + break; + case 'mapNormal': + json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); + break; + case 'mapNormalFactor': + json.normalScale = [ value, value ]; + break; + case 'mapNormalRepeat': + case 'mapNormalOffset': + case 'mapNormalWrap': + case 'mapNormalAnisotropy': + break; + case 'mapSpecular': + json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); + break; + case 'mapSpecularRepeat': + case 'mapSpecularOffset': + case 'mapSpecularWrap': + case 'mapSpecularAnisotropy': + break; + case 'mapMetalness': + json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy ); + break; + case 'mapMetalnessRepeat': + case 'mapMetalnessOffset': + case 'mapMetalnessWrap': + case 'mapMetalnessAnisotropy': + break; + case 'mapRoughness': + json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy ); + break; + case 'mapRoughnessRepeat': + case 'mapRoughnessOffset': + case 'mapRoughnessWrap': + case 'mapRoughnessAnisotropy': + break; + case 'mapAlpha': + json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); + break; + case 'mapAlphaRepeat': + case 'mapAlphaOffset': + case 'mapAlphaWrap': + case 'mapAlphaAnisotropy': + break; + case 'flipSided': + json.side = BackSide; + break; + case 'doubleSided': + json.side = DoubleSide; + break; + case 'transparency': + console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' ); + json.opacity = value; + break; + case 'depthTest': + case 'depthWrite': + case 'colorWrite': + case 'opacity': + case 'reflectivity': + case 'transparent': + case 'visible': + case 'wireframe': + json[ name ] = value; + break; + case 'vertexColors': + if ( value === true ) json.vertexColors = VertexColors; + if ( value === 'face' ) json.vertexColors = FaceColors; + break; + default: + console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); + break; + } + + } + + if ( json.type === 'MeshBasicMaterial' ) delete json.emissive; + if ( json.type !== 'MeshPhongMaterial' ) delete json.specular; + + if ( json.opacity < 1 ) json.transparent = true; + + materialLoader.setTextures( textures ); + + return materialLoader.parse( json ); - } + }; - } + } )() - } + }; - if ( refreshMaterial ) { + Loader.Handlers = { - if ( material.lights ) { + handlers: [], - // the current material requires lighting info + add: function ( regex, loader ) { - // note: all lighting uniforms are always set correctly - // they simply reference the renderer's state for their - // values - // - // use the current material's .needsUpdate flags to set - // the GL state when required + this.handlers.push( regex, loader ); - markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + }, - } + get: function ( file ) { - // refresh uniforms common to several materials + var handlers = this.handlers; - if ( fog && material.fog ) { + for ( var i = 0, l = handlers.length; i < l; i += 2 ) { - refreshUniformsFog( m_uniforms, fog ); + var regex = handlers[ i ]; + var loader = handlers[ i + 1 ]; - } + if ( regex.test( file ) ) { - if ( material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshStandardMaterial || - material instanceof THREE.MeshDepthMaterial ) { + return loader; - refreshUniformsCommon( m_uniforms, material ); + } - } + } - // refresh single material specific uniforms + return null; - if ( material instanceof THREE.LineBasicMaterial ) { + } - refreshUniformsLine( m_uniforms, material ); + }; - } else if ( material instanceof THREE.LineDashedMaterial ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - refreshUniformsLine( m_uniforms, material ); - refreshUniformsDash( m_uniforms, material ); + function JSONLoader ( manager ) { + this.isJSONLoader = true; - } else if ( material instanceof THREE.PointsMaterial ) { + if ( typeof manager === 'boolean' ) { - refreshUniformsPoints( m_uniforms, material ); + console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); + manager = undefined; - } else if ( material instanceof THREE.MeshLambertMaterial ) { + } - refreshUniformsLambert( m_uniforms, material ); + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - } else if ( material instanceof THREE.MeshPhongMaterial ) { + this.withCredentials = false; - refreshUniformsPhong( m_uniforms, material ); + }; - } else if ( material instanceof THREE.MeshPhysicalMaterial ) { + Object.assign( JSONLoader.prototype, { - refreshUniformsPhysical( m_uniforms, material ); + load: function( url, onLoad, onProgress, onError ) { - } else if ( material instanceof THREE.MeshStandardMaterial ) { + var scope = this; - refreshUniformsStandard( m_uniforms, material ); + var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url ); - } else if ( material instanceof THREE.MeshDepthMaterial ) { + var loader = new XHRLoader( this.manager ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { - if ( material.displacementMap ) { + var json = JSON.parse( text ); + var metadata = json.metadata; - m_uniforms.displacementMap.value = material.displacementMap; - m_uniforms.displacementScale.value = material.displacementScale; - m_uniforms.displacementBias.value = material.displacementBias; + if ( metadata !== undefined ) { - } + var type = metadata.type; - } else if ( material instanceof THREE.MeshNormalMaterial ) { + if ( type !== undefined ) { - m_uniforms.opacity.value = material.opacity; + if ( type.toLowerCase() === 'object' ) { - } + console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); + return; - THREE.WebGLUniforms.upload( - _gl, materialProperties.uniformsList, m_uniforms, _this ); + } - } + if ( type.toLowerCase() === 'scene' ) { + console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' ); + return; - // common matrices + } - p_uniforms.set( _gl, object, 'modelViewMatrix' ); - p_uniforms.set( _gl, object, 'normalMatrix' ); - p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + } + } - // dynamic uniforms + var object = scope.parse( json, texturePath ); + onLoad( object.geometry, object.materials ); - var dynUniforms = materialProperties.dynamicUniforms; + }, onProgress, onError ); - if ( dynUniforms !== null ) { + }, - THREE.WebGLUniforms.evalDynamic( - dynUniforms, m_uniforms, object, camera ); + setTexturePath: function ( value ) { - THREE.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); + this.texturePath = value; - } + }, - return program; + parse: function ( json, texturePath ) { - } + var geometry = new Geometry(), + scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; - // Uniforms (refresh uniforms objects) + parseModel( scale ); - function refreshUniformsCommon ( uniforms, material ) { + parseSkin(); + parseMorphing( scale ); + parseAnimations(); - uniforms.opacity.value = material.opacity; + geometry.computeFaceNormals(); + geometry.computeBoundingSphere(); - uniforms.diffuse.value = material.color; + function parseModel( scale ) { - if ( material.emissive ) { + function isBitSet( value, position ) { - uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + return value & ( 1 << position ); - } + } - uniforms.map.value = material.map; - uniforms.specularMap.value = material.specularMap; - uniforms.alphaMap.value = material.alphaMap; + var i, j, fi, - if ( material.aoMap ) { + offset, zLength, - uniforms.aoMap.value = material.aoMap; - uniforms.aoMapIntensity.value = material.aoMapIntensity; + colorIndex, normalIndex, uvIndex, materialIndex, - } + type, + isQuad, + hasMaterial, + hasFaceVertexUv, + hasFaceNormal, hasFaceVertexNormal, + hasFaceColor, hasFaceVertexColor, - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. normal map - // 4. bump map - // 5. alpha map - // 6. emissive map + vertex, face, faceA, faceB, hex, normal, - var uvScaleMap; + uvLayer, uv, u, v, - if ( material.map ) { + faces = json.faces, + vertices = json.vertices, + normals = json.normals, + colors = json.colors, - uvScaleMap = material.map; + nUvLayers = 0; - } else if ( material.specularMap ) { + if ( json.uvs !== undefined ) { - uvScaleMap = material.specularMap; + // disregard empty arrays - } else if ( material.displacementMap ) { + for ( i = 0; i < json.uvs.length; i ++ ) { - uvScaleMap = material.displacementMap; + if ( json.uvs[ i ].length ) nUvLayers ++; - } else if ( material.normalMap ) { + } - uvScaleMap = material.normalMap; + for ( i = 0; i < nUvLayers; i ++ ) { - } else if ( material.bumpMap ) { + geometry.faceVertexUvs[ i ] = []; - uvScaleMap = material.bumpMap; + } - } else if ( material.roughnessMap ) { + } - uvScaleMap = material.roughnessMap; + offset = 0; + zLength = vertices.length; - } else if ( material.metalnessMap ) { + while ( offset < zLength ) { - uvScaleMap = material.metalnessMap; + vertex = new Vector3(); - } else if ( material.alphaMap ) { + vertex.x = vertices[ offset ++ ] * scale; + vertex.y = vertices[ offset ++ ] * scale; + vertex.z = vertices[ offset ++ ] * scale; - uvScaleMap = material.alphaMap; + geometry.vertices.push( vertex ); - } else if ( material.emissiveMap ) { + } - uvScaleMap = material.emissiveMap; + offset = 0; + zLength = faces.length; - } + while ( offset < zLength ) { - if ( uvScaleMap !== undefined ) { + type = faces[ offset ++ ]; - // backwards compatibility - if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) { - uvScaleMap = uvScaleMap.texture; + isQuad = isBitSet( type, 0 ); + hasMaterial = isBitSet( type, 1 ); + hasFaceVertexUv = isBitSet( type, 3 ); + hasFaceNormal = isBitSet( type, 4 ); + hasFaceVertexNormal = isBitSet( type, 5 ); + hasFaceColor = isBitSet( type, 6 ); + hasFaceVertexColor = isBitSet( type, 7 ); - } + // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); - var offset = uvScaleMap.offset; - var repeat = uvScaleMap.repeat; + if ( isQuad ) { - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + faceA = new Face3(); + faceA.a = faces[ offset ]; + faceA.b = faces[ offset + 1 ]; + faceA.c = faces[ offset + 3 ]; - } + faceB = new Face3(); + faceB.a = faces[ offset + 1 ]; + faceB.b = faces[ offset + 2 ]; + faceB.c = faces[ offset + 3 ]; - uniforms.envMap.value = material.envMap; + offset += 4; - // don't flip CubeTexture envMaps, flip everything else: - // WebGLRenderTargetCube will be flipped for backwards compatibility - // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture - // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future - uniforms.flipEnvMap.value = ( ! ( material.envMap instanceof THREE.CubeTexture ) ) ? 1 : - 1; + if ( hasMaterial ) { - uniforms.reflectivity.value = material.reflectivity; - uniforms.refractionRatio.value = material.refractionRatio; + materialIndex = faces[ offset ++ ]; + faceA.materialIndex = materialIndex; + faceB.materialIndex = materialIndex; - } + } - function refreshUniformsLine ( uniforms, material ) { + // to get face <=> uv index correspondence - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; + fi = geometry.faces.length; - } + if ( hasFaceVertexUv ) { - function refreshUniformsDash ( uniforms, material ) { + for ( i = 0; i < nUvLayers; i ++ ) { - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; + uvLayer = json.uvs[ i ]; - } + geometry.faceVertexUvs[ i ][ fi ] = []; + geometry.faceVertexUvs[ i ][ fi + 1 ] = []; - function refreshUniformsPoints ( uniforms, material ) { + for ( j = 0; j < 4; j ++ ) { - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size * _pixelRatio; - uniforms.scale.value = _canvas.clientHeight * 0.5; + uvIndex = faces[ offset ++ ]; - uniforms.map.value = material.map; + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - if ( material.map !== null ) { + uv = new Vector2( u, v ); - var offset = material.map.offset; - var repeat = material.map.repeat; + if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); + if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + } - } + } - } + } - function refreshUniformsFog ( uniforms, fog ) { + if ( hasFaceNormal ) { - uniforms.fogColor.value = fog.color; + normalIndex = faces[ offset ++ ] * 3; - if ( fog instanceof THREE.Fog ) { + faceA.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; + faceB.normal.copy( faceA.normal ); - } else if ( fog instanceof THREE.FogExp2 ) { + } - uniforms.fogDensity.value = fog.density; + if ( hasFaceVertexNormal ) { - } + for ( i = 0; i < 4; i ++ ) { - } + normalIndex = faces[ offset ++ ] * 3; - function refreshUniformsLambert ( uniforms, material ) { + normal = new Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - if ( material.lightMap ) { - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + if ( i !== 2 ) faceA.vertexNormals.push( normal ); + if ( i !== 0 ) faceB.vertexNormals.push( normal ); - } + } - if ( material.emissiveMap ) { + } - uniforms.emissiveMap.value = material.emissiveMap; - } + if ( hasFaceColor ) { - } + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - function refreshUniformsPhong ( uniforms, material ) { + faceA.color.setHex( hex ); + faceB.color.setHex( hex ); - uniforms.specular.value = material.specular; - uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + } - if ( material.lightMap ) { - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + if ( hasFaceVertexColor ) { - } + for ( i = 0; i < 4; i ++ ) { - if ( material.emissiveMap ) { + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - uniforms.emissiveMap.value = material.emissiveMap; + if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) ); + if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) ); - } + } - if ( material.bumpMap ) { + } - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + geometry.faces.push( faceA ); + geometry.faces.push( faceB ); - } + } else { - if ( material.normalMap ) { + face = new Face3(); + face.a = faces[ offset ++ ]; + face.b = faces[ offset ++ ]; + face.c = faces[ offset ++ ]; - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); + if ( hasMaterial ) { - } + materialIndex = faces[ offset ++ ]; + face.materialIndex = materialIndex; - if ( material.displacementMap ) { + } - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + // to get face <=> uv index correspondence - } + fi = geometry.faces.length; - } + if ( hasFaceVertexUv ) { - function refreshUniformsStandard ( uniforms, material ) { + for ( i = 0; i < nUvLayers; i ++ ) { - uniforms.roughness.value = material.roughness; - uniforms.metalness.value = material.metalness; + uvLayer = json.uvs[ i ]; - if ( material.roughnessMap ) { + geometry.faceVertexUvs[ i ][ fi ] = []; - uniforms.roughnessMap.value = material.roughnessMap; + for ( j = 0; j < 3; j ++ ) { - } + uvIndex = faces[ offset ++ ]; - if ( material.metalnessMap ) { + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - uniforms.metalnessMap.value = material.metalnessMap; + uv = new Vector2( u, v ); - } + geometry.faceVertexUvs[ i ][ fi ].push( uv ); - if ( material.lightMap ) { + } - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + } - } + } - if ( material.emissiveMap ) { + if ( hasFaceNormal ) { - uniforms.emissiveMap.value = material.emissiveMap; + normalIndex = faces[ offset ++ ] * 3; - } + face.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - if ( material.bumpMap ) { + } - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + if ( hasFaceVertexNormal ) { - } + for ( i = 0; i < 3; i ++ ) { - if ( material.normalMap ) { + normalIndex = faces[ offset ++ ] * 3; - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); + normal = new Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - } + face.vertexNormals.push( normal ); - if ( material.displacementMap ) { + } - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + } - } - if ( material.envMap ) { + if ( hasFaceColor ) { - //uniforms.envMap.value = material.envMap; // part of uniforms common - uniforms.envMapIntensity.value = material.envMapIntensity; + colorIndex = faces[ offset ++ ]; + face.color.setHex( colors[ colorIndex ] ); - } + } - } - function refreshUniformsPhysical ( uniforms, material ) { + if ( hasFaceVertexColor ) { - uniforms.clearCoat.value = material.clearCoat; - uniforms.clearCoatRoughness.value = material.clearCoatRoughness; + for ( i = 0; i < 3; i ++ ) { - refreshUniformsStandard( uniforms, material ); + colorIndex = faces[ offset ++ ]; + face.vertexColors.push( new Color( colors[ colorIndex ] ) ); - } + } - // If uniforms are marked as clean, they don't need to be loaded to the GPU. + } - function markUniformsLightsNeedsUpdate ( uniforms, value ) { + geometry.faces.push( face ); - uniforms.ambientLightColor.needsUpdate = value; + } - uniforms.directionalLights.needsUpdate = value; - uniforms.pointLights.needsUpdate = value; - uniforms.spotLights.needsUpdate = value; - uniforms.hemisphereLights.needsUpdate = value; + } - } + } - // Lighting + function parseSkin() { - function setupShadows ( lights ) { + var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; - var lightShadowsLength = 0; + if ( json.skinWeights ) { - for ( var i = 0, l = lights.length; i < l; i ++ ) { + for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { - var light = lights[ i ]; + var x = json.skinWeights[ i ]; + var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; + var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; + var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; - if ( light.castShadow ) { + geometry.skinWeights.push( new Vector4( x, y, z, w ) ); - _lights.shadows[ lightShadowsLength ++ ] = light; + } - } + } - } + if ( json.skinIndices ) { - _lights.shadows.length = lightShadowsLength; + for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { - } + var a = json.skinIndices[ i ]; + var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; + var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; + var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; - function setupLights ( lights, camera ) { + geometry.skinIndices.push( new Vector4( a, b, c, d ) ); - var l, ll, light, - r = 0, g = 0, b = 0, - color, - intensity, - distance, - shadowMap, + } - viewMatrix = camera.matrixWorldInverse, + } - directionalLength = 0, - pointLength = 0, - spotLength = 0, - hemiLength = 0; + geometry.bones = json.bones; - for ( l = 0, ll = lights.length; l < ll; l ++ ) { + if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { - light = lights[ l ]; + console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + + geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); - color = light.color; - intensity = light.intensity; - distance = light.distance; + } - shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + } - if ( light instanceof THREE.AmbientLight ) { + function parseMorphing( scale ) { - r += color.r * intensity; - g += color.g * intensity; - b += color.b * intensity; + if ( json.morphTargets !== undefined ) { - } else if ( light instanceof THREE.DirectionalLight ) { + for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) { - var uniforms = lightCache.get( light ); + geometry.morphTargets[ i ] = {}; + geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; + geometry.morphTargets[ i ].vertices = []; - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - uniforms.direction.sub( _vector3 ); - uniforms.direction.transformDirection( viewMatrix ); + var dstVertices = geometry.morphTargets[ i ].vertices; + var srcVertices = json.morphTargets[ i ].vertices; - uniforms.shadow = light.castShadow; + for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) { - if ( light.castShadow ) { + var vertex = new Vector3(); + vertex.x = srcVertices[ v ] * scale; + vertex.y = srcVertices[ v + 1 ] * scale; + vertex.z = srcVertices[ v + 2 ] * scale; - uniforms.shadowBias = light.shadow.bias; - uniforms.shadowRadius = light.shadow.radius; - uniforms.shadowMapSize = light.shadow.mapSize; + dstVertices.push( vertex ); - } + } - _lights.directionalShadowMap[ directionalLength ] = shadowMap; - _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; - _lights.directional[ directionalLength ++ ] = uniforms; + } - } else if ( light instanceof THREE.SpotLight ) { + } - var uniforms = lightCache.get( light ); + if ( json.morphColors !== undefined && json.morphColors.length > 0 ) { - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' ); - uniforms.color.copy( color ).multiplyScalar( intensity ); - uniforms.distance = distance; + var faces = geometry.faces; + var morphColors = json.morphColors[ 0 ].colors; - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - uniforms.direction.sub( _vector3 ); - uniforms.direction.transformDirection( viewMatrix ); + for ( var i = 0, l = faces.length; i < l; i ++ ) { - uniforms.coneCos = Math.cos( light.angle ); - uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); - uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; + faces[ i ].color.fromArray( morphColors, i * 3 ); - uniforms.shadow = light.castShadow; + } - if ( light.castShadow ) { + } - uniforms.shadowBias = light.shadow.bias; - uniforms.shadowRadius = light.shadow.radius; - uniforms.shadowMapSize = light.shadow.mapSize; + } - } + function parseAnimations() { - _lights.spotShadowMap[ spotLength ] = shadowMap; - _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; - _lights.spot[ spotLength ++ ] = uniforms; + var outputAnimations = []; - } else if ( light instanceof THREE.PointLight ) { + // parse old style Bone/Hierarchy animations + var animations = []; - var uniforms = lightCache.get( light ); + if ( json.animation !== undefined ) { - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + animations.push( json.animation ); - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.distance = light.distance; - uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; + } - uniforms.shadow = light.castShadow; + if ( json.animations !== undefined ) { - if ( light.castShadow ) { + if ( json.animations.length ) { - uniforms.shadowBias = light.shadow.bias; - uniforms.shadowRadius = light.shadow.radius; - uniforms.shadowMapSize = light.shadow.mapSize; + animations = animations.concat( json.animations ); - } + } else { - _lights.pointShadowMap[ pointLength ] = shadowMap; + animations.push( json.animations ); - if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) { + } - _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4(); + } - } + for ( var i = 0; i < animations.length; i ++ ) { - // for point lights we set the shadow matrix to be a translation-only matrix - // equal to inverse of the light's position - _vector3.setFromMatrixPosition( light.matrixWorld ).negate(); - _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 ); + var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones ); + if ( clip ) outputAnimations.push( clip ); - _lights.point[ pointLength ++ ] = uniforms; + } - } else if ( light instanceof THREE.HemisphereLight ) { + // parse implicit morph animations + if ( geometry.morphTargets ) { - var uniforms = lightCache.get( light ); + // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary. + var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); + outputAnimations = outputAnimations.concat( morphAnimationClips ); - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - uniforms.direction.transformDirection( viewMatrix ); - uniforms.direction.normalize(); + } - uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); - uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); + if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations; - _lights.hemi[ hemiLength ++ ] = uniforms; + } - } + if ( json.materials === undefined || json.materials.length === 0 ) { - } + return { geometry: geometry }; - _lights.ambient[ 0 ] = r; - _lights.ambient[ 1 ] = g; - _lights.ambient[ 2 ] = b; + } else { - _lights.directional.length = directionalLength; - _lights.spot.length = spotLength; - _lights.point.length = pointLength; - _lights.hemi.length = hemiLength; + var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); - _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length; + return { geometry: geometry, materials: materials }; - } + } - // GL state setting + } - this.setFaceCulling = function ( cullFace, frontFaceDirection ) { + } ); - state.setCullFace( cullFace ); - state.setFlipSided( frontFaceDirection === THREE.FrontFaceDirectionCW ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - }; + function ObjectLoader ( manager ) { + this.isObjectLoader = true; - // Textures + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + this.texturePath = ''; - function allocTextureUnit() { + }; - var textureUnit = _usedTextureUnits; + Object.assign( ObjectLoader.prototype, { - if ( textureUnit >= capabilities.maxTextures ) { + load: function ( url, onLoad, onProgress, onError ) { - console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); + if ( this.texturePath === '' ) { - } + this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); - _usedTextureUnits += 1; + } - return textureUnit; + var scope = this; - } + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - this.allocTextureUnit = allocTextureUnit; + scope.parse( JSON.parse( text ), onLoad ); - // this.setTexture2D = setTexture2D; - this.setTexture2D = ( function() { + }, onProgress, onError ); - var warned = false; + }, - // backwards compatibility: peel texture.texture - return function setTexture2D( texture, slot ) { + setTexturePath: function ( value ) { - if ( texture instanceof THREE.WebGLRenderTarget ) { + this.texturePath = value; - if ( ! warned ) { + }, - console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); - warned = true; + setCrossOrigin: function ( value ) { - } + this.crossOrigin = value; - texture = texture.texture; + }, - } + parse: function ( json, onLoad ) { - textures.setTexture2D( texture, slot ); + var geometries = this.parseGeometries( json.geometries ); - }; + var images = this.parseImages( json.images, function () { - }() ); + if ( onLoad !== undefined ) onLoad( object ); - this.setTexture = ( function() { + } ); - var warned = false; + var textures = this.parseTextures( json.textures, images ); + var materials = this.parseMaterials( json.materials, textures ); - return function setTexture( texture, slot ) { + var object = this.parseObject( json.object, geometries, materials ); - if ( ! warned ) { + if ( json.animations ) { - console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); - warned = true; + object.animations = this.parseAnimations( json.animations ); - } + } - textures.setTexture2D( texture, slot ); + if ( json.images === undefined || json.images.length === 0 ) { - }; + if ( onLoad !== undefined ) onLoad( object ); - }() ); + } - this.setTextureCube = ( function() { + return object; - var warned = false; + }, - return function setTextureCube( texture, slot ) { + parseGeometries: function ( json ) { - // backwards compatibility: peel texture.texture - if ( texture instanceof THREE.WebGLRenderTargetCube ) { + var geometries = {}; - if ( ! warned ) { + if ( json !== undefined ) { - console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); - warned = true; + var geometryLoader = new JSONLoader(); + var bufferGeometryLoader = new BufferGeometryLoader(); - } + for ( var i = 0, l = json.length; i < l; i ++ ) { - texture = texture.texture; + var geometry; + var data = json[ i ]; - } + switch ( data.type ) { - // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture - // TODO: unify these code paths - if ( texture instanceof THREE.CubeTexture || - ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { + case 'PlaneGeometry': + case 'PlaneBufferGeometry': - // CompressedTexture can have Array in image :/ + geometry = new THREE[ data.type ]( + data.width, + data.height, + data.widthSegments, + data.heightSegments + ); - // this function alone should take care of cube textures - textures.setTextureCube( texture, slot ); + break; - } else { + case 'BoxGeometry': + case 'BoxBufferGeometry': + case 'CubeGeometry': // backwards compatible - // assumed: texture property of THREE.WebGLRenderTargetCube + geometry = new THREE[ data.type ]( + data.width, + data.height, + data.depth, + data.widthSegments, + data.heightSegments, + data.depthSegments + ); - textures.setTextureCubeDynamic( texture, slot ); + break; - } + case 'CircleGeometry': + case 'CircleBufferGeometry': - }; + geometry = new THREE[ data.type ]( + data.radius, + data.segments, + data.thetaStart, + data.thetaLength + ); - }() ); + break; - this.getCurrentRenderTarget = function() { + case 'CylinderGeometry': + case 'CylinderBufferGeometry': - return _currentRenderTarget; + geometry = new THREE[ data.type ]( + data.radiusTop, + data.radiusBottom, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - }; + break; - this.setRenderTarget = function ( renderTarget ) { + case 'ConeGeometry': + case 'ConeBufferGeometry': - _currentRenderTarget = renderTarget; + geometry = new THREE [ data.type ]( + data.radius, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { + break; - textures.setupRenderTarget( renderTarget ); + case 'SphereGeometry': + case 'SphereBufferGeometry': - } + geometry = new THREE[ data.type ]( + data.radius, + data.widthSegments, + data.heightSegments, + data.phiStart, + data.phiLength, + data.thetaStart, + data.thetaLength + ); - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); - var framebuffer; + break; - if ( renderTarget ) { + case 'DodecahedronGeometry': + case 'IcosahedronGeometry': + case 'OctahedronGeometry': + case 'TetrahedronGeometry': - var renderTargetProperties = properties.get( renderTarget ); + geometry = new THREE[ data.type ]( + data.radius, + data.detail + ); - if ( isCube ) { + break; - framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ]; + case 'RingGeometry': + case 'RingBufferGeometry': - } else { + geometry = new THREE[ data.type ]( + data.innerRadius, + data.outerRadius, + data.thetaSegments, + data.phiSegments, + data.thetaStart, + data.thetaLength + ); - framebuffer = renderTargetProperties.__webglFramebuffer; + break; - } + case 'TorusGeometry': + case 'TorusBufferGeometry': - _currentScissor.copy( renderTarget.scissor ); - _currentScissorTest = renderTarget.scissorTest; + geometry = new THREE[ data.type ]( + data.radius, + data.tube, + data.radialSegments, + data.tubularSegments, + data.arc + ); - _currentViewport.copy( renderTarget.viewport ); + break; - } else { + case 'TorusKnotGeometry': + case 'TorusKnotBufferGeometry': - framebuffer = null; + geometry = new THREE[ data.type ]( + data.radius, + data.tube, + data.tubularSegments, + data.radialSegments, + data.p, + data.q + ); - _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); - _currentScissorTest = _scissorTest; + break; - _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); + case 'LatheGeometry': + case 'LatheBufferGeometry': - } + geometry = new THREE[ data.type ]( + data.points, + data.segments, + data.phiStart, + data.phiLength + ); - if ( _currentFramebuffer !== framebuffer ) { + break; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _currentFramebuffer = framebuffer; + case 'BufferGeometry': - } + geometry = bufferGeometryLoader.parse( data ); - state.scissor( _currentScissor ); - state.setScissorTest( _currentScissorTest ); + break; - state.viewport( _currentViewport ); + case 'Geometry': - if ( isCube ) { + geometry = geometryLoader.parse( data.data, this.texturePath ).geometry; - var textureProperties = properties.get( renderTarget.texture ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel ); + break; - } + default: - }; + console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); - this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { + continue; - if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) { + } - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); - return; + geometry.uuid = data.uuid; - } + if ( data.name !== undefined ) geometry.name = data.name; - var framebuffer = properties.get( renderTarget ).__webglFramebuffer; + geometries[ data.uuid ] = geometry; - if ( framebuffer ) { + } - var restore = false; + } - if ( framebuffer !== _currentFramebuffer ) { + return geometries; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + }, - restore = true; + parseMaterials: function ( json, textures ) { - } + var materials = {}; - try { + if ( json !== undefined ) { - var texture = renderTarget.texture; + var loader = new MaterialLoader(); + loader.setTextures( textures ); - if ( texture.format !== THREE.RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + for ( var i = 0, l = json.length; i < l; i ++ ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); - return; + var material = loader.parse( json[ i ] ); + materials[ material.uuid ] = material; - } + } - if ( texture.type !== THREE.UnsignedByteType && - paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && - ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) && - ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { + } - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); - return; + return materials; - } + }, - if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { + parseAnimations: function ( json ) { - // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + var animations = []; - if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + for ( var i = 0; i < json.length; i ++ ) { - _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer ); + var clip = AnimationClip.parse( json[ i ] ); - } + animations.push( clip ); - } else { + } - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); + return animations; - } + }, - } finally { + parseImages: function ( json, onLoad ) { - if ( restore ) { + var scope = this; + var images = {}; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); + function loadImage( url ) { - } + scope.manager.itemStart( url ); - } + return loader.load( url, function () { - } + scope.manager.itemEnd( url ); - }; + } ); - // Map three.js constants to WebGL constants + } - function paramThreeToGL ( p ) { + if ( json !== undefined && json.length > 0 ) { - var extension; + var manager = new LoadingManager( onLoad ); - if ( p === THREE.RepeatWrapping ) return _gl.REPEAT; - if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; - if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; + var loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); - if ( p === THREE.NearestFilter ) return _gl.NEAREST; - if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; - if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; + for ( var i = 0, l = json.length; i < l; i ++ ) { - if ( p === THREE.LinearFilter ) return _gl.LINEAR; - if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; - if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; + var image = json[ i ]; + var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; - if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; - if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; - if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; - if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; + images[ image.uuid ] = loadImage( path ); - if ( p === THREE.ByteType ) return _gl.BYTE; - if ( p === THREE.ShortType ) return _gl.SHORT; - if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; - if ( p === THREE.IntType ) return _gl.INT; - if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; - if ( p === THREE.FloatType ) return _gl.FLOAT; + } - extension = extensions.get( 'OES_texture_half_float' ); + } - if ( extension !== null ) { + return images; - if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES; + }, - } + parseTextures: function ( json, images ) { - if ( p === THREE.AlphaFormat ) return _gl.ALPHA; - if ( p === THREE.RGBFormat ) return _gl.RGB; - if ( p === THREE.RGBAFormat ) return _gl.RGBA; - if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; - if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; - if ( p === THREE.DepthFormat ) return _gl.DEPTH_COMPONENT; + function parseConstant( value ) { - if ( p === THREE.AddEquation ) return _gl.FUNC_ADD; - if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT; - if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; + if ( typeof( value ) === 'number' ) return value; - if ( p === THREE.ZeroFactor ) return _gl.ZERO; - if ( p === THREE.OneFactor ) return _gl.ONE; - if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR; - if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; - if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA; - if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; - if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA; - if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; + console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); - if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR; - if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; - if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; + return THREE[ value ]; - extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + } - if ( extension !== null ) { + var textures = {}; - if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; - if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; - if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; - if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + if ( json !== undefined ) { - } + for ( var i = 0, l = json.length; i < l; i ++ ) { - extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + var data = json[ i ]; - if ( extension !== null ) { + if ( data.image === undefined ) { - if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); - } + } - extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + if ( images[ data.image ] === undefined ) { - if ( extension !== null ) { + console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); - if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; + } - } + var texture = new Texture( images[ data.image ] ); + texture.needsUpdate = true; - extension = extensions.get( 'EXT_blend_minmax' ); + texture.uuid = data.uuid; - if ( extension !== null ) { + if ( data.name !== undefined ) texture.name = data.name; - if ( p === THREE.MinEquation ) return extension.MIN_EXT; - if ( p === THREE.MaxEquation ) return extension.MAX_EXT; + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping ); - } + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.wrap !== undefined ) { - return 0; + texture.wrapS = parseConstant( data.wrap[ 0 ] ); + texture.wrapT = parseConstant( data.wrap[ 1 ] ); - } + } -}; + if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter ); + if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter ); + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; -// File:src/renderers/WebGLRenderTarget.js + if ( data.flipY !== undefined ) texture.flipY = data.flipY; -/** - * @author szimek / https://github.com/szimek/ - * @author alteredq / http://alteredqualia.com/ - * @author Marius Kintel / https://github.com/kintel - */ + textures[ data.uuid ] = texture; -/* - In options, we can specify: - * Texture parameters for an auto-generated target texture - * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers -*/ -THREE.WebGLRenderTarget = function ( width, height, options ) { + } - this.uuid = THREE.Math.generateUUID(); + } - this.width = width; - this.height = height; + return textures; - this.scissor = new THREE.Vector4( 0, 0, width, height ); - this.scissorTest = false; + }, - this.viewport = new THREE.Vector4( 0, 0, width, height ); + parseObject: function () { - options = options || {}; + var matrix = new Matrix4(); - if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter; + return function parseObject( data, geometries, materials ) { - this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + var object; - this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; - this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; - this.depthTexture = null; + function getGeometry( name ) { -}; + if ( geometries[ name ] === undefined ) { -Object.assign( THREE.WebGLRenderTarget.prototype, THREE.EventDispatcher.prototype, { + console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); - setSize: function ( width, height ) { + } - if ( this.width !== width || this.height !== height ) { + return geometries[ name ]; - this.width = width; - this.height = height; + } - this.dispose(); + function getMaterial( name ) { - } + if ( name === undefined ) return undefined; - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); + if ( materials[ name ] === undefined ) { - }, + console.warn( 'THREE.ObjectLoader: Undefined material', name ); - clone: function () { + } - return new this.constructor().copy( this ); + return materials[ name ]; - }, + } - copy: function ( source ) { + switch ( data.type ) { - this.width = source.width; - this.height = source.height; + case 'Scene': - this.viewport.copy( source.viewport ); + object = new Scene(); - this.texture = source.texture.clone(); + break; - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - this.depthTexture = source.depthTexture; + case 'PerspectiveCamera': - return this; + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - }, + if ( data.focus !== undefined ) object.focus = data.focus; + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge; + if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - dispose: function () { + break; - this.dispatchEvent( { type: 'dispose' } ); + case 'OrthographicCamera': - } + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); -} ); + break; -// File:src/renderers/WebGLRenderTargetCube.js + case 'AmbientLight': -/** - * @author alteredq / http://alteredqualia.com - */ + object = new AmbientLight( data.color, data.intensity ); -THREE.WebGLRenderTargetCube = function ( width, height, options ) { + break; - THREE.WebGLRenderTarget.call( this, width, height, options ); + case 'DirectionalLight': - this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 - this.activeMipMapLevel = 0; + object = new DirectionalLight( data.color, data.intensity ); -}; + break; -THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype ); -THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube; + case 'PointLight': -// File:src/renderers/webgl/WebGLBufferRenderer.js + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); -/** -* @author mrdoob / http://mrdoob.com/ -*/ + break; -THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) { + case 'SpotLight': - var mode; + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); - function setMode( value ) { + break; - mode = value; + case 'HemisphereLight': - } + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); - function render( start, count ) { + break; - _gl.drawArrays( mode, start, count ); + case 'Mesh': - _infoRender.calls ++; - _infoRender.vertices += count; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; + var geometry = getGeometry( data.geometry ); + var material = getMaterial( data.material ); - } + if ( geometry.bones && geometry.bones.length > 0 ) { - function renderInstances( geometry ) { + object = new SkinnedMesh( geometry, material ); - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + } else { - if ( extension === null ) { + object = new Mesh( geometry, material ); - console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + } - } + break; - var position = geometry.attributes.position; + case 'LOD': - var count = 0; + object = new LOD(); - if ( position instanceof THREE.InterleavedBufferAttribute ) { + break; - count = position.data.count; + case 'Line': - extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); - } else { + break; - count = position.count; + case 'PointCloud': + case 'Points': - extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); - } + break; - _infoRender.calls ++; - _infoRender.vertices += count * geometry.maxInstancedCount; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; + case 'Sprite': - } + object = new Sprite( getMaterial( data.material ) ); - this.setMode = setMode; - this.render = render; - this.renderInstances = renderInstances; + break; -}; + case 'Group': -// File:src/renderers/webgl/WebGLClipping.js + object = new Group(); -THREE.WebGLClipping = function() { + break; - var scope = this, + default: - globalState = null, - numGlobalPlanes = 0, - localClippingEnabled = false, - renderingShadows = false, + object = new Object3D(); - plane = new THREE.Plane(), - viewNormalMatrix = new THREE.Matrix3(), + } - uniform = { value: null, needsUpdate: false }; + object.uuid = data.uuid; - this.uniform = uniform; - this.numPlanes = 0; + if ( data.name !== undefined ) object.name = data.name; + if ( data.matrix !== undefined ) { - this.init = function( planes, enableLocalClipping, camera ) { + matrix.fromArray( data.matrix ); + matrix.decompose( object.position, object.quaternion, object.scale ); - var enabled = - planes.length !== 0 || - enableLocalClipping || - // enable state of previous frame - the clipping code has to - // run another frame in order to reset the state: - numGlobalPlanes !== 0 || - localClippingEnabled; + } else { - localClippingEnabled = enableLocalClipping; + if ( data.position !== undefined ) object.position.fromArray( data.position ); + if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); + if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); - globalState = projectPlanes( planes, camera, 0 ); - numGlobalPlanes = planes.length; + } - return enabled; + if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; + if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; - }; + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.userData !== undefined ) object.userData = data.userData; - this.beginShadows = function() { + if ( data.children !== undefined ) { - renderingShadows = true; - projectPlanes( null ); + for ( var child in data.children ) { - }; + object.add( this.parseObject( data.children[ child ], geometries, materials ) ); - this.endShadows = function() { + } - renderingShadows = false; - resetGlobalState(); + } - }; + if ( data.type === 'LOD' ) { - this.setState = function( planes, clipShadows, camera, cache, fromCache ) { + var levels = data.levels; - if ( ! localClippingEnabled || - planes === null || planes.length === 0 || - renderingShadows && ! clipShadows ) { - // there's no local clipping + for ( var l = 0; l < levels.length; l ++ ) { - if ( renderingShadows ) { - // there's no global clipping + var level = levels[ l ]; + var child = object.getObjectByProperty( 'uuid', level.object ); - projectPlanes( null ); + if ( child !== undefined ) { - } else { + object.addLevel( child, level.distance ); - resetGlobalState(); - } + } - } else { + } - var nGlobal = renderingShadows ? 0 : numGlobalPlanes, - lGlobal = nGlobal * 4, + } - dstArray = cache.clippingState || null; + return object; - uniform.value = dstArray; // ensure unique state + }; - dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); + }() - for ( var i = 0; i !== lGlobal; ++ i ) { + } ); - dstArray[ i ] = globalState[ i ]; + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - } + exports.ShapeUtils = { - cache.clippingState = dstArray; - this.numPlanes += nGlobal; + // calculate area of the contour polygon - } + area: function ( contour ) { + var n = contour.length; + var a = 0.0; - }; + for ( var p = n - 1, q = 0; q < n; p = q ++ ) { - function resetGlobalState() { + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - if ( uniform.value !== globalState ) { + } - uniform.value = globalState; - uniform.needsUpdate = numGlobalPlanes > 0; + return a * 0.5; - } + }, - scope.numPlanes = numGlobalPlanes; + triangulate: ( function () { - } + /** + * This code is a quick port of code written in C++ which was submitted to + * flipcode.com by John W. Ratcliff // July 22, 2000 + * See original code and more information here: + * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml + * + * ported to actionscript by Zevan Rosser + * www.actionsnippet.com + * + * ported to javascript by Joshua Koo + * http://www.lab4games.net/zz85/blog + * + */ - function projectPlanes( planes, camera, dstOffset, skipTransform ) { + function snip( contour, u, v, w, n, verts ) { - var nPlanes = planes !== null ? planes.length : 0, - dstArray = null; + var p; + var ax, ay, bx, by; + var cx, cy, px, py; - if ( nPlanes !== 0 ) { + ax = contour[ verts[ u ] ].x; + ay = contour[ verts[ u ] ].y; - dstArray = uniform.value; + bx = contour[ verts[ v ] ].x; + by = contour[ verts[ v ] ].y; - if ( skipTransform !== true || dstArray === null ) { + cx = contour[ verts[ w ] ].x; + cy = contour[ verts[ w ] ].y; - var flatSize = dstOffset + nPlanes * 4, - viewMatrix = camera.matrixWorldInverse; + if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false; - viewNormalMatrix.getNormalMatrix( viewMatrix ); + var aX, aY, bX, bY, cX, cY; + var apx, apy, bpx, bpy, cpx, cpy; + var cCROSSap, bCROSScp, aCROSSbp; - if ( dstArray === null || dstArray.length < flatSize ) { + aX = cx - bx; aY = cy - by; + bX = ax - cx; bY = ay - cy; + cX = bx - ax; cY = by - ay; - dstArray = new Float32Array( flatSize ); + for ( p = 0; p < n; p ++ ) { - } + px = contour[ verts[ p ] ].x; + py = contour[ verts[ p ] ].y; - for ( var i = 0, i4 = dstOffset; - i !== nPlanes; ++ i, i4 += 4 ) { + if ( ( ( px === ax ) && ( py === ay ) ) || + ( ( px === bx ) && ( py === by ) ) || + ( ( px === cx ) && ( py === cy ) ) ) continue; - plane.copy( planes[ i ] ). - applyMatrix4( viewMatrix, viewNormalMatrix ); + apx = px - ax; apy = py - ay; + bpx = px - bx; bpy = py - by; + cpx = px - cx; cpy = py - cy; - plane.normal.toArray( dstArray, i4 ); - dstArray[ i4 + 3 ] = plane.constant; + // see if p is inside triangle abc - } + aCROSSbp = aX * bpy - aY * bpx; + cCROSSap = cX * apy - cY * apx; + bCROSScp = bX * cpy - bY * cpx; - } + if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false; - uniform.value = dstArray; - uniform.needsUpdate = true; + } - } + return true; - scope.numPlanes = nPlanes; - return dstArray; + } - } + // takes in an contour array and returns -}; + return function triangulate( contour, indices ) { + var n = contour.length; -// File:src/renderers/webgl/WebGLIndexedBufferRenderer.js + if ( n < 3 ) return null; -/** -* @author mrdoob / http://mrdoob.com/ -*/ + var result = [], + verts = [], + vertIndices = []; -THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) { + /* we want a counter-clockwise polygon in verts */ - var mode; + var u, v, w; - function setMode( value ) { + if ( exports.ShapeUtils.area( contour ) > 0.0 ) { - mode = value; + for ( v = 0; v < n; v ++ ) verts[ v ] = v; - } + } else { - var type, size; + for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; - function setIndex( index ) { + } - if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { + var nv = n; - type = _gl.UNSIGNED_INT; - size = 4; + /* remove nv - 2 vertices, creating 1 triangle every time */ - } else { + var count = 2 * nv; /* error detection */ - type = _gl.UNSIGNED_SHORT; - size = 2; + for ( v = nv - 1; nv > 2; ) { - } + /* if we loop, it is probably a non-simple polygon */ - } + if ( ( count -- ) <= 0 ) { - function render( start, count ) { + //** Triangulate: ERROR - probable bad polygon! - _gl.drawElements( mode, count, type, start * size ); + //throw ( "Warning, unable to triangulate polygon!" ); + //return null; + // Sometimes warning is fine, especially polygons are triangulated in reverse. + console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' ); - _infoRender.calls ++; - _infoRender.vertices += count; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; + if ( indices ) return vertIndices; + return result; - } + } - function renderInstances( geometry, start, count ) { + /* three consecutive vertices in current polygon, */ - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + u = v; if ( nv <= u ) u = 0; /* previous */ + v = u + 1; if ( nv <= v ) v = 0; /* new v */ + w = v + 1; if ( nv <= w ) w = 0; /* next */ - if ( extension === null ) { + if ( snip( contour, u, v, w, nv, verts ) ) { - console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + var a, b, c, s, t; - } + /* true names of the vertices */ - extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount ); + a = verts[ u ]; + b = verts[ v ]; + c = verts[ w ]; - _infoRender.calls ++; - _infoRender.vertices += count * geometry.maxInstancedCount; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; - } + /* output Triangle */ - this.setMode = setMode; - this.setIndex = setIndex; - this.render = render; - this.renderInstances = renderInstances; + result.push( [ contour[ a ], + contour[ b ], + contour[ c ] ] ); -}; -// File:src/renderers/webgl/WebGLExtensions.js + vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); -/** -* @author mrdoob / http://mrdoob.com/ -*/ + /* remove v from the remaining polygon */ -THREE.WebGLExtensions = function ( gl ) { + for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { - var extensions = {}; + verts[ s ] = verts[ t ]; - this.get = function ( name ) { + } - if ( extensions[ name ] !== undefined ) { + nv --; - return extensions[ name ]; + /* reset error detection counter */ - } + count = 2 * nv; - var extension; + } - switch ( name ) { + } - case 'WEBGL_depth_texture': - extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); - break; + if ( indices ) return vertIndices; + return result; - case 'EXT_texture_filter_anisotropic': - extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); - break; + } - case 'WEBGL_compressed_texture_s3tc': - extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); - break; + } )(), - case 'WEBGL_compressed_texture_pvrtc': - extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); - break; + triangulateShape: function ( contour, holes ) { - case 'WEBGL_compressed_texture_etc1': - extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); - break; + function removeDupEndPts(points) { - default: - extension = gl.getExtension( name ); + var l = points.length; - } + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { - if ( extension === null ) { + points.pop(); - console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + } - } + } - extensions[ name ] = extension; + removeDupEndPts( contour ); + holes.forEach( removeDupEndPts ); - return extension; + function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { - }; + // inOtherPt needs to be collinear to the inSegment + if ( inSegPt1.x !== inSegPt2.x ) { -}; + if ( inSegPt1.x < inSegPt2.x ) { -// File:src/renderers/webgl/WebGLCapabilities.js + return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); -THREE.WebGLCapabilities = function ( gl, extensions, parameters ) { + } else { - var maxAnisotropy; + return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); - function getMaxAnisotropy() { + } - if ( maxAnisotropy !== undefined ) return maxAnisotropy; + } else { - var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + if ( inSegPt1.y < inSegPt2.y ) { - if ( extension !== null ) { + return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); - maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + } else { - } else { + return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); - maxAnisotropy = 0; + } - } + } - return maxAnisotropy; + } - } + function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { - function getMaxPrecision( precision ) { + var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; + var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; - if ( precision === 'highp' ) { + var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; + var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; - if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && - gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { + var limit = seg1dy * seg2dx - seg1dx * seg2dy; + var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; - return 'highp'; + if ( Math.abs( limit ) > Number.EPSILON ) { - } + // not parallel - precision = 'mediump'; + var perpSeg2; + if ( limit > 0 ) { - } + if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; - if ( precision === 'mediump' ) { + } else { - if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && - gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { + if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; - return 'mediump'; + } - } + // i.e. to reduce rounding errors + // intersection at endpoint of segment#1? + if ( perpSeg2 === 0 ) { - } + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; + return [ inSeg1Pt1 ]; - return 'lowp'; + } + if ( perpSeg2 === limit ) { - } + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; + return [ inSeg1Pt2 ]; - this.getMaxAnisotropy = getMaxAnisotropy; - this.getMaxPrecision = getMaxPrecision; + } + // intersection at endpoint of segment#2? + if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ]; + if ( perpSeg1 === limit ) return [ inSeg2Pt2 ]; - this.precision = parameters.precision !== undefined ? parameters.precision : 'highp'; - this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false; + // return real intersection point + var factorSeg1 = perpSeg2 / limit; + return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, + y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; - this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); - this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); - this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); - this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + } else { - this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); - this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); - this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); - this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); + // parallel or collinear + if ( ( perpSeg1 !== 0 ) || + ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return []; - this.vertexTextures = this.maxVertexTextures > 0; - this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); - this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures; + // they are collinear or degenerate + var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point? + var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point? + // both segments are points + if ( seg1Pt && seg2Pt ) { - var _maxPrecision = getMaxPrecision( this.precision ); + if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) || + ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points + return [ inSeg1Pt1 ]; // they are the same point - if ( _maxPrecision !== this.precision ) { + } + // segment#1 is a single point + if ( seg1Pt ) { - console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' ); - this.precision = _maxPrecision; + if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 + return [ inSeg1Pt1 ]; - } + } + // segment#2 is a single point + if ( seg2Pt ) { - if ( this.logarithmicDepthBuffer ) { + if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 + return [ inSeg2Pt1 ]; - this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' ); + } - } + // they are collinear segments, which might overlap + var seg1min, seg1max, seg1minVal, seg1maxVal; + var seg2min, seg2max, seg2minVal, seg2maxVal; + if ( seg1dx !== 0 ) { -}; + // the segments are NOT on a vertical line + if ( inSeg1Pt1.x < inSeg1Pt2.x ) { -// File:src/renderers/webgl/WebGLGeometries.js + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; -/** -* @author mrdoob / http://mrdoob.com/ -*/ + } else { -THREE.WebGLGeometries = function ( gl, properties, info ) { + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; - var geometries = {}; + } + if ( inSeg2Pt1.x < inSeg2Pt2.x ) { - function get( object ) { + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; - var geometry = object.geometry; + } else { - if ( geometries[ geometry.id ] !== undefined ) { + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; - return geometries[ geometry.id ]; + } - } + } else { - geometry.addEventListener( 'dispose', onGeometryDispose ); + // the segments are on a vertical line + if ( inSeg1Pt1.y < inSeg1Pt2.y ) { - var buffergeometry; + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; - if ( geometry instanceof THREE.BufferGeometry ) { + } else { - buffergeometry = geometry; + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; - } else if ( geometry instanceof THREE.Geometry ) { + } + if ( inSeg2Pt1.y < inSeg2Pt2.y ) { - if ( geometry._bufferGeometry === undefined ) { + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; - geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object ); + } else { - } + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; - buffergeometry = geometry._bufferGeometry; + } - } + } + if ( seg1minVal <= seg2minVal ) { - geometries[ geometry.id ] = buffergeometry; + if ( seg1maxVal < seg2minVal ) return []; + if ( seg1maxVal === seg2minVal ) { - info.memory.geometries ++; + if ( inExcludeAdjacentSegs ) return []; + return [ seg2min ]; - return buffergeometry; + } + if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; + return [ seg2min, seg2max ]; - } + } else { - function onGeometryDispose( event ) { + if ( seg1minVal > seg2maxVal ) return []; + if ( seg1minVal === seg2maxVal ) { - var geometry = event.target; - var buffergeometry = geometries[ geometry.id ]; + if ( inExcludeAdjacentSegs ) return []; + return [ seg1min ]; - if ( buffergeometry.index !== null ) { + } + if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; + return [ seg1min, seg2max ]; - deleteAttribute( buffergeometry.index ); + } - } + } - deleteAttributes( buffergeometry.attributes ); + } - geometry.removeEventListener( 'dispose', onGeometryDispose ); + function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { - delete geometries[ geometry.id ]; + // The order of legs is important - // TODO + // translation of all points, so that Vertex is at (0,0) + var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y; + var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y; + var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y; - var property = properties.get( geometry ); + // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. + var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; + var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; - if ( property.wireframe ) { + if ( Math.abs( from2toAngle ) > Number.EPSILON ) { - deleteAttribute( property.wireframe ); + // angle != 180 deg. - } + var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; + // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); - properties.delete( geometry ); + if ( from2toAngle > 0 ) { - var bufferproperty = properties.get( buffergeometry ); + // main angle < 180 deg. + return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); - if ( bufferproperty.wireframe ) { + } else { - deleteAttribute( bufferproperty.wireframe ); + // main angle > 180 deg. + return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); - } + } - properties.delete( buffergeometry ); + } else { - // + // angle == 180 deg. + // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); + return ( from2otherAngle > 0 ); - info.memory.geometries --; + } - } + } - function getAttributeBuffer( attribute ) { - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + function removeHoles( contour, holes ) { - return properties.get( attribute.data ).__webglBuffer; + var shape = contour.concat(); // work on this shape + var hole; - } + function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { - return properties.get( attribute ).__webglBuffer; + // Check if hole point lies within angle around shape point + var lastShapeIdx = shape.length - 1; - } + var prevShapeIdx = inShapeIdx - 1; + if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; - function deleteAttribute( attribute ) { + var nextShapeIdx = inShapeIdx + 1; + if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; - var buffer = getAttributeBuffer( attribute ); + var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] ); + if ( ! insideAngle ) { - if ( buffer !== undefined ) { + // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); + return false; - gl.deleteBuffer( buffer ); - removeAttributeBuffer( attribute ); + } - } + // Check if shape point lies within angle around hole point + var lastHoleIdx = hole.length - 1; - } + var prevHoleIdx = inHoleIdx - 1; + if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; - function deleteAttributes( attributes ) { + var nextHoleIdx = inHoleIdx + 1; + if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; - for ( var name in attributes ) { + insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] ); + if ( ! insideAngle ) { - deleteAttribute( attributes[ name ] ); + // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); + return false; - } + } - } + return true; - function removeAttributeBuffer( attribute ) { + } - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + function intersectsShapeEdge( inShapePt, inHolePt ) { - properties.delete( attribute.data ); + // checks for intersections with shape edges + var sIdx, nextIdx, intersection; + for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) { - } else { + nextIdx = sIdx + 1; nextIdx %= shape.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true ); + if ( intersection.length > 0 ) return true; - properties.delete( attribute ); + } - } + return false; - } + } - this.get = get; + var indepHoles = []; -}; + function intersectsHoleEdge( inShapePt, inHolePt ) { -// File:src/renderers/webgl/WebGLLights.js + // checks for intersections with hole edges + var ihIdx, chkHole, + hIdx, nextIdx, intersection; + for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { -/** -* @author mrdoob / http://mrdoob.com/ -*/ + chkHole = holes[ indepHoles[ ihIdx ]]; + for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { -THREE.WebGLLights = function () { + nextIdx = hIdx + 1; nextIdx %= chkHole.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true ); + if ( intersection.length > 0 ) return true; - var lights = {}; + } - this.get = function ( light ) { + } + return false; - if ( lights[ light.id ] !== undefined ) { + } - return lights[ light.id ]; + var holeIndex, shapeIndex, + shapePt, holePt, + holeIdx, cutKey, failedCuts = [], + tmpShape1, tmpShape2, + tmpHole1, tmpHole2; - } + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - var uniforms; - - switch ( light.type ) { - - case 'DirectionalLight': - uniforms = { - direction: new THREE.Vector3(), - color: new THREE.Color(), - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new THREE.Vector2() - }; - break; - - case 'SpotLight': - uniforms = { - position: new THREE.Vector3(), - direction: new THREE.Vector3(), - color: new THREE.Color(), - distance: 0, - coneCos: 0, - penumbraCos: 0, - decay: 0, - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new THREE.Vector2() - }; - break; - - case 'PointLight': - uniforms = { - position: new THREE.Vector3(), - color: new THREE.Color(), - distance: 0, - decay: 0, - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new THREE.Vector2() - }; - break; - - case 'HemisphereLight': - uniforms = { - direction: new THREE.Vector3(), - skyColor: new THREE.Color(), - groundColor: new THREE.Color() - }; - break; + indepHoles.push( h ); - } + } - lights[ light.id ] = uniforms; + var minShapeIndex = 0; + var counter = indepHoles.length * 2; + while ( indepHoles.length > 0 ) { - return uniforms; + counter --; + if ( counter < 0 ) { - }; + console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); + break; -}; + } -// File:src/renderers/webgl/WebGLObjects.js + // search for shape-vertex and hole-vertex, + // which can be connected without intersections + for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) { -/** -* @author mrdoob / http://mrdoob.com/ -*/ + shapePt = shape[ shapeIndex ]; + holeIndex = - 1; -THREE.WebGLObjects = function ( gl, properties, info ) { + // search for hole which can be reached without intersections + for ( var h = 0; h < indepHoles.length; h ++ ) { - var geometries = new THREE.WebGLGeometries( gl, properties, info ); + holeIdx = indepHoles[ h ]; - // + // prevent multiple checks + cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; + if ( failedCuts[ cutKey ] !== undefined ) continue; - function update( object ) { + hole = holes[ holeIdx ]; + for ( var h2 = 0; h2 < hole.length; h2 ++ ) { - // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter. + holePt = hole[ h2 ]; + if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; + if ( intersectsShapeEdge( shapePt, holePt ) ) continue; + if ( intersectsHoleEdge( shapePt, holePt ) ) continue; - var geometry = geometries.get( object ); + holeIndex = h2; + indepHoles.splice( h, 1 ); - if ( object.geometry instanceof THREE.Geometry ) { + tmpShape1 = shape.slice( 0, shapeIndex + 1 ); + tmpShape2 = shape.slice( shapeIndex ); + tmpHole1 = hole.slice( holeIndex ); + tmpHole2 = hole.slice( 0, holeIndex + 1 ); - geometry.updateFromObject( object ); + shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); - } + minShapeIndex = shapeIndex; - var index = geometry.index; - var attributes = geometry.attributes; + // Debug only, to show the selected cuts + // glob_CutLines.push( [ shapePt, holePt ] ); - if ( index !== null ) { + break; - updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER ); + } + if ( holeIndex >= 0 ) break; // hole-vertex found - } + failedCuts[ cutKey ] = true; // remember failure - for ( var name in attributes ) { + } + if ( holeIndex >= 0 ) break; // hole-vertex found - updateAttribute( attributes[ name ], gl.ARRAY_BUFFER ); + } - } + } - // morph targets + return shape; /* shape with no holes */ - var morphAttributes = geometry.morphAttributes; + } - for ( var name in morphAttributes ) { - var array = morphAttributes[ name ]; + var i, il, f, face, + key, index, + allPointsMap = {}; - for ( var i = 0, l = array.length; i < l; i ++ ) { + // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first. - updateAttribute( array[ i ], gl.ARRAY_BUFFER ); + var allpoints = contour.concat(); - } + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - } + Array.prototype.push.apply( allpoints, holes[ h ] ); - return geometry; + } - } + //console.log( "allpoints",allpoints, allpoints.length ); - function updateAttribute( attribute, bufferType ) { + // prepare all points map - var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute; + for ( i = 0, il = allpoints.length; i < il; i ++ ) { - var attributeProperties = properties.get( data ); + key = allpoints[ i ].x + ":" + allpoints[ i ].y; - if ( attributeProperties.__webglBuffer === undefined ) { + if ( allPointsMap[ key ] !== undefined ) { - createBuffer( attributeProperties, data, bufferType ); + console.warn( "THREE.ShapeUtils: Duplicate point", key, i ); - } else if ( attributeProperties.version !== data.version ) { + } - updateBuffer( attributeProperties, data, bufferType ); + allPointsMap[ key ] = i; - } + } - } + // remove holes by cutting paths to holes and adding them to the shape + var shapeWithoutHoles = removeHoles( contour, holes ); - function createBuffer( attributeProperties, data, bufferType ) { + var triangles = exports.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape + //console.log( "triangles",triangles, triangles.length ); - attributeProperties.__webglBuffer = gl.createBuffer(); - gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); + // check all face vertices against all points map - var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; + for ( i = 0, il = triangles.length; i < il; i ++ ) { - gl.bufferData( bufferType, data.array, usage ); + face = triangles[ i ]; - attributeProperties.version = data.version; + for ( f = 0; f < 3; f ++ ) { - } + key = face[ f ].x + ":" + face[ f ].y; - function updateBuffer( attributeProperties, data, bufferType ) { + index = allPointsMap[ key ]; - gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); + if ( index !== undefined ) { - if ( data.dynamic === false || data.updateRange.count === - 1 ) { + face[ f ] = index; - // Not using update ranges + } - gl.bufferSubData( bufferType, 0, data.array ); + } - } else if ( data.updateRange.count === 0 ) { + } - console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' ); + return triangles.concat(); - } else { + }, - gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT, - data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) ); + isClockWise: function ( pts ) { - data.updateRange.count = 0; // reset range + return exports.ShapeUtils.area( pts ) < 0; - } + }, - attributeProperties.version = data.version; + // Bezier Curves formulas obtained from + // http://en.wikipedia.org/wiki/B%C3%A9zier_curve - } + // Quad Bezier Functions - function getAttributeBuffer( attribute ) { + b2: ( function () { - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + function b2p0( t, p ) { - return properties.get( attribute.data ).__webglBuffer; + var k = 1 - t; + return k * k * p; - } + } - return properties.get( attribute ).__webglBuffer; + function b2p1( t, p ) { - } + return 2 * ( 1 - t ) * t * p; - function getWireframeAttribute( geometry ) { + } - var property = properties.get( geometry ); + function b2p2( t, p ) { - if ( property.wireframe !== undefined ) { + return t * t * p; - return property.wireframe; + } - } + return function b2( t, p0, p1, p2 ) { - var indices = []; + return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 ); - var index = geometry.index; - var attributes = geometry.attributes; - var position = attributes.position; + }; - // console.time( 'wireframe' ); + } )(), - if ( index !== null ) { + // Cubic Bezier Functions - var edges = {}; - var array = index.array; + b3: ( function () { - for ( var i = 0, l = array.length; i < l; i += 3 ) { + function b3p0( t, p ) { - var a = array[ i + 0 ]; - var b = array[ i + 1 ]; - var c = array[ i + 2 ]; + var k = 1 - t; + return k * k * k * p; - if ( checkEdge( edges, a, b ) ) indices.push( a, b ); - if ( checkEdge( edges, b, c ) ) indices.push( b, c ); - if ( checkEdge( edges, c, a ) ) indices.push( c, a ); + } - } + function b3p1( t, p ) { - } else { + var k = 1 - t; + return 3 * k * k * t * p; - var array = attributes.position.array; + } - for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + function b3p2( t, p ) { - var a = i + 0; - var b = i + 1; - var c = i + 2; + var k = 1 - t; + return 3 * k * t * t * p; - indices.push( a, b, b, c, c, a ); + } - } + function b3p3( t, p ) { - } + return t * t * t * p; - // console.timeEnd( 'wireframe' ); + } - var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; - var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 ); + return function b3( t, p0, p1, p2, p3 ) { - updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); + return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 ); - property.wireframe = attribute; + }; - return attribute; + } )() - } + }; - function checkEdge( edges, a, b ) { + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Extensible curve object + * + * Some common of Curve methods + * .getPoint(t), getTangent(t) + * .getPointAt(u), getTagentAt(u) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following classes subclasses THREE.Curve: + * + * -- 2d classes -- + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.CubicBezierCurve + * THREE.SplineCurve + * THREE.ArcCurve + * THREE.EllipseCurve + * + * -- 3d classes -- + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * THREE.CubicBezierCurve3 + * THREE.SplineCurve3 + * + * A series of curves can be represented as a THREE.CurvePath + * + **/ - if ( a > b ) { + /************************************************************** + * Abstract Curve base class + **************************************************************/ - var tmp = a; - a = b; - b = tmp; + function Curve () { + this.isCurve = true; - } + }; - var list = edges[ a ]; + Curve.prototype = { - if ( list === undefined ) { + constructor: Curve, - edges[ a ] = [ b ]; - return true; + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] - } else if ( list.indexOf( b ) === -1 ) { + getPoint: function ( t ) { - list.push( b ); - return true; + console.warn( "THREE.Curve: Warning, getPoint() not implemented!" ); + return null; - } + }, - return false; + // Get point at relative position in curve according to arc length + // - u [0 .. 1] - } + getPointAt: function ( u ) { - this.getAttributeBuffer = getAttributeBuffer; - this.getWireframeAttribute = getWireframeAttribute; + var t = this.getUtoTmapping( u ); + return this.getPoint( t ); - this.update = update; + }, -}; + // Get sequence of points using getPoint( t ) -// File:src/renderers/webgl/WebGLProgram.js + getPoints: function ( divisions ) { -THREE.WebGLProgram = ( function () { + if ( ! divisions ) divisions = 5; - var programIdCount = 0; + var points = []; - function getEncodingComponents( encoding ) { + for ( var d = 0; d <= divisions; d ++ ) { - switch ( encoding ) { + points.push( this.getPoint( d / divisions ) ); - case THREE.LinearEncoding: - return [ 'Linear','( value )' ]; - case THREE.sRGBEncoding: - return [ 'sRGB','( value )' ]; - case THREE.RGBEEncoding: - return [ 'RGBE','( value )' ]; - case THREE.RGBM7Encoding: - return [ 'RGBM','( value, 7.0 )' ]; - case THREE.RGBM16Encoding: - return [ 'RGBM','( value, 16.0 )' ]; - case THREE.RGBDEncoding: - return [ 'RGBD','( value, 256.0 )' ]; - case THREE.GammaEncoding: - return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ]; - default: - throw new Error( 'unsupported encoding: ' + encoding ); + } - } + return points; - } + }, - function getTexelDecodingFunction( functionName, encoding ) { + // Get sequence of points using getPointAt( u ) - var components = getEncodingComponents( encoding ); - return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }"; + getSpacedPoints: function ( divisions ) { - } + if ( ! divisions ) divisions = 5; - function getTexelEncodingFunction( functionName, encoding ) { + var points = []; - var components = getEncodingComponents( encoding ); - return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }"; + for ( var d = 0; d <= divisions; d ++ ) { - } + points.push( this.getPointAt( d / divisions ) ); - function getToneMappingFunction( functionName, toneMapping ) { + } - var toneMappingName; + return points; - switch ( toneMapping ) { + }, - case THREE.LinearToneMapping: - toneMappingName = "Linear"; - break; + // Get total curve arc length - case THREE.ReinhardToneMapping: - toneMappingName = "Reinhard"; - break; + getLength: function () { - case THREE.Uncharted2ToneMapping: - toneMappingName = "Uncharted2"; - break; + var lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; - case THREE.CineonToneMapping: - toneMappingName = "OptimizedCineon"; - break; + }, - default: - throw new Error( 'unsupported toneMapping: ' + toneMapping ); + // Get list of cumulative segment lengths - } + getLengths: function ( divisions ) { - return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; + if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200; - } + if ( this.cacheArcLengths + && ( this.cacheArcLengths.length === divisions + 1 ) + && ! this.needsUpdate ) { - function generateExtensions( extensions, parameters, rendererExtensions ) { + //console.log( "cached", this.cacheArcLengths ); + return this.cacheArcLengths; - extensions = extensions || {}; + } - var chunks = [ - ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', - ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '', - ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '', - ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '', - ]; + this.needsUpdate = false; - return chunks.filter( filterEmptyLine ).join( '\n' ); + var cache = []; + var current, last = this.getPoint( 0 ); + var p, sum = 0; - } + cache.push( 0 ); - function generateDefines( defines ) { + for ( p = 1; p <= divisions; p ++ ) { - var chunks = []; + current = this.getPoint ( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; - for ( var name in defines ) { + } - var value = defines[ name ]; + this.cacheArcLengths = cache; - if ( value === false ) continue; + return cache; // { sums: cache, sum:sum }; Sum is in the last element. - chunks.push( '#define ' + name + ' ' + value ); + }, - } + updateArcLengths: function() { - return chunks.join( '\n' ); + this.needsUpdate = true; + this.getLengths(); - } + }, - function fetchAttributeLocations( gl, program, identifiers ) { + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant - var attributes = {}; + getUtoTmapping: function ( u, distance ) { - var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); + var arcLengths = this.getLengths(); - for ( var i = 0; i < n; i ++ ) { + var i = 0, il = arcLengths.length; - var info = gl.getActiveAttrib( program, i ); - var name = info.name; + var targetArcLength; // The targeted u distance value to get - // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i ); + if ( distance ) { - attributes[ name ] = gl.getAttribLocation( program, name ); + targetArcLength = distance; - } + } else { - return attributes; + targetArcLength = u * arcLengths[ il - 1 ]; - } + } - function filterEmptyLine( string ) { + //var time = Date.now(); - return string !== ''; + // binary search for the index with largest value smaller than target u distance - } + var low = 0, high = il - 1, comparison; - function replaceLightNums( string, parameters ) { + while ( low <= high ) { - return string - .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) - .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) - .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) - .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ); + i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats - } + comparison = arcLengths[ i ] - targetArcLength; - function parseIncludes( string ) { + if ( comparison < 0 ) { - var pattern = /#include +<([\w\d.]+)>/g; + low = i + 1; - function replace( match, include ) { + } else if ( comparison > 0 ) { - var replace = THREE.ShaderChunk[ include ]; + high = i - 1; - if ( replace === undefined ) { + } else { - throw new Error( 'Can not resolve #include <' + include + '>' ); + high = i; + break; - } + // DONE - return parseIncludes( replace ); + } - } + } - return string.replace( pattern, replace ); + i = high; - } + //console.log('b' , i, low, high, Date.now()- time); - function unrollLoops( string ) { + if ( arcLengths[ i ] === targetArcLength ) { - var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; + var t = i / ( il - 1 ); + return t; - function replace( match, start, end, snippet ) { + } - var unroll = ''; + // we could get finer grain at lengths, or use simple interpolation between two points - for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { + var lengthBefore = arcLengths[ i ]; + var lengthAfter = arcLengths[ i + 1 ]; - unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); + var segmentLength = lengthAfter - lengthBefore; - } + // determine where we are between the 'before' and 'after' points - return unroll; + var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - } + // add that fractional amount to t - return string.replace( pattern, replace ); + var t = ( i + segmentFraction ) / ( il - 1 ); - } + return t; - return function WebGLProgram( renderer, code, material, parameters ) { + }, - var gl = renderer.context; + // Returns a unit vector tangent at t + // In case any sub curve does not implement its tangent derivation, + // 2 points a small delta apart will be used to find its gradient + // which seems to give a reasonable approximation - var extensions = material.extensions; - var defines = material.defines; + getTangent: function( t ) { - var vertexShader = material.__webglShader.vertexShader; - var fragmentShader = material.__webglShader.fragmentShader; + var delta = 0.0001; + var t1 = t - delta; + var t2 = t + delta; - var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + // Capping in case of danger - if ( parameters.shadowMapType === THREE.PCFShadowMap ) { + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + var pt1 = this.getPoint( t1 ); + var pt2 = this.getPoint( t2 ); - } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { + var vec = pt2.clone().sub( pt1 ); + return vec.normalize(); - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + }, - } + getTangentAt: function ( u ) { - var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; - var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + var t = this.getUtoTmapping( u ); + return this.getTangent( t ); - if ( parameters.envMap ) { + } - switch ( material.envMap.mapping ) { + }; - case THREE.CubeReflectionMapping: - case THREE.CubeRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - break; + // TODO: Transformation for Curves? - case THREE.CubeUVReflectionMapping: - case THREE.CubeUVRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; - break; + /************************************************************** + * 3D Curves + **************************************************************/ - case THREE.EquirectangularReflectionMapping: - case THREE.EquirectangularRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; - break; + // A Factory method for creating new curve subclasses - case THREE.SphericalReflectionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; - break; + Curve.create = function ( constructor, getPointFunc ) { - } + constructor.prototype = Object.create( Curve.prototype ); + constructor.prototype.constructor = constructor; + constructor.prototype.getPoint = getPointFunc; - switch ( material.envMap.mapping ) { + return constructor; - case THREE.CubeRefractionMapping: - case THREE.EquirectangularRefractionMapping: - envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; - break; + }; - } + /************************************************************** + * Line + **************************************************************/ - switch ( material.combine ) { + function LineCurve ( v1, v2 ) { + this.isLineCurve = this.isCurve = true; - case THREE.MultiplyOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - break; + this.v1 = v1; + this.v2 = v2; - case THREE.MixOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; - break; + }; - case THREE.AddOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; - break; + LineCurve.prototype = Object.create( Curve.prototype ); + LineCurve.prototype.constructor = LineCurve; - } + LineCurve.prototype.getPoint = function ( t ) { - } + if ( t === 1 ) { - var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; + return this.v2.clone(); - // console.log( 'building new program ' ); + } - // + var point = this.v2.clone().sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); - var customExtensions = generateExtensions( extensions, parameters, renderer.extensions ); + return point; - var customDefines = generateDefines( defines ); + }; - // + // Line curve is linear, so we can overwrite default getPointAt - var program = gl.createProgram(); + LineCurve.prototype.getPointAt = function ( u ) { - var prefixVertex, prefixFragment; + return this.getPoint( u ); - if ( material instanceof THREE.RawShaderMaterial ) { + }; - prefixVertex = [ + LineCurve.prototype.getTangent = function( t ) { - customDefines + var tangent = this.v2.clone().sub( this.v1 ); - ].filter( filterEmptyLine ).join( '\n' ); + return tangent.normalize(); - prefixFragment = [ + }; - customDefines + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + **/ - ].filter( filterEmptyLine ).join( '\n' ); + /************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ - } else { + function CurvePath () { + this.isCurvePath = true; - prefixVertex = [ + this.curves = []; - 'precision ' + parameters.precision + ' float;', - 'precision ' + parameters.precision + ' int;', + this.autoClose = false; // Automatically closes the path - '#define SHADER_NAME ' + material.__webglShader.name, + }; - customDefines, + CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { - parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + constructor: CurvePath, - '#define GAMMA_FACTOR ' + gammaFactorDefine, + add: function ( curve ) { - '#define MAX_BONES ' + parameters.maxBones, + this.curves.push( curve ); - parameters.map ? '#define USE_MAP' : '', - parameters.envMap ? '#define USE_ENVMAP' : '', - parameters.envMap ? '#define ' + envMapModeDefine : '', - parameters.lightMap ? '#define USE_LIGHTMAP' : '', - parameters.aoMap ? '#define USE_AOMAP' : '', - parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', - parameters.bumpMap ? '#define USE_BUMPMAP' : '', - parameters.normalMap ? '#define USE_NORMALMAP' : '', - parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', - parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', + }, - parameters.flatShading ? '#define FLAT_SHADED' : '', + closePath: function () { - parameters.skinning ? '#define USE_SKINNING' : '', - parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', + // Add a line curve if start and end of lines are not connected + var startPoint = this.curves[ 0 ].getPoint( 0 ); + var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); - parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', - parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + if ( ! startPoint.equals( endPoint ) ) { - '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, + this.curves.push( new LineCurve( endPoint, startPoint ) ); - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + } - parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + }, - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + // To get accurate point with reference to + // entire path distance at time t, + // following has to be done: - 'uniform mat4 modelMatrix;', - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform mat4 viewMatrix;', - 'uniform mat3 normalMatrix;', - 'uniform vec3 cameraPosition;', + // 1. Length of each sub path have to be known + // 2. Locate and identify type of curve + // 3. Get t for the curve + // 4. Return curve.getPointAt(t') - 'attribute vec3 position;', - 'attribute vec3 normal;', - 'attribute vec2 uv;', + getPoint: function ( t ) { - '#ifdef USE_COLOR', + var d = t * this.getLength(); + var curveLengths = this.getCurveLengths(); + var i = 0; - ' attribute vec3 color;', + // To think about boundaries points. - '#endif', + while ( i < curveLengths.length ) { - '#ifdef USE_MORPHTARGETS', + if ( curveLengths[ i ] >= d ) { - ' attribute vec3 morphTarget0;', - ' attribute vec3 morphTarget1;', - ' attribute vec3 morphTarget2;', - ' attribute vec3 morphTarget3;', + var diff = curveLengths[ i ] - d; + var curve = this.curves[ i ]; - ' #ifdef USE_MORPHNORMALS', + var segmentLength = curve.getLength(); + var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; - ' attribute vec3 morphNormal0;', - ' attribute vec3 morphNormal1;', - ' attribute vec3 morphNormal2;', - ' attribute vec3 morphNormal3;', + return curve.getPointAt( u ); - ' #else', + } - ' attribute vec3 morphTarget4;', - ' attribute vec3 morphTarget5;', - ' attribute vec3 morphTarget6;', - ' attribute vec3 morphTarget7;', + i ++; - ' #endif', + } - '#endif', + return null; - '#ifdef USE_SKINNING', + // loop where sum != 0, sum > d , sum+1 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) { - // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); - // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); + points.push( points[ 0 ] ); - if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { + } - runnable = false; + return points; - console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog ); + }, - } else if ( programLog !== '' ) { + /************************************************************** + * Create Geometries Helpers + **************************************************************/ - console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); + /// Generate geometry from path points (for Line or Points objects) - } else if ( vertexLog === '' || fragmentLog === '' ) { + createPointsGeometry: function ( divisions ) { - haveDiagnostics = false; + var pts = this.getPoints( divisions ); + return this.createGeometry( pts ); - } + }, - if ( haveDiagnostics ) { + // Generate geometry from equidistant sampling along the path - this.diagnostics = { + createSpacedPointsGeometry: function ( divisions ) { - runnable: runnable, - material: material, + var pts = this.getSpacedPoints( divisions ); + return this.createGeometry( pts ); - programLog: programLog, + }, - vertexShader: { + createGeometry: function ( points ) { - log: vertexLog, - prefix: prefixVertex + var geometry = new Geometry(); - }, + for ( var i = 0, l = points.length; i < l; i ++ ) { - fragmentShader: { + var point = points[ i ]; + geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); - log: fragmentLog, - prefix: prefixFragment + } - } + return geometry; - }; + } - } + } ); - // clean up + /************************************************************** + * Ellipse curve + **************************************************************/ - gl.deleteShader( glVertexShader ); - gl.deleteShader( glFragmentShader ); + function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + this.isEllipseCurve = this.isCurve = true; - // set up caching for uniform locations + this.aX = aX; + this.aY = aY; - var cachedUniforms; + this.xRadius = xRadius; + this.yRadius = yRadius; - this.getUniforms = function() { + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; - if ( cachedUniforms === undefined ) { + this.aClockwise = aClockwise; - cachedUniforms = - new THREE.WebGLUniforms( gl, program, renderer ); + this.aRotation = aRotation || 0; - } + }; - return cachedUniforms; + EllipseCurve.prototype = Object.create( Curve.prototype ); + EllipseCurve.prototype.constructor = EllipseCurve; - }; + EllipseCurve.prototype.getPoint = function( t ) { - // set up caching for attribute locations + var twoPi = Math.PI * 2; + var deltaAngle = this.aEndAngle - this.aStartAngle; + var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; - var cachedAttributes; + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; - this.getAttributes = function() { + if ( deltaAngle < Number.EPSILON ) { - if ( cachedAttributes === undefined ) { + if ( samePoints ) { - cachedAttributes = fetchAttributeLocations( gl, program ); + deltaAngle = 0; - } + } else { - return cachedAttributes; + deltaAngle = twoPi; - }; + } - // free resource + } - this.destroy = function() { + if ( this.aClockwise === true && ! samePoints ) { - gl.deleteProgram( program ); - this.program = undefined; + if ( deltaAngle === twoPi ) { - }; + deltaAngle = - twoPi; - // DEPRECATED + } else { - Object.defineProperties( this, { + deltaAngle = deltaAngle - twoPi; - uniforms: { - get: function() { + } - console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' ); - return this.getUniforms(); + } - } - }, + var angle = this.aStartAngle + t * deltaAngle; + var x = this.aX + this.xRadius * Math.cos( angle ); + var y = this.aY + this.yRadius * Math.sin( angle ); - attributes: { - get: function() { + if ( this.aRotation !== 0 ) { - console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' ); - return this.getAttributes(); + var cos = Math.cos( this.aRotation ); + var sin = Math.sin( this.aRotation ); - } - } + var tx = x - this.aX; + var ty = y - this.aY; - } ); + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; + } - // + return new Vector2( x, y ); - this.id = programIdCount ++; - this.code = code; - this.usedTimes = 1; - this.program = program; - this.vertexShader = glVertexShader; - this.fragmentShader = glFragmentShader; + }; - return this; + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - }; + exports.CurveUtils = { -} )(); + tangentQuadraticBezier: function ( t, p0, p1, p2 ) { -// File:src/renderers/webgl/WebGLPrograms.js + return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); -THREE.WebGLPrograms = function ( renderer, capabilities ) { + }, - var programs = []; + // Puay Bing, thanks for helping with this derivative! - var shaderIDs = { - MeshDepthMaterial: 'depth', - MeshNormalMaterial: 'normal', - MeshBasicMaterial: 'basic', - MeshLambertMaterial: 'lambert', - MeshPhongMaterial: 'phong', - MeshStandardMaterial: 'physical', - MeshPhysicalMaterial: 'physical', - LineBasicMaterial: 'basic', - LineDashedMaterial: 'dashed', - PointsMaterial: 'points' - }; + tangentCubicBezier: function ( t, p0, p1, p2, p3 ) { - var parameterNames = [ - "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding", - "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap", - "roughnessMap", "metalnessMap", - "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp", - "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", - "maxBones", "useVertexTexture", "morphTargets", "morphNormals", - "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", - "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", - "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', - "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking" - ]; + return - 3 * p0 * ( 1 - t ) * ( 1 - t ) + + 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) + + 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 + + 3 * t * t * p3; + }, - function allocateBones ( object ) { + tangentSpline: function ( t, p0, p1, p2, p3 ) { - if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { + // To check if my formulas are correct - return 1024; + var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1 + var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t + var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2 + var h11 = 3 * t * t - 2 * t; // t3 − t2 - } else { + return h00 + h10 + h01 + h11; - // default for when object is not specified - // ( for example when prebuilding shader to be used with multiple objects ) - // - // - leave some extra space for other uniforms - // - limit here is ANGLE's 254 max uniform vectors - // (up to 54 should be safe) + }, - var nVertexUniforms = capabilities.maxVertexUniforms; - var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); + // Catmull-Rom - var maxBones = nVertexMatrices; + interpolate: function( p0, p1, p2, p3, t ) { - if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { + var v0 = ( p2 - p0 ) * 0.5; + var v1 = ( p3 - p1 ) * 0.5; + var t2 = t * t; + var t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - maxBones = Math.min( object.skeleton.bones.length, maxBones ); + } - if ( maxBones < object.skeleton.bones.length ) { + }; - console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); + /************************************************************** + * Spline curve + **************************************************************/ - } + function SplineCurve ( points /* array of Vector2 */ ) { + this.isSplineCurve = this.isCurve = true; - } + this.points = ( points == undefined ) ? [] : points; - return maxBones; + }; - } + SplineCurve.prototype = Object.create( Curve.prototype ); + SplineCurve.prototype.constructor = SplineCurve; - } + SplineCurve.prototype.getPoint = function ( t ) { - function getTextureEncodingFromMap( map, gammaOverrideLinear ) { + var points = this.points; + var point = ( points.length - 1 ) * t; - var encoding; + var intPoint = Math.floor( point ); + var weight = point - intPoint; - if ( ! map ) { + var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + var point1 = points[ intPoint ]; + var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; - encoding = THREE.LinearEncoding; + var interpolate = exports.CurveUtils.interpolate; - } else if ( map instanceof THREE.Texture ) { + return new Vector2( + interpolate( point0.x, point1.x, point2.x, point3.x, weight ), + interpolate( point0.y, point1.y, point2.y, point3.y, weight ) + ); - encoding = map.encoding; + }; - } else if ( map instanceof THREE.WebGLRenderTarget ) { + /************************************************************** + * Cubic Bezier curve + **************************************************************/ - console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); - encoding = map.texture.encoding; + function CubicBezierCurve ( v0, v1, v2, v3 ) { + this.isCubicBezierCurve = this.isCurve = true; - } + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. - if ( encoding === THREE.LinearEncoding && gammaOverrideLinear ) { + }; - encoding = THREE.GammaEncoding; + CubicBezierCurve.prototype = Object.create( Curve.prototype ); + CubicBezierCurve.prototype.constructor = CubicBezierCurve; - } + CubicBezierCurve.prototype.getPoint = function ( t ) { - return encoding; + var b3 = exports.ShapeUtils.b3; - } + return new Vector2( + b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), + b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) + ); - this.getParameters = function ( material, lights, fog, nClipPlanes, object ) { + }; - var shaderID = shaderIDs[ material.type ]; + CubicBezierCurve.prototype.getTangent = function( t ) { - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) + var tangentCubicBezier = exports.CurveUtils.tangentCubicBezier; - var maxBones = allocateBones( object ); - var precision = renderer.getPrecision(); + return new Vector2( + tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), + tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) + ).normalize(); - if ( material.precision !== null ) { + }; - precision = capabilities.getMaxPrecision( material.precision ); + /************************************************************** + * Quadratic Bezier curve + **************************************************************/ - if ( precision !== material.precision ) { - console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + function QuadraticBezierCurve ( v0, v1, v2 ) { + this.isQuadraticBezierCurve = this.isCurve = true; - } + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - } + }; - var currentRenderTarget = renderer.getCurrentRenderTarget(); + QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); + QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; - var parameters = { - shaderID: shaderID, + QuadraticBezierCurve.prototype.getPoint = function ( t ) { - precision: precision, - supportsVertexTextures: capabilities.vertexTextures, - outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ), - map: !! material.map, - mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ), - envMap: !! material.envMap, - envMapMode: material.envMap && material.envMap.mapping, - envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ), - envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === THREE.CubeUVReflectionMapping ) || ( material.envMap.mapping === THREE.CubeUVRefractionMapping ) ), - lightMap: !! material.lightMap, - aoMap: !! material.aoMap, - emissiveMap: !! material.emissiveMap, - emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ), - bumpMap: !! material.bumpMap, - normalMap: !! material.normalMap, - displacementMap: !! material.displacementMap, - roughnessMap: !! material.roughnessMap, - metalnessMap: !! material.metalnessMap, - specularMap: !! material.specularMap, - alphaMap: !! material.alphaMap, + var b2 = exports.ShapeUtils.b2; - combine: material.combine, + return new Vector2( + b2( t, this.v0.x, this.v1.x, this.v2.x ), + b2( t, this.v0.y, this.v1.y, this.v2.y ) + ); - vertexColors: material.vertexColors, + }; - fog: !! fog, - useFog: material.fog, - fogExp: fog instanceof THREE.FogExp2, - flatShading: material.shading === THREE.FlatShading, + QuadraticBezierCurve.prototype.getTangent = function( t ) { - sizeAttenuation: material.sizeAttenuation, - logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, + var tangentQuadraticBezier = exports.CurveUtils.tangentQuadraticBezier; - skinning: material.skinning, - maxBones: maxBones, - useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture, + return new Vector2( + tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ), + tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ) + ).normalize(); - morphTargets: material.morphTargets, - morphNormals: material.morphNormals, - maxMorphTargets: renderer.maxMorphTargets, - maxMorphNormals: renderer.maxMorphNormals, + }; - numDirLights: lights.directional.length, - numPointLights: lights.point.length, - numSpotLights: lights.spot.length, - numHemiLights: lights.hemi.length, + var PathPrototype; - numClippingPlanes: nClipPlanes, + PathPrototype = Object.assign( Object.create( CurvePath.prototype ), { - shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0, - shadowMapType: renderer.shadowMap.type, + fromPoints: function ( vectors ) { - toneMapping: renderer.toneMapping, - physicallyCorrectLights: renderer.physicallyCorrectLights, + this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - premultipliedAlpha: material.premultipliedAlpha, + for ( var i = 1, l = vectors.length; i < l; i ++ ) { - alphaTest: material.alphaTest, - doubleSided: material.side === THREE.DoubleSide, - flipSided: material.side === THREE.BackSide, + this.lineTo( vectors[ i ].x, vectors[ i ].y ); - depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false + } - }; + }, - return parameters; + moveTo: function ( x, y ) { - }; + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? - this.getProgramCode = function ( material, parameters ) { + }, - var array = []; + lineTo: function ( x, y ) { - if ( parameters.shaderID ) { + var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); - array.push( parameters.shaderID ); + this.currentPoint.set( x, y ); - } else { + }, - array.push( material.fragmentShader ); - array.push( material.vertexShader ); + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - } + var curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); - if ( material.defines !== undefined ) { + this.curves.push( curve ); - for ( var name in material.defines ) { + this.currentPoint.set( aX, aY ); - array.push( name ); - array.push( material.defines[ name ] ); + }, - } + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - } + var curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); - for ( var i = 0; i < parameterNames.length; i ++ ) { + this.curves.push( curve ); - array.push( parameters[ parameterNames[ i ] ] ); + this.currentPoint.set( aX, aY ); - } + }, - return array.join(); + splineThru: function ( pts /*Array of Vector*/ ) { - }; + var npts = [ this.currentPoint.clone() ].concat( pts ); - this.acquireProgram = function ( material, parameters, code ) { + var curve = new SplineCurve( npts ); + this.curves.push( curve ); - var program; + this.currentPoint.copy( pts[ pts.length - 1 ] ); - // Check if code has been already compiled - for ( var p = 0, pl = programs.length; p < pl; p ++ ) { + }, - var programInfo = programs[ p ]; + arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - if ( programInfo.code === code ) { + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - program = programInfo; - ++ program.usedTimes; + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); - break; + }, - } + absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - } + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - if ( program === undefined ) { + }, - program = new THREE.WebGLProgram( renderer, code, material, parameters ); - programs.push( program ); + ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - } + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - return program; + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - }; + }, - this.releaseProgram = function( program ) { + absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - if ( -- program.usedTimes === 0 ) { + var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - // Remove from unordered set - var i = programs.indexOf( program ); - programs[ i ] = programs[ programs.length - 1 ]; - programs.pop(); + if ( this.curves.length > 0 ) { - // Free WebGL resources - program.destroy(); + // if a previous curve is present, attempt to join + var firstPoint = curve.getPoint( 0 ); - } + if ( ! firstPoint.equals( this.currentPoint ) ) { - }; + this.lineTo( firstPoint.x, firstPoint.y ); - // Exposed for resource monitoring & error feedback via renderer.info: - this.programs = programs; + } -}; + } -// File:src/renderers/webgl/WebGLProperties.js + this.curves.push( curve ); -/** -* @author fordacious / fordacious.github.io -*/ + var lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); -THREE.WebGLProperties = function () { + } - var properties = {}; + } ) - this.get = function ( object ) { + /** + * @author WestLangley / https://github.com/WestLangley + * @author zz85 / https://github.com/zz85 + * @author miningold / https://github.com/miningold + * @author jonobr1 / https://github.com/jonobr1 + * + * Modified from the TorusKnotGeometry by @oosmoxiecode + * + * Creates a tube which extrudes along a 3d spline + * + * Uses parallel transport frames as described in + * http://www.cs.indiana.edu/pub/techreports/TR425.pdf + */ - var uuid = object.uuid; - var map = properties[ uuid ]; + function TubeGeometry ( path, segments, radius, radialSegments, closed, taper ) { + this.isTubeGeometry = this.isGeometry = true; - if ( map === undefined ) { + Geometry.call( this ); - map = {}; - properties[ uuid ] = map; + this.type = 'TubeGeometry'; - } + this.parameters = { + path: path, + segments: segments, + radius: radius, + radialSegments: radialSegments, + closed: closed, + taper: taper + }; - return map; + segments = segments || 64; + radius = radius || 1; + radialSegments = radialSegments || 8; + closed = closed || false; + taper = taper || TubeGeometry.NoTaper; - }; + var grid = []; - this.delete = function ( object ) { + var scope = this, - delete properties[ object.uuid ]; + tangent, + normal, + binormal, - }; + numpoints = segments + 1, - this.clear = function () { + u, v, r, - properties = {}; + cx, cy, + pos, pos2 = new Vector3(), + i, j, + ip, jp, + a, b, c, d, + uva, uvb, uvc, uvd; - }; + var frames = new TubeGeometry.FrenetFrames( path, segments, closed ), + tangents = frames.tangents, + normals = frames.normals, + binormals = frames.binormals; -}; + // proxy internals + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; -// File:src/renderers/webgl/WebGLShader.js + function vert( x, y, z ) { -THREE.WebGLShader = ( function () { + return scope.vertices.push( new Vector3( x, y, z ) ) - 1; - function addLineNumbers( string ) { + } - var lines = string.split( '\n' ); + // construct the grid - for ( var i = 0; i < lines.length; i ++ ) { + for ( i = 0; i < numpoints; i ++ ) { - lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; + grid[ i ] = []; - } + u = i / ( numpoints - 1 ); - return lines.join( '\n' ); + pos = path.getPointAt( u ); - } + tangent = tangents[ i ]; + normal = normals[ i ]; + binormal = binormals[ i ]; - return function WebGLShader( gl, type, string ) { + r = radius * taper( u ); - var shader = gl.createShader( type ); + for ( j = 0; j < radialSegments; j ++ ) { - gl.shaderSource( shader, string ); - gl.compileShader( shader ); + v = j / radialSegments * 2 * Math.PI; - if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { + cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. + cy = r * Math.sin( v ); - console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); + pos2.copy( pos ); + pos2.x += cx * normal.x + cy * binormal.x; + pos2.y += cx * normal.y + cy * binormal.y; + pos2.z += cx * normal.z + cy * binormal.z; - } + grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); - if ( gl.getShaderInfoLog( shader ) !== '' ) { + } - console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); + } - } - // --enable-privileged-webgl-extension - // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + // construct the mesh - return shader; + for ( i = 0; i < segments; i ++ ) { - }; + for ( j = 0; j < radialSegments; j ++ ) { -} )(); + ip = ( closed ) ? ( i + 1 ) % segments : i + 1; + jp = ( j + 1 ) % radialSegments; -// File:src/renderers/webgl/WebGLShadowMap.js + a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** + b = grid[ ip ][ j ]; + c = grid[ ip ][ jp ]; + d = grid[ i ][ jp ]; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + uva = new Vector2( i / segments, j / radialSegments ); + uvb = new Vector2( ( i + 1 ) / segments, j / radialSegments ); + uvc = new Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments ); + uvd = new Vector2( i / segments, ( j + 1 ) / radialSegments ); -THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { + this.faces.push( new Face3( a, b, d ) ); + this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - var _gl = _renderer.context, - _state = _renderer.state, - _frustum = new THREE.Frustum(), - _projScreenMatrix = new THREE.Matrix4(), + this.faces.push( new Face3( b, c, d ) ); + this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); - _lightShadows = _lights.shadows, + } - _shadowMapSize = new THREE.Vector2(), - _maxShadowMapSize = new THREE.Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), + } - _lookTarget = new THREE.Vector3(), - _lightPositionWorld = new THREE.Vector3(), + this.computeFaceNormals(); + this.computeVertexNormals(); - _renderList = [], + }; - _MorphingFlag = 1, - _SkinningFlag = 2, + TubeGeometry.prototype = Object.create( Geometry.prototype ); + TubeGeometry.prototype.constructor = TubeGeometry; - _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, + TubeGeometry.NoTaper = function ( u ) { - _depthMaterials = new Array( _NumberOfMaterialVariants ), - _distanceMaterials = new Array( _NumberOfMaterialVariants ), + return 1; - _materialCache = {}; + }; - var cubeDirections = [ - new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ), - new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 ) - ]; + TubeGeometry.SinusoidalTaper = function ( u ) { - var cubeUps = [ - new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), - new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 ) - ]; + return Math.sin( Math.PI * u ); - var cube2DViewPorts = [ - new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(), - new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4() - ]; + }; - // init + // For computing of Frenet frames, exposing the tangents, normals and binormals the spline + TubeGeometry.FrenetFrames = function ( path, segments, closed ) { - var depthMaterialTemplate = new THREE.MeshDepthMaterial(); - depthMaterialTemplate.depthPacking = THREE.RGBADepthPacking; - depthMaterialTemplate.clipping = true; + var normal = new Vector3(), - var distanceShader = THREE.ShaderLib[ "distanceRGBA" ]; - var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms ); + tangents = [], + normals = [], + binormals = [], - for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { + vec = new Vector3(), + mat = new Matrix4(), - var useMorphing = ( i & _MorphingFlag ) !== 0; - var useSkinning = ( i & _SkinningFlag ) !== 0; + numpoints = segments + 1, + theta, + smallest, - var depthMaterial = depthMaterialTemplate.clone(); - depthMaterial.morphTargets = useMorphing; - depthMaterial.skinning = useSkinning; + tx, ty, tz, + i, u; - _depthMaterials[ i ] = depthMaterial; - var distanceMaterial = new THREE.ShaderMaterial( { - defines: { - 'USE_SHADOWMAP': '' - }, - uniforms: distanceUniforms, - vertexShader: distanceShader.vertexShader, - fragmentShader: distanceShader.fragmentShader, - morphTargets: useMorphing, - skinning: useSkinning, - clipping: true - } ); + // expose internals + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; - _distanceMaterials[ i ] = distanceMaterial; + // compute the tangent vectors for each segment on the path - } + for ( i = 0; i < numpoints; i ++ ) { - // + u = i / ( numpoints - 1 ); - var scope = this; + tangents[ i ] = path.getTangentAt( u ); + tangents[ i ].normalize(); - this.enabled = false; + } - this.autoUpdate = true; - this.needsUpdate = false; + initialNormal3(); - this.type = THREE.PCFShadowMap; + /* + function initialNormal1(lastBinormal) { + // fixed start binormal. Has dangers of 0 vectors + normals[ 0 ] = new THREE.Vector3(); + binormals[ 0 ] = new THREE.Vector3(); + if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 ); + normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize(); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); + } - this.renderReverseSided = true; - this.renderSingleSided = true; + function initialNormal2() { - this.render = function ( scene, camera ) { + // This uses the Frenet-Serret formula for deriving binormal + var t2 = path.getTangentAt( epsilon ); - if ( scope.enabled === false ) return; - if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); + binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); - if ( _lightShadows.length === 0 ) return; + normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); - // Set GL state for depth map. - _state.clearColor( 1, 1, 1, 1 ); - _state.disable( _gl.BLEND ); - _state.setDepthTest( true ); - _state.setScissorTest( false ); + } + */ - // render depth map + function initialNormal3() { - var faceCount, isPointLight; + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the smallest tangent xyz component - for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) { + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + smallest = Number.MAX_VALUE; + tx = Math.abs( tangents[ 0 ].x ); + ty = Math.abs( tangents[ 0 ].y ); + tz = Math.abs( tangents[ 0 ].z ); - var light = _lightShadows[ i ]; - var shadow = light.shadow; + if ( tx <= smallest ) { - if ( shadow === undefined ) { + smallest = tx; + normal.set( 1, 0, 0 ); - console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); - continue; + } - } + if ( ty <= smallest ) { - var shadowCamera = shadow.camera; + smallest = ty; + normal.set( 0, 1, 0 ); - _shadowMapSize.copy( shadow.mapSize ); - _shadowMapSize.min( _maxShadowMapSize ); + } - if ( light instanceof THREE.PointLight ) { + if ( tz <= smallest ) { - faceCount = 6; - isPointLight = true; + normal.set( 0, 0, 1 ); - var vpWidth = _shadowMapSize.x; - var vpHeight = _shadowMapSize.y; + } - // These viewports map a cube-map onto a 2D texture with the - // following orientation: - // - // xzXZ - // y Y - // - // X - Positive x direction - // x - Negative x direction - // Y - Positive y direction - // y - Negative y direction - // Z - Positive z direction - // z - Negative z direction + vec.crossVectors( tangents[ 0 ], normal ).normalize(); - // positive X - cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight ); - // negative X - cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight ); - // positive Z - cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight ); - // negative Z - cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight ); - // positive Y - cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight ); - // negative Y - cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight ); + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); - _shadowMapSize.x *= 4.0; - _shadowMapSize.y *= 2.0; + } - } else { - faceCount = 1; - isPointLight = false; + // compute the slowly-varying normal and binormal vectors for each segment on the path - } + for ( i = 1; i < numpoints; i ++ ) { - if ( shadow.map === null ) { + normals[ i ] = normals[ i - 1 ].clone(); - var pars = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat }; + binormals[ i ] = binormals[ i - 1 ].clone(); - shadow.map = new THREE.WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); - shadowCamera.updateProjectionMatrix(); + if ( vec.length() > Number.EPSILON ) { - } + vec.normalize(); - if ( shadow instanceof THREE.SpotLightShadow ) { + theta = Math.acos( exports.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors - shadow.update( light ); + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); - } + } - var shadowMap = shadow.map; - var shadowMatrix = shadow.matrix; + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); - shadowCamera.position.copy( _lightPositionWorld ); + } - _renderer.setRenderTarget( shadowMap ); - _renderer.clear(); - // render shadow map for each cube face (if omni-directional) or - // run a single pass if not + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same - for ( var face = 0; face < faceCount; face ++ ) { + if ( closed ) { - if ( isPointLight ) { + theta = Math.acos( exports.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); + theta /= ( numpoints - 1 ); - _lookTarget.copy( shadowCamera.position ); - _lookTarget.add( cubeDirections[ face ] ); - shadowCamera.up.copy( cubeUps[ face ] ); - shadowCamera.lookAt( _lookTarget ); + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { - var vpDimensions = cube2DViewPorts[ face ]; - _state.viewport( vpDimensions ); + theta = - theta; - } else { + } - _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); - shadowCamera.lookAt( _lookTarget ); + for ( i = 1; i < numpoints; i ++ ) { - } + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - shadowCamera.updateMatrixWorld(); - shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); + } - // compute shadow matrix + } - shadowMatrix.set( - 0.5, 0.0, 0.0, 0.5, - 0.0, 0.5, 0.0, 0.5, - 0.0, 0.0, 0.5, 0.5, - 0.0, 0.0, 0.0, 1.0 - ); + }; - shadowMatrix.multiply( shadowCamera.projectionMatrix ); - shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + * Creates extruded geometry from a path shape. + * + * parameters = { + * + * curveSegments: , // number of points on the curves + * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too + * amount: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline is bevel + * bevelSegments: , // number of bevel layers + * + * extrudePath: // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined) + * frames: // containing arrays of tangents, normals, binormals + * + * uvGenerator: // object that provides UV generator functions + * + * } + **/ - // update camera matrices and frustum + function ExtrudeGeometry ( shapes, options ) { + this.isExtrudeGeometry = this.isGeometry = true; - _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + if ( typeof( shapes ) === "undefined" ) { - // set object matrices & frustum culling + shapes = []; + return; - _renderList.length = 0; + } - projectObject( scene, camera, shadowCamera ); + Geometry.call( this ); - // render shadow map - // render regular objects + this.type = 'ExtrudeGeometry'; - for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) { + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; - var object = _renderList[ j ]; - var geometry = _objects.update( object ); - var material = object.material; + this.addShapeList( shapes, options ); - if ( material instanceof THREE.MultiMaterial ) { + this.computeFaceNormals(); - var groups = geometry.groups; - var materials = material.materials; + // can't really use automatic vertex normals + // as then front and back sides get smoothed too + // should do separate smoothing just for sides - for ( var k = 0, kl = groups.length; k < kl; k ++ ) { + //this.computeVertexNormals(); - var group = groups[ k ]; - var groupMaterial = materials[ group.materialIndex ]; + //console.log( "took", ( Date.now() - startTime ) ); - if ( groupMaterial.visible === true ) { + }; - var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld ); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); + ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; - } + ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { - } + var sl = shapes.length; - } else { + for ( var s = 0; s < sl; s ++ ) { - var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld ); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + var shape = shapes[ s ]; + this.addShape( shape, options ); - } + } - } + }; - } + ExtrudeGeometry.prototype.addShape = function ( shape, options ) { - } + var amount = options.amount !== undefined ? options.amount : 100; - // Restore GL state. - var clearColor = _renderer.getClearColor(), - clearAlpha = _renderer.getClearAlpha(); - _renderer.setClearColor( clearColor, clearAlpha ); + var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10 + var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8 + var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; - scope.needsUpdate = false; + var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false - }; + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) { + var steps = options.steps !== undefined ? options.steps : 1; - var geometry = object.geometry; + var extrudePath = options.extrudePath; + var extrudePts, extrudeByPath = false; - var result = null; + // Use default WorldUVGenerator if no UV generators are specified. + var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator; - var materialVariants = _depthMaterials; - var customMaterial = object.customDepthMaterial; + var splineTube, binormal, normal, position2; + if ( extrudePath ) { - if ( isPointLight ) { + extrudePts = extrudePath.getSpacedPoints( steps ); - materialVariants = _distanceMaterials; - customMaterial = object.customDistanceMaterial; + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion - } + // SETUP TNB variables - if ( ! customMaterial ) { + // Reuse TNB from TubeGeomtry for now. + // TODO1 - have a .isClosed in spline? - var useMorphing = false; + splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false ); - if ( material.morphTargets ) { + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - if ( geometry instanceof THREE.BufferGeometry ) { + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); - useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; + } - } else if ( geometry instanceof THREE.Geometry ) { + // Safeguards if bevels are not enabled - useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; + if ( ! bevelEnabled ) { - } + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; - } + } - var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning; + // Variables initialization - var variantIndex = 0; + var ahole, h, hl; // looping of holes + var scope = this; - if ( useMorphing ) variantIndex |= _MorphingFlag; - if ( useSkinning ) variantIndex |= _SkinningFlag; + var shapesOffset = this.vertices.length; - result = materialVariants[ variantIndex ]; + var shapePoints = shape.extractPoints( curveSegments ); - } else { + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - result = customMaterial; + var reverse = ! exports.ShapeUtils.isClockWise( vertices ); - } + if ( reverse ) { - if ( _renderer.localClippingEnabled && - material.clipShadows === true && - material.clippingPlanes.length !== 0 ) { + vertices = vertices.reverse(); - // in this case we need a unique material instance reflecting the - // appropriate state + // Maybe we should also check if holes are in the opposite direction, just to be safe ... - var keyA = result.uuid, keyB = material.uuid; + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - var materialsForVariant = _materialCache[ keyA ]; + ahole = holes[ h ]; - if ( materialsForVariant === undefined ) { + if ( exports.ShapeUtils.isClockWise( ahole ) ) { - materialsForVariant = {}; - _materialCache[ keyA ] = materialsForVariant; + holes[ h ] = ahole.reverse(); - } + } - var cachedMaterial = materialsForVariant[ keyB ]; + } - if ( cachedMaterial === undefined ) { + reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! - cachedMaterial = result.clone(); - materialsForVariant[ keyB ] = cachedMaterial; + } - } - result = cachedMaterial; + var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); - } + /* Vertices */ - result.visible = material.visible; - result.wireframe = material.wireframe; + var contour = vertices; // vertices has all points but contour has only points of circumference - var side = material.side; + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - if ( scope.renderSingleSided && side == THREE.DoubleSide ) { + ahole = holes[ h ]; - side = THREE.FrontSide; + vertices = vertices.concat( ahole ); - } + } - if ( scope.renderReverseSided ) { - if ( side === THREE.FrontSide ) side = THREE.BackSide; - else if ( side === THREE.BackSide ) side = THREE.FrontSide; + function scalePt2 ( pt, vec, size ) { - } + if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); - result.side = side; + return vec.clone().multiplyScalar( size ).add( pt ); - result.clipShadows = material.clipShadows; - result.clippingPlanes = material.clippingPlanes; + } - result.wireframeLinewidth = material.wireframeLinewidth; - result.linewidth = material.linewidth; + var b, bs, t, z, + vert, vlen = vertices.length, + face, flen = faces.length; - if ( isPointLight && result.uniforms.lightPos !== undefined ) { - result.uniforms.lightPos.value.copy( lightPositionWorld ); + // Find directions for point movement - } - return result; + function getBevelVec( inPt, inPrev, inNext ) { - } + // computes for inPt the corresponding point inPt' on a new contour + // shifted by 1 unit (length of normalized vector) to the left + // if we walk along contour clockwise, this new contour is outside the old one + // + // inPt' is the intersection of the two lines parallel to the two + // adjacent edges of inPt at a distance of 1 unit on the left side. - function projectObject( object, camera, shadowCamera ) { + var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt - if ( object.visible === false ) return; + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html - if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) { + var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; - if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { + var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - var material = object.material; + // check for collinear edges + var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - if ( material.visible === true ) { + if ( Math.abs( collinear0 ) > Number.EPSILON ) { - object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); - _renderList.push( object ); + // not collinear - } + // length of vectors for normalizing - } + var v_prev_len = Math.sqrt( v_prev_lensq ); + var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); - } + // shift adjacent points by unit vectors to the left - var children = object.children; + var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); - for ( var i = 0, l = children.length; i < l; i ++ ) { + var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - projectObject( children[ i ], camera, shadowCamera ); + // scaling factor for v_prev to intersection point - } + var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - + ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / + ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - } + // vector from inPt to intersection point -}; + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); -// File:src/renderers/webgl/WebGLState.js + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { -/** -* @author mrdoob / http://mrdoob.com/ -*/ + return new Vector2( v_trans_x, v_trans_y ); -THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { + } else { - var _this = this; + shrink_by = Math.sqrt( v_trans_lensq / 2 ); - this.buffers = { - color: new THREE.WebGLColorBuffer( gl, this ), - depth: new THREE.WebGLDepthBuffer( gl, this ), - stencil: new THREE.WebGLStencilBuffer( gl, this ) - }; + } - var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); - var newAttributes = new Uint8Array( maxVertexAttributes ); - var enabledAttributes = new Uint8Array( maxVertexAttributes ); - var attributeDivisors = new Uint8Array( maxVertexAttributes ); + } else { - var capabilities = {}; + // handle special case of collinear edges - var compressedTextureFormats = null; + var direction_eq = false; // assumes: opposite + if ( v_prev_x > Number.EPSILON ) { - var currentBlending = null; - var currentBlendEquation = null; - var currentBlendSrc = null; - var currentBlendDst = null; - var currentBlendEquationAlpha = null; - var currentBlendSrcAlpha = null; - var currentBlendDstAlpha = null; - var currentPremultipledAlpha = false; + if ( v_next_x > Number.EPSILON ) { - var currentFlipSided = null; - var currentCullFace = null; + direction_eq = true; - var currentLineWidth = null; + } - var currentPolygonOffsetFactor = null; - var currentPolygonOffsetUnits = null; + } else { - var currentScissorTest = null; + if ( v_prev_x < - Number.EPSILON ) { - var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + if ( v_next_x < - Number.EPSILON ) { - var currentTextureSlot = null; - var currentBoundTextures = {}; + direction_eq = true; - var currentScissor = new THREE.Vector4(); - var currentViewport = new THREE.Vector4(); + } - function createTexture( type, target, count ) { + } else { - var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. - var texture = gl.createTexture(); + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { - gl.bindTexture( type, texture ); - gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + direction_eq = true; - for ( var i = 0; i < count; i ++ ) { + } - gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + } - } + } - return texture; + if ( direction_eq ) { - } + // console.log("Warning: lines are a straight sequence"); + v_trans_x = - v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt( v_prev_lensq ); - var emptyTextures = {}; - emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 ); - emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 ); + } else { - // + // console.log("Warning: lines are a straight spike"); + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt( v_prev_lensq / 2 ); - this.init = function () { + } - this.clearColor( 0, 0, 0, 1 ); - this.clearDepth( 1 ); - this.clearStencil( 0 ); + } - this.enable( gl.DEPTH_TEST ); - this.setDepthFunc( THREE.LessEqualDepth ); + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - this.setFlipSided( false ); - this.setCullFace( THREE.CullFaceBack ); - this.enable( gl.CULL_FACE ); + } - this.enable( gl.BLEND ); - this.setBlending( THREE.NormalBlending ); - }; + var contourMovements = []; - this.initAttributes = function () { + for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { + if ( j === il ) j = 0; + if ( k === il ) k = 0; - newAttributes[ i ] = 0; + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) - } + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); - }; + } - this.enableAttribute = function ( attribute ) { + var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); - newAttributes[ attribute ] = 1; + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - if ( enabledAttributes[ attribute ] === 0 ) { + ahole = holes[ h ]; - gl.enableVertexAttribArray( attribute ); - enabledAttributes[ attribute ] = 1; + oneHoleMovements = []; - } + for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - if ( attributeDivisors[ attribute ] !== 0 ) { + if ( j === il ) j = 0; + if ( k === il ) k = 0; - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); - extension.vertexAttribDivisorANGLE( attribute, 0 ); - attributeDivisors[ attribute ] = 0; + } - } + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); - }; + } - this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) { - newAttributes[ attribute ] = 1; + // Loop bevelSegments, 1 for the front, 1 for the back - if ( enabledAttributes[ attribute ] === 0 ) { + for ( b = 0; b < bevelSegments; b ++ ) { - gl.enableVertexAttribArray( attribute ); - enabledAttributes[ attribute ] = 1; + //for ( b = bevelSegments; b > 0; b -- ) { - } + t = b / bevelSegments; + z = bevelThickness * ( 1 - t ); - if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + //z = bevelThickness * t; + bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved + //bs = bevelSize * t; // linear - extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute ); - attributeDivisors[ attribute ] = meshPerAttribute; + // contract shape - } + for ( i = 0, il = contour.length; i < il; i ++ ) { - }; + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - this.disableUnusedAttributes = function () { + v( vert.x, vert.y, - z ); - for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { + } - if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + // expand holes - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - } + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - } + for ( i = 0, il = ahole.length; i < il; i ++ ) { - }; + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - this.enable = function ( id ) { + v( vert.x, vert.y, - z ); - if ( capabilities[ id ] !== true ) { + } - gl.enable( id ); - capabilities[ id ] = true; + } - } + } - }; + bs = bevelSize; - this.disable = function ( id ) { + // Back facing vertices - if ( capabilities[ id ] !== false ) { + for ( i = 0; i < vlen; i ++ ) { - gl.disable( id ); - capabilities[ id ] = false; + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - } + if ( ! extrudeByPath ) { - }; + v( vert.x, vert.y, 0 ); - this.getCompressedTextureFormats = function () { + } else { - if ( compressedTextureFormats === null ) { + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); - compressedTextureFormats = []; + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); - if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || - extensions.get( 'WEBGL_compressed_texture_s3tc' ) || - extensions.get( 'WEBGL_compressed_texture_etc1' ) ) { + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); - var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS ); + v( position2.x, position2.y, position2.z ); - for ( var i = 0; i < formats.length; i ++ ) { + } - compressedTextureFormats.push( formats[ i ] ); + } - } + // Add stepped vertices... + // Including front facing vertices - } + var s; - } + for ( s = 1; s <= steps; s ++ ) { - return compressedTextureFormats; + for ( i = 0; i < vlen; i ++ ) { - }; + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + if ( ! extrudeByPath ) { - if ( blending !== THREE.NoBlending ) { + v( vert.x, vert.y, amount / steps * s ); - this.enable( gl.BLEND ); + } else { - } else { + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); - this.disable( gl.BLEND ); - currentBlending = blending; // no blending, that is - return; + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); - } + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); - if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + v( position2.x, position2.y, position2.z ); - if ( blending === THREE.AdditiveBlending ) { + } - if ( premultipliedAlpha ) { + } - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); + } - } else { - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + // Add bevel segments planes - } + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( b = bevelSegments - 1; b >= 0; b -- ) { - } else if ( blending === THREE.SubtractiveBlending ) { + t = b / bevelSegments; + z = bevelThickness * ( 1 - t ); + //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) ); + bs = bevelSize * Math.sin ( t * Math.PI / 2 ); - if ( premultipliedAlpha ) { + // contract shape - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); + for ( i = 0, il = contour.length; i < il; i ++ ) { - } else { + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, amount + z ); - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); + } - } + // expand holes - } else if ( blending === THREE.MultiplyBlending ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - if ( premultipliedAlpha ) { + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); + for ( i = 0, il = ahole.length; i < il; i ++ ) { - } else { + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); + if ( ! extrudeByPath ) { - } + v( vert.x, vert.y, amount + z ); - } else { + } else { - if ( premultipliedAlpha ) { + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + } - } else { + } - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + } - } + } - } + /* Faces */ - currentBlending = blending; - currentPremultipledAlpha = premultipliedAlpha; + // Top and bottom faces - } + buildLidFaces(); - if ( blending === THREE.CustomBlending ) { + // Sides faces - blendEquationAlpha = blendEquationAlpha || blendEquation; - blendSrcAlpha = blendSrcAlpha || blendSrc; - blendDstAlpha = blendDstAlpha || blendDst; + buildSideFaces(); - if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { - gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); + ///// Internal functions - currentBlendEquation = blendEquation; - currentBlendEquationAlpha = blendEquationAlpha; + function buildLidFaces() { - } + if ( bevelEnabled ) { - if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + var layer = 0; // steps + 1 + var offset = vlen * layer; - gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); + // Bottom faces - currentBlendSrc = blendSrc; - currentBlendDst = blendDst; - currentBlendSrcAlpha = blendSrcAlpha; - currentBlendDstAlpha = blendDstAlpha; + for ( i = 0; i < flen; i ++ ) { - } + face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); - } else { + } - currentBlendEquation = null; - currentBlendSrc = null; - currentBlendDst = null; - currentBlendEquationAlpha = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; + layer = steps + bevelSegments * 2; + offset = vlen * layer; - } + // Top faces - }; + for ( i = 0; i < flen; i ++ ) { - // TODO Deprecate + face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); - this.setColorWrite = function ( colorWrite ) { + } - this.buffers.color.setMask( colorWrite ); + } else { - }; + // Bottom faces - this.setDepthTest = function ( depthTest ) { + for ( i = 0; i < flen; i ++ ) { - this.buffers.depth.setTest( depthTest ); + face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); - }; + } - this.setDepthWrite = function ( depthWrite ) { + // Top faces - this.buffers.depth.setMask( depthWrite ); + for ( i = 0; i < flen; i ++ ) { - }; + face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); - this.setDepthFunc = function ( depthFunc ) { + } - this.buffers.depth.setFunc( depthFunc ); + } - }; + } - this.setStencilTest = function ( stencilTest ) { + // Create faces for the z-sides of the shape - this.buffers.stencil.setTest( stencilTest ); + function buildSideFaces() { - }; + var layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; - this.setStencilWrite = function ( stencilWrite ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - this.buffers.stencil.setMask( stencilWrite ); + ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); - }; + //, true + layeroffset += ahole.length; - this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) { + } - this.buffers.stencil.setFunc( stencilFunc, stencilRef, stencilMask ); + } - }; + function sidewalls( contour, layeroffset ) { - this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) { + var j, k; + i = contour.length; - this.buffers.stencil.setOp( stencilFail, stencilZFail, stencilZPass ); + while ( -- i >= 0 ) { - }; + j = i; + k = i - 1; + if ( k < 0 ) k = contour.length - 1; - // + //console.log('b', i,j, i-1, k,vertices.length); - this.setFlipSided = function ( flipSided ) { + var s = 0, sl = steps + bevelSegments * 2; - if ( currentFlipSided !== flipSided ) { + for ( s = 0; s < sl; s ++ ) { - if ( flipSided ) { + var slen1 = vlen * s; + var slen2 = vlen * ( s + 1 ); - gl.frontFace( gl.CW ); + var a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; - } else { + f4( a, b, c, d, contour, s, sl, j, k ); - gl.frontFace( gl.CCW ); + } - } + } - currentFlipSided = flipSided; + } - } - }; + function v( x, y, z ) { - this.setCullFace = function ( cullFace ) { + scope.vertices.push( new Vector3( x, y, z ) ); - if ( cullFace !== THREE.CullFaceNone ) { + } - this.enable( gl.CULL_FACE ); + function f3( a, b, c ) { - if ( cullFace !== currentCullFace ) { + a += shapesOffset; + b += shapesOffset; + c += shapesOffset; - if ( cullFace === THREE.CullFaceBack ) { + scope.faces.push( new Face3( a, b, c, null, null, 0 ) ); - gl.cullFace( gl.BACK ); + var uvs = uvgen.generateTopUV( scope, a, b, c ); - } else if ( cullFace === THREE.CullFaceFront ) { + scope.faceVertexUvs[ 0 ].push( uvs ); - gl.cullFace( gl.FRONT ); + } - } else { + function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { - gl.cullFace( gl.FRONT_AND_BACK ); + a += shapesOffset; + b += shapesOffset; + c += shapesOffset; + d += shapesOffset; - } + scope.faces.push( new Face3( a, b, d, null, null, 1 ) ); + scope.faces.push( new Face3( b, c, d, null, null, 1 ) ); - } + var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); - } else { + scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); + scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); - this.disable( gl.CULL_FACE ); + } - } + }; - currentCullFace = cullFace; + ExtrudeGeometry.WorldUVGenerator = { - }; + generateTopUV: function ( geometry, indexA, indexB, indexC ) { - this.setLineWidth = function ( width ) { + var vertices = geometry.vertices; - if ( width !== currentLineWidth ) { + var a = vertices[ indexA ]; + var b = vertices[ indexB ]; + var c = vertices[ indexC ]; - gl.lineWidth( width ); + return [ + new Vector2( a.x, a.y ), + new Vector2( b.x, b.y ), + new Vector2( c.x, c.y ) + ]; - currentLineWidth = width; + }, - } + generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) { - }; + var vertices = geometry.vertices; - this.setPolygonOffset = function ( polygonOffset, factor, units ) { + var a = vertices[ indexA ]; + var b = vertices[ indexB ]; + var c = vertices[ indexC ]; + var d = vertices[ indexD ]; - if ( polygonOffset ) { + if ( Math.abs( a.y - b.y ) < 0.01 ) { - this.enable( gl.POLYGON_OFFSET_FILL ); + return [ + new Vector2( a.x, 1 - a.z ), + new Vector2( b.x, 1 - b.z ), + new Vector2( c.x, 1 - c.z ), + new Vector2( d.x, 1 - d.z ) + ]; - if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + } else { - gl.polygonOffset( factor, units ); + return [ + new Vector2( a.y, 1 - a.z ), + new Vector2( b.y, 1 - b.z ), + new Vector2( c.y, 1 - c.z ), + new Vector2( d.y, 1 - d.z ) + ]; - currentPolygonOffsetFactor = factor; - currentPolygonOffsetUnits = units; + } - } + } + }; - } else { + /** + * @author jonobr1 / http://jonobr1.com + * + * Creates a one-sided polygonal geometry from a path shape. Similar to + * ExtrudeGeometry. + * + * parameters = { + * + * curveSegments: , // number of points on the curves. NOT USED AT THE MOMENT. + * + * material: // material index for front and back faces + * uvGenerator: // object that provides UV generator functions + * + * } + **/ - this.disable( gl.POLYGON_OFFSET_FILL ); + function ShapeGeometry ( shapes, options ) { + this.isShapeGeometry = this.isGeometry = true; - } + Geometry.call( this ); - }; + this.type = 'ShapeGeometry'; - this.getScissorTest = function () { + if ( Array.isArray( shapes ) === false ) shapes = [ shapes ]; - return currentScissorTest; + this.addShapeList( shapes, options ); - }; + this.computeFaceNormals(); - this.setScissorTest = function ( scissorTest ) { + }; - currentScissorTest = scissorTest; + ShapeGeometry.prototype = Object.create( Geometry.prototype ); + ShapeGeometry.prototype.constructor = ShapeGeometry; - if ( scissorTest ) { + /** + * Add an array of shapes to THREE.ShapeGeometry. + */ + ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { - this.enable( gl.SCISSOR_TEST ); + for ( var i = 0, l = shapes.length; i < l; i ++ ) { - } else { + this.addShape( shapes[ i ], options ); - this.disable( gl.SCISSOR_TEST ); + } - } + return this; - }; + }; - // texture + /** + * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. + */ + ShapeGeometry.prototype.addShape = function ( shape, options ) { - this.activeTexture = function ( webglSlot ) { + if ( options === undefined ) options = {}; + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; + var material = options.material; + var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; - if ( currentTextureSlot !== webglSlot ) { + // - gl.activeTexture( webglSlot ); - currentTextureSlot = webglSlot; + var i, l, hole; - } + var shapesOffset = this.vertices.length; + var shapePoints = shape.extractPoints( curveSegments ); - }; + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - this.bindTexture = function ( webglType, webglTexture ) { + var reverse = ! exports.ShapeUtils.isClockWise( vertices ); - if ( currentTextureSlot === null ) { + if ( reverse ) { - _this.activeTexture(); + vertices = vertices.reverse(); - } + // Maybe we should also check if holes are in the opposite direction, just to be safe... - var boundTexture = currentBoundTextures[ currentTextureSlot ]; + for ( i = 0, l = holes.length; i < l; i ++ ) { - if ( boundTexture === undefined ) { + hole = holes[ i ]; - boundTexture = { type: undefined, texture: undefined }; - currentBoundTextures[ currentTextureSlot ] = boundTexture; + if ( exports.ShapeUtils.isClockWise( hole ) ) { - } + holes[ i ] = hole.reverse(); - if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + } - gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + } - boundTexture.type = webglType; - boundTexture.texture = webglTexture; + reverse = false; - } + } - }; + var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); - this.compressedTexImage2D = function () { + // Vertices - try { + for ( i = 0, l = holes.length; i < l; i ++ ) { - gl.compressedTexImage2D.apply( gl, arguments ); + hole = holes[ i ]; + vertices = vertices.concat( hole ); - } catch ( error ) { + } - console.error( error ); + // - } + var vert, vlen = vertices.length; + var face, flen = faces.length; - }; + for ( i = 0; i < vlen; i ++ ) { - this.texImage2D = function () { + vert = vertices[ i ]; - try { + this.vertices.push( new Vector3( vert.x, vert.y, 0 ) ); - gl.texImage2D.apply( gl, arguments ); + } - } catch ( error ) { + for ( i = 0; i < flen; i ++ ) { - console.error( error ); + face = faces[ i ]; - } + var a = face[ 0 ] + shapesOffset; + var b = face[ 1 ] + shapesOffset; + var c = face[ 2 ] + shapesOffset; - }; + this.faces.push( new Face3( a, b, c, null, null, material ) ); + this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); - // TODO Deprecate + } - this.clearColor = function ( r, g, b, a ) { + }; - this.buffers.color.setClear( r, g, b, a ); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Defines a 2d shape plane using paths. + **/ - }; + // STEP 1 Create a path. + // STEP 2 Turn path into shape. + // STEP 3 ExtrudeGeometry takes in Shape/Shapes + // STEP 3a - Extract points from each shape, turn to vertices + // STEP 3b - Triangulate each shape, add faces. - this.clearDepth = function ( depth ) { + function Shape () { + this.isShape = true; - this.buffers.depth.setClear( depth ); + Path.apply( this, arguments ); - }; + this.holes = []; - this.clearStencil = function ( stencil ) { + }; - this.buffers.stencil.setClear( stencil ); + Shape.prototype = Object.assign( Object.create( PathPrototype ), { - }; + constructor: Shape, - // + // Convenience method to return ExtrudeGeometry - this.scissor = function ( scissor ) { + extrude: function ( options ) { - if ( currentScissor.equals( scissor ) === false ) { + return new ExtrudeGeometry( this, options ); - gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); - currentScissor.copy( scissor ); + }, - } + // Convenience method to return ShapeGeometry - }; + makeGeometry: function ( options ) { - this.viewport = function ( viewport ) { + return new ShapeGeometry( this, options ); - if ( currentViewport.equals( viewport ) === false ) { + }, - gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); - currentViewport.copy( viewport ); + getPointsHoles: function ( divisions ) { - } + var holesPts = []; - }; + for ( var i = 0, l = this.holes.length; i < l; i ++ ) { - // + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); - this.reset = function () { + } - for ( var i = 0; i < enabledAttributes.length; i ++ ) { + return holesPts; - if ( enabledAttributes[ i ] === 1 ) { + }, - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + // Get points of shape and holes (keypoints based on segments parameter) - } + extractAllPoints: function ( divisions ) { - } + return { - capabilities = {}; + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) - compressedTextureFormats = null; + }; - currentTextureSlot = null; - currentBoundTextures = {}; + }, - currentBlending = null; + extractPoints: function ( divisions ) { - currentFlipSided = null; - currentCullFace = null; + return this.extractAllPoints( divisions ); - this.buffers.color.reset(); - this.buffers.depth.reset(); - this.buffers.stencil.reset(); + } - }; + } ); -}; + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Creates free form 2d path using series of points, lines or curves. + * + **/ -THREE.WebGLColorBuffer = function ( gl, state ) { + function Path ( points ) { + this.isPath = true; - var locked = false; + CurvePath.call( this ); + this.currentPoint = new Vector2(); - var color = new THREE.Vector4(); - var currentColorMask = null; - var currentColorClear = new THREE.Vector4(); + if ( points ) { - this.setMask = function ( colorMask ) { + this.fromPoints( points ); - if ( currentColorMask !== colorMask && ! locked ) { + } - gl.colorMask( colorMask, colorMask, colorMask, colorMask ); - currentColorMask = colorMask; + }; - } + Path.prototype = PathPrototype; + PathPrototype.constructor = Path; - }; - this.setLocked = function ( lock ) { + // minimal class for proxing functions to Path. Replaces old "extractSubpaths()" + function ShapePath() { + this.isShapePath = true; + this.subPaths = []; + this.currentPath = null; + } - locked = lock; + ShapePath.prototype = { + moveTo: function ( x, y ) { + this.currentPath = new Path(); + this.subPaths.push(this.currentPath); + this.currentPath.moveTo( x, y ); + }, + lineTo: function ( x, y ) { + this.currentPath.lineTo( x, y ); + }, + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); + }, + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); + }, + splineThru: function ( pts ) { + this.currentPath.splineThru( pts ); + }, - }; + toShapes: function ( isCCW, noHoles ) { - this.setClear = function ( r, g, b, a ) { + function toShapesNoHoles( inSubpaths ) { - color.set( r, g, b, a ); + var shapes = []; - if ( currentColorClear.equals( color ) === false ) { + for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { - gl.clearColor( r, g, b, a ); - currentColorClear.copy( color ); + var tmpPath = inSubpaths[ i ]; - } + var tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; - }; + shapes.push( tmpShape ); - this.reset = function () { + } - locked = false; + return shapes; - currentColorMask = null; - currentColorClear = new THREE.Vector4(); + } - }; + function isPointInsidePolygon( inPt, inPolygon ) { -}; + var polyLen = inPolygon.length; -THREE.WebGLDepthBuffer = function( gl, state ) { + // inPt on polygon contour => immediate success or + // toggling of inside/outside at every single! intersection point of an edge + // with the horizontal line through inPt, left of inPt + // not counting lowerY endpoints of edges and whole edges on that line + var inside = false; + for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { - var locked = false; + var edgeLowPt = inPolygon[ p ]; + var edgeHighPt = inPolygon[ q ]; - var currentDepthMask = null; - var currentDepthFunc = null; - var currentDepthClear = null; + var edgeDx = edgeHighPt.x - edgeLowPt.x; + var edgeDy = edgeHighPt.y - edgeLowPt.y; - this.setTest = function ( depthTest ) { + if ( Math.abs( edgeDy ) > Number.EPSILON ) { - if ( depthTest ) { + // not parallel + if ( edgeDy < 0 ) { - state.enable( gl.DEPTH_TEST ); + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; - } else { + } + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; - state.disable( gl.DEPTH_TEST ); + if ( inPt.y === edgeLowPt.y ) { - } + if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? + // continue; // no intersection or edgeLowPt => doesn't count !!! - }; + } else { - this.setMask = function( depthMask ){ + var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y ); + if ( perpEdge === 0 ) return true; // inPt is on contour ? + if ( perpEdge < 0 ) continue; + inside = ! inside; // true intersection left of inPt - if ( currentDepthMask !== depthMask && ! locked ) { + } - gl.depthMask( depthMask ); - currentDepthMask = depthMask; + } else { - } + // parallel or collinear + if ( inPt.y !== edgeLowPt.y ) continue; // parallel + // edge lies on the same horizontal line as inPt + if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || + ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! + // continue; - }; + } - this.setFunc = function ( depthFunc ) { + } - if ( currentDepthFunc !== depthFunc ) { + return inside; - if ( depthFunc ) { + } - switch ( depthFunc ) { + var isClockWise = exports.ShapeUtils.isClockWise; - case THREE.NeverDepth: + var subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; - gl.depthFunc( gl.NEVER ); - break; + if ( noHoles === true ) return toShapesNoHoles( subPaths ); - case THREE.AlwaysDepth: - gl.depthFunc( gl.ALWAYS ); - break; + var solid, tmpPath, tmpShape, shapes = []; - case THREE.LessDepth: + if ( subPaths.length === 1 ) { - gl.depthFunc( gl.LESS ); - break; + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; - case THREE.LessEqualDepth: + } - gl.depthFunc( gl.LEQUAL ); - break; + var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; - case THREE.EqualDepth: + // console.log("Holes first", holesFirst); - gl.depthFunc( gl.EQUAL ); - break; + var betterShapeHoles = []; + var newShapes = []; + var newShapeHoles = []; + var mainIdx = 0; + var tmpPoints; - case THREE.GreaterEqualDepth: + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; - gl.depthFunc( gl.GEQUAL ); - break; + for ( var i = 0, l = subPaths.length; i < l; i ++ ) { - case THREE.GreaterDepth: + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; - gl.depthFunc( gl.GREATER ); - break; + if ( solid ) { - case THREE.NotEqualDepth: + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; - gl.depthFunc( gl.NOTEQUAL ); - break; + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; - default: + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; - gl.depthFunc( gl.LEQUAL ); + //console.log('cw', i); - } + } else { - } else { + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); - gl.depthFunc( gl.LEQUAL ); + //console.log('ccw', i); - } + } - currentDepthFunc = depthFunc; + } - } + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); - }; - this.setLocked = function ( lock ) { + if ( newShapes.length > 1 ) { - locked = lock; + var ambiguous = false; + var toChange = []; - }; + for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - this.setClear = function ( depth ) { + betterShapeHoles[ sIdx ] = []; - if ( currentDepthClear !== depth ) { + } - gl.clearDepth( depth ); - currentDepthClear = depth; + for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - } + var sho = newShapeHoles[ sIdx ]; - }; + for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { - this.reset = function () { + var ho = sho[ hIdx ]; + var hole_unassigned = true; - locked = false; + for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { - currentDepthMask = null; - currentDepthFunc = null; - currentDepthClear = null; + if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { - }; + if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); + if ( hole_unassigned ) { -}; + hole_unassigned = false; + betterShapeHoles[ s2Idx ].push( ho ); -THREE.WebGLStencilBuffer = function ( gl, state ) { + } else { - var locked = false; + ambiguous = true; - var currentStencilMask = null; - var currentStencilFunc = null; - var currentStencilRef = null; - var currentStencilFuncMask = null; - var currentStencilFail = null; - var currentStencilZFail = null; - var currentStencilZPass = null; - var currentStencilClear = null; + } - this.setTest = function ( stencilTest ) { + } - if ( stencilTest ) { + } + if ( hole_unassigned ) { - state.enable( gl.STENCIL_TEST ); + betterShapeHoles[ sIdx ].push( ho ); - } else { + } - state.disable( gl.STENCIL_TEST ); + } - } + } + // console.log("ambiguous: ", ambiguous); + if ( toChange.length > 0 ) { - }; + // console.log("to change: ", toChange); + if ( ! ambiguous ) newShapeHoles = betterShapeHoles; - this.setMask = function ( stencilMask ) { + } - if ( currentStencilMask !== stencilMask && ! locked ) { + } - gl.stencilMask( stencilMask ); - currentStencilMask = stencilMask; + var tmpHoles; - } + for ( var i = 0, il = newShapes.length; i < il; i ++ ) { - }; + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; - this.setFunc = function ( stencilFunc, stencilRef, stencilMask ) { + for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { - if ( currentStencilFunc !== stencilFunc || - currentStencilRef !== stencilRef || - currentStencilFuncMask !== stencilMask ) { + tmpShape.holes.push( tmpHoles[ j ].h ); - gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + } - currentStencilFunc = stencilFunc; - currentStencilRef = stencilRef; - currentStencilFuncMask = stencilMask; + } - } + //console.log("shape", shapes); - }; + return shapes; - this.setOp = function ( stencilFail, stencilZFail, stencilZPass ) { + } + } - if ( currentStencilFail !== stencilFail || - currentStencilZFail !== stencilZFail || - currentStencilZPass !== stencilZPass ) { + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author mrdoob / http://mrdoob.com/ + */ - gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + function Font ( data ) { + this.isFont = true; - currentStencilFail = stencilFail; - currentStencilZFail = stencilZFail; - currentStencilZPass = stencilZPass; + this.data = data; - } + }; - }; + Object.assign( Font.prototype, { - this.setLocked = function ( lock ) { + generateShapes: function ( text, size, divisions ) { - locked = lock; + function createPaths( text ) { - }; + var chars = String( text ).split( '' ); + var scale = size / data.resolution; + var offset = 0; - this.setClear = function ( stencil ) { + var paths = []; - if ( currentStencilClear !== stencil ) { + for ( var i = 0; i < chars.length; i ++ ) { - gl.clearStencil( stencil ); - currentStencilClear = stencil; + var ret = createPath( chars[ i ], scale, offset ); + offset += ret.offset; - } + paths.push( ret.path ); - }; + } - this.reset = function () { + return paths; - locked = false; + } - currentStencilMask = null; - currentStencilFunc = null; - currentStencilRef = null; - currentStencilFuncMask = null; - currentStencilFail = null; - currentStencilZFail = null; - currentStencilZPass = null; - currentStencilClear = null; + function createPath( c, scale, offset ) { - }; + var glyph = data.glyphs[ c ] || data.glyphs[ '?' ]; -}; + if ( ! glyph ) return; -// File:src/renderers/webgl/WebGLTextures.js + var path = new ShapePath(); -/** -* @author mrdoob / http://mrdoob.com/ -*/ + var pts = [], b2 = exports.ShapeUtils.b2, b3 = exports.ShapeUtils.b3; + var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; -THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { + if ( glyph.o ) { - var _infoMemory = info.memory; - var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); + var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - // + for ( var i = 0, l = outline.length; i < l; ) { - function clampToMaxSize ( image, maxSize ) { + var action = outline[ i ++ ]; - if ( image.width > maxSize || image.height > maxSize ) { + switch ( action ) { - // Warning: Scaling through the canvas will only work with images that use - // premultiplied alpha. + case 'm': // moveTo - var scale = maxSize / Math.max( image.width, image.height ); + x = outline[ i ++ ] * scale + offset; + y = outline[ i ++ ] * scale; - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = Math.floor( image.width * scale ); - canvas.height = Math.floor( image.height * scale ); + path.moveTo( x, y ); - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); + break; - console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); + case 'l': // lineTo - return canvas; + x = outline[ i ++ ] * scale + offset; + y = outline[ i ++ ] * scale; - } + path.lineTo( x, y ); - return image; + break; - } + case 'q': // quadraticCurveTo - function isPowerOfTwo( image ) { + cpx = outline[ i ++ ] * scale + offset; + cpy = outline[ i ++ ] * scale; + cpx1 = outline[ i ++ ] * scale + offset; + cpy1 = outline[ i ++ ] * scale; - return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ); + path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); - } + laste = pts[ pts.length - 1 ]; - function makePowerOfTwo( image ) { + if ( laste ) { - if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { + cpx0 = laste.x; + cpy0 = laste.y; - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = THREE.Math.nearestPowerOfTwo( image.width ); - canvas.height = THREE.Math.nearestPowerOfTwo( image.height ); + for ( var i2 = 1; i2 <= divisions; i2 ++ ) { - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, canvas.width, canvas.height ); + var t = i2 / divisions; + b2( t, cpx0, cpx1, cpx ); + b2( t, cpy0, cpy1, cpy ); - console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); + } - return canvas; + } - } + break; - return image; + case 'b': // bezierCurveTo - } + cpx = outline[ i ++ ] * scale + offset; + cpy = outline[ i ++ ] * scale; + cpx1 = outline[ i ++ ] * scale + offset; + cpy1 = outline[ i ++ ] * scale; + cpx2 = outline[ i ++ ] * scale + offset; + cpy2 = outline[ i ++ ] * scale; - function textureNeedsPowerOfTwo( texture ) { + path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); - if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true; - if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true; + laste = pts[ pts.length - 1 ]; - return false; + if ( laste ) { - } + cpx0 = laste.x; + cpy0 = laste.y; - // Fallback filters for non-power-of-2 textures + for ( var i2 = 1; i2 <= divisions; i2 ++ ) { - function filterFallback ( f ) { + var t = i2 / divisions; + b3( t, cpx0, cpx1, cpx2, cpx ); + b3( t, cpy0, cpy1, cpy2, cpy ); - if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { + } - return _gl.NEAREST; + } - } + break; - return _gl.LINEAR; + } - } + } - // + } - function onTextureDispose( event ) { + return { offset: glyph.ha * scale, path: path }; - var texture = event.target; + } - texture.removeEventListener( 'dispose', onTextureDispose ); + // - deallocateTexture( texture ); + if ( size === undefined ) size = 100; + if ( divisions === undefined ) divisions = 4; - _infoMemory.textures --; + var data = this.data; + var paths = createPaths( text ); + var shapes = []; - } + for ( var p = 0, pl = paths.length; p < pl; p ++ ) { - function onRenderTargetDispose( event ) { + Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); - var renderTarget = event.target; + } - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + return shapes; - deallocateRenderTarget( renderTarget ); + } - _infoMemory.textures --; + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - // + function FontLoader ( manager ) { + this.isFontLoader = true; - function deallocateTexture( texture ) { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - var textureProperties = properties.get( texture ); + }; - if ( texture.image && textureProperties.__image__webglTextureCube ) { + Object.assign( FontLoader.prototype, { - // cube texture + load: function ( url, onLoad, onProgress, onError ) { - _gl.deleteTexture( textureProperties.__image__webglTextureCube ); + var scope = this; - } else { + var loader = new XHRLoader( this.manager ); + loader.load( url, function ( text ) { - // 2D texture + var json; - if ( textureProperties.__webglInit === undefined ) return; + try { - _gl.deleteTexture( textureProperties.__webglTexture ); + json = JSON.parse( text ); - } + } catch ( e ) { - // remove all webgl properties - properties.delete( texture ); + console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); + json = JSON.parse( text.substring( 65, text.length - 2 ) ); - } + } - function deallocateRenderTarget( renderTarget ) { + var font = scope.parse( json ); - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + if ( onLoad ) onLoad( font ); - if ( ! renderTarget ) return; + }, onProgress, onError ); - if ( textureProperties.__webglTexture !== undefined ) { + }, - _gl.deleteTexture( textureProperties.__webglTexture ); + parse: function ( json ) { - } + return new Font( json ); - if ( renderTarget.depthTexture ) { + } - renderTarget.depthTexture.dispose(); + } ); - } + var context; - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { + function getAudioContext () { + if ( context === undefined ) { + context = new ( window.AudioContext || window.webkitAudioContext )(); + } - for ( var i = 0; i < 6; i ++ ) { + return context; + } - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + /** + * @author Reece Aaron Lecrivain / http://reecenotes.com/ + */ - } + function AudioLoader ( manager ) { + this.isAudioLoader = true; - } else { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + }; - } + Object.assign( AudioLoader.prototype, { - properties.delete( renderTarget.texture ); - properties.delete( renderTarget ); + load: function ( url, onLoad, onProgress, onError ) { - } + var loader = new XHRLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.load( url, function ( buffer ) { - // + var context = getAudioContext(); + context.decodeAudioData( buffer, function ( audioBuffer ) { + onLoad( audioBuffer ); - function setTexture2D( texture, slot ) { + } ); - var textureProperties = properties.get( texture ); + }, onProgress, onError ); - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + } - var image = texture.image; + } ); - if ( image === undefined ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); + function StereoCamera () { + this.isStereoCamera = true; - } else if ( image.complete === false ) { + this.type = 'StereoCamera'; - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); + this.aspect = 1; - } else { + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; - uploadTexture( textureProperties, texture, slot ); - return; + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; - } + }; - } + Object.assign( StereoCamera.prototype, { - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + update: ( function () { - } + var focus, fov, aspect, near, far; - function setTextureCube ( texture, slot ) { + var eyeRight = new Matrix4(); + var eyeLeft = new Matrix4(); - var textureProperties = properties.get( texture ); + return function update( camera ) { - if ( texture.image.length === 6 ) { + var needsUpdate = focus !== camera.focus || fov !== camera.fov || + aspect !== camera.aspect * this.aspect || near !== camera.near || + far !== camera.far; - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + if ( needsUpdate ) { - if ( ! textureProperties.__image__webglTextureCube ) { + focus = camera.focus; + fov = camera.fov; + aspect = camera.aspect * this.aspect; + near = camera.near; + far = camera.far; - texture.addEventListener( 'dispose', onTextureDispose ); + // Off-axis stereoscopic effect based on + // http://paulbourke.net/stereographics/stereorender/ - textureProperties.__image__webglTextureCube = _gl.createTexture(); + var projectionMatrix = camera.projectionMatrix.clone(); + var eyeSep = 0.064 / 2; + var eyeSepOnProjection = eyeSep * near / focus; + var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); + var xmin, xmax; - _infoMemory.textures ++; + // translate xOffset - } + eyeLeft.elements[ 12 ] = - eyeSep; + eyeRight.elements[ 12 ] = eyeSep; - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); + // for left eye - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + xmin = - ymax * aspect + eyeSepOnProjection; + xmax = ymax * aspect + eyeSepOnProjection; - var isCompressed = texture instanceof THREE.CompressedTexture; - var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture; + projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); + projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - var cubeImage = []; + this.cameraL.projectionMatrix.copy( projectionMatrix ); - for ( var i = 0; i < 6; i ++ ) { + // for right eye - if ( ! isCompressed && ! isDataTexture ) { + xmin = - ymax * aspect - eyeSepOnProjection; + xmax = ymax * aspect - eyeSepOnProjection; - cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); + projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); + projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - } else { + this.cameraR.projectionMatrix.copy( projectionMatrix ); - cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + } - } + this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft ); + this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight ); - } + }; - var image = cubeImage[ 0 ], - isPowerOfTwoImage = isPowerOfTwo( image ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + } )() - setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); + } ); - for ( var i = 0; i < 6; i ++ ) { + /** + * Camera for rendering cube maps + * - renders scene into axis-aligned cube + * + * @author alteredq / http://alteredqualia.com/ + */ - if ( ! isCompressed ) { + function CubeCamera ( near, far, cubeResolution ) { + this.isCubeCamera = this.isObject3D = true; - if ( isDataTexture ) { + Object3D.call( this ); - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + this.type = 'CubeCamera'; - } else { + var fov = 90, aspect = 1; - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); + var cameraPX = new PerspectiveCamera( fov, aspect, near, far ); + cameraPX.up.set( 0, - 1, 0 ); + cameraPX.lookAt( new Vector3( 1, 0, 0 ) ); + this.add( cameraPX ); - } + var cameraNX = new PerspectiveCamera( fov, aspect, near, far ); + cameraNX.up.set( 0, - 1, 0 ); + cameraNX.lookAt( new Vector3( - 1, 0, 0 ) ); + this.add( cameraNX ); - } else { + var cameraPY = new PerspectiveCamera( fov, aspect, near, far ); + cameraPY.up.set( 0, 0, 1 ); + cameraPY.lookAt( new Vector3( 0, 1, 0 ) ); + this.add( cameraPY ); - var mipmap, mipmaps = cubeImage[ i ].mipmaps; + var cameraNY = new PerspectiveCamera( fov, aspect, near, far ); + cameraNY.up.set( 0, 0, - 1 ); + cameraNY.lookAt( new Vector3( 0, - 1, 0 ) ); + this.add( cameraNY ); - for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { + var cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.up.set( 0, - 1, 0 ); + cameraPZ.lookAt( new Vector3( 0, 0, 1 ) ); + this.add( cameraPZ ); - mipmap = mipmaps[ j ]; + var cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.up.set( 0, - 1, 0 ); + cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) ); + this.add( cameraNZ ); - if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { + var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter }; - if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { + this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); - state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + this.updateCubeMap = function ( renderer, scene ) { - } else { + if ( this.parent === null ) this.updateMatrixWorld(); - console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" ); + var renderTarget = this.renderTarget; + var generateMipmaps = renderTarget.texture.generateMipmaps; - } + renderTarget.texture.generateMipmaps = false; - } else { + renderTarget.activeCubeFace = 0; + renderer.render( scene, cameraPX, renderTarget ); - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + renderTarget.activeCubeFace = 1; + renderer.render( scene, cameraNX, renderTarget ); - } + renderTarget.activeCubeFace = 2; + renderer.render( scene, cameraPY, renderTarget ); - } + renderTarget.activeCubeFace = 3; + renderer.render( scene, cameraNY, renderTarget ); - } + renderTarget.activeCubeFace = 4; + renderer.render( scene, cameraPZ, renderTarget ); - } + renderTarget.texture.generateMipmaps = generateMipmaps; - if ( texture.generateMipmaps && isPowerOfTwoImage ) { + renderTarget.activeCubeFace = 5; + renderer.render( scene, cameraNZ, renderTarget ); - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + renderer.setRenderTarget( null ); - } + }; - textureProperties.__version = texture.version; + }; - if ( texture.onUpdate ) texture.onUpdate( texture ); + CubeCamera.prototype = Object.create( Object3D.prototype ); + CubeCamera.prototype.constructor = CubeCamera; - } else { + /** + * @author mrdoob / http://mrdoob.com/ + */ - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); + function AudioListener () { + this.isAudioListener = true; - } + Object3D.call( this ); - } + this.type = 'AudioListener'; - } + this.context = getAudioContext(); - function setTextureCubeDynamic ( texture, slot ) { + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); + this.filter = null; - } + }; - function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) { + AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { - var extension; + constructor: AudioListener, - if ( isPowerOfTwoImage ) { + getInput: function () { - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); + return this.gain; - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); + }, - } else { + removeFilter: function ( ) { - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + if ( this.filter !== null ) { - if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) { + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); + } - } + }, - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); + getFilter: function () { - if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) { + return this.filter; - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); + }, - } + setFilter: function ( value ) { - } + if ( this.filter !== null ) { - extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); - if ( extension ) { + } else { - if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; - if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; + this.gain.disconnect( this.context.destination ); - if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + } - _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); - properties.get( texture ).__currentAnisotropy = texture.anisotropy; + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); - } + }, - } + getMasterVolume: function () { - } + return this.gain.gain.value; - function uploadTexture( textureProperties, texture, slot ) { + }, - if ( textureProperties.__webglInit === undefined ) { + setMasterVolume: function ( value ) { - textureProperties.__webglInit = true; + this.gain.gain.value = value; - texture.addEventListener( 'dispose', onTextureDispose ); + }, - textureProperties.__webglTexture = _gl.createTexture(); + updateMatrixWorld: ( function () { - _infoMemory.textures ++; + var position = new Vector3(); + var quaternion = new Quaternion(); + var scale = new Vector3(); - } + var orientation = new Vector3(); - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + return function updateMatrixWorld( force ) { - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); - _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + Object3D.prototype.updateMatrixWorld.call( this, force ); - var image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); + var listener = this.context.listener; + var up = this.up; - if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { + this.matrixWorld.decompose( position, quaternion, scale ); - image = makePowerOfTwo( image ); + orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - } + listener.setPosition( position.x, position.y, position.z ); + listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z ); - var isPowerOfTwoImage = isPowerOfTwo( image ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + }; - setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); + } )() - var mipmap, mipmaps = texture.mipmaps; + } ); - if ( texture instanceof THREE.DepthTexture ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author Reece Aaron Lecrivain / http://reecenotes.com/ + */ - // populate depth texture with dummy data + function Audio ( listener ) { + this.isAudio = true; - var internalFormat = _gl.DEPTH_COMPONENT; + Object3D.call( this ); - if ( texture.type === THREE.FloatType ) { + this.type = 'Audio'; - if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); - internalFormat = _gl.DEPTH_COMPONENT32F; + this.context = listener.context; + this.source = this.context.createBufferSource(); + this.source.onended = this.onEnded.bind( this ); - } else if ( _isWebGL2 ) { + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); - // WebGL 2.0 requires signed internalformat for glTexImage2D - internalFormat = _gl.DEPTH_COMPONENT16; + this.autoplay = false; - } + this.startTime = 0; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.sourceType = 'empty'; - state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); + this.filters = []; - } else if ( texture instanceof THREE.DataTexture ) { + }; - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { - if ( mipmaps.length > 0 && isPowerOfTwoImage ) { + constructor: Audio, - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + getOutput: function () { - mipmap = mipmaps[ i ]; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + return this.gain; - } + }, - texture.generateMipmaps = false; + setNodeSource: function ( audioNode ) { - } else { + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); - state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); + return this; - } + }, - } else if ( texture instanceof THREE.CompressedTexture ) { + setBuffer: function ( audioBuffer ) { - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + this.source.buffer = audioBuffer; + this.sourceType = 'buffer'; - mipmap = mipmaps[ i ]; + if ( this.autoplay ) this.play(); - if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { + return this; - if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { + }, - state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + play: function () { - } else { + if ( this.isPlaying === true ) { - console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); + console.warn( 'THREE.Audio: Audio is already playing.' ); + return; - } + } - } else { + if ( this.hasPlaybackControl === false ) { - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - } + } - } + var source = this.context.createBufferSource(); - } else { + source.buffer = this.source.buffer; + source.loop = this.source.loop; + source.onended = this.source.onended; + source.start( 0, this.startTime ); + source.playbackRate.value = this.playbackRate; - // regular Texture (image, video, canvas) + this.isPlaying = true; - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + this.source = source; - if ( mipmaps.length > 0 && isPowerOfTwoImage ) { + return this.connect(); - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + }, - mipmap = mipmaps[ i ]; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); + pause: function () { - } + if ( this.hasPlaybackControl === false ) { - texture.generateMipmaps = false; + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - } else { + } - state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); + this.source.stop(); + this.startTime = this.context.currentTime; + this.isPlaying = false; - } + return this; - } + }, - if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D ); + stop: function () { - textureProperties.__version = texture.version; + if ( this.hasPlaybackControl === false ) { - if ( texture.onUpdate ) texture.onUpdate( texture ); + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - } + } - // Render targets + this.source.stop(); + this.startTime = 0; + this.isPlaying = false; - // Setup storage for target texture and bind it to correct framebuffer - function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) { + return this; - var glFormat = paramThreeToGL( renderTarget.texture.format ); - var glType = paramThreeToGL( renderTarget.texture.type ); - state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + }, - } + connect: function () { - // Setup storage for internal depth/stencil buffers and bind to correct framebuffer - function setupRenderBufferStorage ( renderbuffer, renderTarget ) { + if ( this.filters.length > 0 ) { - _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + this.source.connect( this.filters[ 0 ] ); - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + for ( var i = 1, l = this.filters.length; i < l; i ++ ) { - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + this.filters[ i - 1 ].connect( this.filters[ i ] ); - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + } - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); - } else { + } else { - // FIXME: We don't support !depth !stencil - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); + this.source.connect( this.getOutput() ); - } + } - _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + return this; - } + }, - // Setup resources for a Depth Texture for a FBO (needs an extension) - function setupDepthTexture ( framebuffer, renderTarget ) { + disconnect: function () { - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); - if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); + if ( this.filters.length > 0 ) { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + this.source.disconnect( this.filters[ 0 ] ); - if ( !( renderTarget.depthTexture instanceof THREE.DepthTexture ) ) { + for ( var i = 1, l = this.filters.length; i < l; i ++ ) { - throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); - } + } - // upload an empty depth texture with framebuffer size - if ( !properties.get( renderTarget.depthTexture ).__webglTexture || - renderTarget.depthTexture.image.width !== renderTarget.width || - renderTarget.depthTexture.image.height !== renderTarget.height ) { - renderTarget.depthTexture.image.width = renderTarget.width; - renderTarget.depthTexture.image.height = renderTarget.height; - renderTarget.depthTexture.needsUpdate = true; - } + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); - setTexture2D( renderTarget.depthTexture, 0 ); + } else { - var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + this.source.disconnect( this.getOutput() ); - } + } - // Setup GL resources for a non-texture depth buffer - function setupDepthRenderbuffer( renderTarget ) { + return this; - var renderTargetProperties = properties.get( renderTarget ); + }, - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + getFilters: function () { - if ( renderTarget.depthTexture ) { + return this.filters; - if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets'); + }, - setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + setFilters: function ( value ) { - } else { + if ( ! value ) value = []; - if ( isCube ) { + if ( this.isPlaying === true ) { - renderTargetProperties.__webglDepthbuffer = []; + this.disconnect(); + this.filters = value; + this.connect(); - for ( var i = 0; i < 6; i ++ ) { + } else { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); - renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); + this.filters = value; - } + } - } else { + return this; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); - renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); + }, - } + getFilter: function () { - } + return this.getFilters()[ 0 ]; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + }, - } + setFilter: function ( filter ) { - // Set up GL resources for the render target - function setupRenderTarget( renderTarget ) { + return this.setFilters( filter ? [ filter ] : [] ); - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + }, - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + setPlaybackRate: function ( value ) { - textureProperties.__webglTexture = _gl.createTexture(); + if ( this.hasPlaybackControl === false ) { - _infoMemory.textures ++; + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); - var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); + } - // Setup framebuffer + this.playbackRate = value; - if ( isCube ) { + if ( this.isPlaying === true ) { - renderTargetProperties.__webglFramebuffer = []; + this.source.playbackRate.value = this.playbackRate; - for ( var i = 0; i < 6; i ++ ) { + } - renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + return this; - } + }, - } else { + getPlaybackRate: function () { - renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + return this.playbackRate; - } + }, - // Setup color buffer + onEnded: function () { - if ( isCube ) { + this.isPlaying = false; - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); + }, - for ( var i = 0; i < 6; i ++ ) { + getLoop: function () { - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); + if ( this.hasPlaybackControl === false ) { - } + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return false; - if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); + } - } else { + return this.source.loop; - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); + }, - if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); - state.bindTexture( _gl.TEXTURE_2D, null ); + setLoop: function ( value ) { - } + if ( this.hasPlaybackControl === false ) { - // Setup depth and stencil buffers + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - if ( renderTarget.depthBuffer ) { + } - setupDepthRenderbuffer( renderTarget ); + this.source.loop = value; - } + }, - } + getVolume: function () { - function updateRenderTargetMipmap( renderTarget ) { + return this.gain.gain.value; - var texture = renderTarget.texture; + }, - if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && - texture.minFilter !== THREE.NearestFilter && - texture.minFilter !== THREE.LinearFilter ) { - var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; - var webglTexture = properties.get( texture ).__webglTexture; + setVolume: function ( value ) { - state.bindTexture( target, webglTexture ); - _gl.generateMipmap( target ); - state.bindTexture( target, null ); + this.gain.gain.value = value; - } + return this; - } + } - this.setTexture2D = setTexture2D; - this.setTextureCube = setTextureCube; - this.setTextureCubeDynamic = setTextureCubeDynamic; - this.setupRenderTarget = setupRenderTarget; - this.updateRenderTargetMipmap = updateRenderTargetMipmap; + } ); -}; + /** + * @author mrdoob / http://mrdoob.com/ + */ -// File:src/renderers/webgl/WebGLUniforms.js + function PositionalAudio ( listener ) { + this.isPositionalAudio = true; -/** - * - * Uniforms of a program. - * Those form a tree structure with a special top-level container for the root, - * which you get by calling 'new WebGLUniforms( gl, program, renderer )'. - * - * - * Properties of inner nodes including the top-level container: - * - * .seq - array of nested uniforms - * .map - nested uniforms by name - * - * - * Methods of all nodes except the top-level container: - * - * .setValue( gl, value, [renderer] ) - * - * uploads a uniform value(s) - * the 'renderer' parameter is needed for sampler uniforms - * - * - * Static methods of the top-level container (renderer factorizations): - * - * .upload( gl, seq, values, renderer ) - * - * sets uniforms in 'seq' to 'values[id].value' - * - * .seqWithValue( seq, values ) : filteredSeq - * - * filters 'seq' entries with corresponding entry in values - * - * .splitDynamic( seq, values ) : filteredSeq - * - * filters 'seq' entries with dynamic entry and removes them from 'seq' - * - * - * Methods of the top-level container (renderer factorizations): - * - * .setValue( gl, name, value ) - * - * sets uniform with name 'name' to 'value' - * - * .set( gl, obj, prop ) - * - * sets uniform from object and property with same name than uniform - * - * .setOptional( gl, obj, prop ) - * - * like .set for an optional property of the object - * - * - * @author tschw - * - */ + Audio.call( this, listener ); -THREE.WebGLUniforms = ( function() { // scope + this.panner = this.context.createPanner(); + this.panner.connect( this.gain ); - var emptyTexture = new THREE.Texture(); - var emptyCubeTexture = new THREE.CubeTexture(); + }; - // --- Base for inner nodes (including the root) --- + PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { - var UniformContainer = function() { + constructor: PositionalAudio, - this.seq = []; - this.map = {}; + getOutput: function () { - }, + return this.panner; - // --- Utilities --- + }, - // Array Caches (provide typed arrays for temporary by size) + getRefDistance: function () { - arrayCacheF32 = [], - arrayCacheI32 = [], + return this.panner.refDistance; - uncacheTemporaryArrays = function() { + }, - arrayCacheF32.length = 0; - arrayCacheI32.length = 0; + setRefDistance: function ( value ) { - }, + this.panner.refDistance = value; - // Flattening for arrays of vectors and matrices + }, - flatten = function( array, nBlocks, blockSize ) { + getRolloffFactor: function () { - var firstElem = array[ 0 ]; + return this.panner.rolloffFactor; - if ( firstElem <= 0 || firstElem > 0 ) return array; - // unoptimized: ! isNaN( firstElem ) - // see http://jacksondunstan.com/articles/983 + }, - var n = nBlocks * blockSize, - r = arrayCacheF32[ n ]; + setRolloffFactor: function ( value ) { - if ( r === undefined ) { + this.panner.rolloffFactor = value; - r = new Float32Array( n ); - arrayCacheF32[ n ] = r; + }, - } + getDistanceModel: function () { - if ( nBlocks !== 0 ) { + return this.panner.distanceModel; - firstElem.toArray( r, 0 ); + }, - for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { + setDistanceModel: function ( value ) { - offset += blockSize; - array[ i ].toArray( r, offset ); + this.panner.distanceModel = value; - } + }, - } + getMaxDistance: function () { - return r; + return this.panner.maxDistance; - }, + }, - // Texture unit allocation + setMaxDistance: function ( value ) { - allocTexUnits = function( renderer, n ) { + this.panner.maxDistance = value; - var r = arrayCacheI32[ n ]; + }, - if ( r === undefined ) { + updateMatrixWorld: ( function () { - r = new Int32Array( n ); - arrayCacheI32[ n ] = r; + var position = new Vector3(); - } + return function updateMatrixWorld( force ) { - for ( var i = 0; i !== n; ++ i ) - r[ i ] = renderer.allocTextureUnit(); + Object3D.prototype.updateMatrixWorld.call( this, force ); - return r; + position.setFromMatrixPosition( this.matrixWorld ); - }, + this.panner.setPosition( position.x, position.y, position.z ); - // --- Setters --- + }; - // Note: Defining these methods externally, because they come in a bunch - // and this way their names minify. + } )() - // Single scalar - setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); }, - setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); }, + } ); - // Single float vector (from flat array or THREE.VectorN) + /** + * @author mrdoob / http://mrdoob.com/ + */ - setValue2fv = function( gl, v ) { + function AudioAnalyser ( audio, fftSize ) { + this.isAudioAnalyser = true; - if ( v.x === undefined ) gl.uniform2fv( this.addr, v ); - else gl.uniform2f( this.addr, v.x, v.y ); + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; - }, + this.data = new Uint8Array( this.analyser.frequencyBinCount ); - setValue3fv = function( gl, v ) { + audio.getOutput().connect( this.analyser ); - if ( v.x !== undefined ) - gl.uniform3f( this.addr, v.x, v.y, v.z ); - else if ( v.r !== undefined ) - gl.uniform3f( this.addr, v.r, v.g, v.b ); - else - gl.uniform3fv( this.addr, v ); + }; - }, + Object.assign( AudioAnalyser.prototype, { - setValue4fv = function( gl, v ) { + getFrequencyData: function () { - if ( v.x === undefined ) gl.uniform4fv( this.addr, v ); - else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + this.analyser.getByteFrequencyData( this.data ); - }, + return this.data; - // Single matrix (from flat array or MatrixN) + }, - setValue2fm = function( gl, v ) { + getAverageFrequency: function () { - gl.uniformMatrix2fv( this.addr, false, v.elements || v ); + var value = 0, data = this.getFrequencyData(); - }, + for ( var i = 0; i < data.length; i ++ ) { - setValue3fm = function( gl, v ) { + value += data[ i ]; - gl.uniformMatrix3fv( this.addr, false, v.elements || v ); + } - }, + return value / data.length; - setValue4fm = function( gl, v ) { + } - gl.uniformMatrix4fv( this.addr, false, v.elements || v ); + } ); - }, + /** + * + * Buffered scene graph property that allows weighted accumulation. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - // Single texture (2D / Cube) + function PropertyMixer ( binding, typeName, valueSize ) { + this.isPropertyMixer = true; - setValueT1 = function( gl, v, renderer ) { + this.binding = binding; + this.valueSize = valueSize; - var unit = renderer.allocTextureUnit(); - gl.uniform1i( this.addr, unit ); - renderer.setTexture2D( v || emptyTexture, unit ); + var bufferType = Float64Array, + mixFunction; - }, + switch ( typeName ) { - setValueT6 = function( gl, v, renderer ) { + case 'quaternion': mixFunction = this._slerp; break; - var unit = renderer.allocTextureUnit(); - gl.uniform1i( this.addr, unit ); - renderer.setTextureCube( v || emptyCubeTexture, unit ); + case 'string': + case 'bool': - }, + bufferType = Array, mixFunction = this._select; break; - // Integer / Boolean vectors or arrays thereof (always flat arrays) + default: mixFunction = this._lerp; - setValue2iv = function( gl, v ) { gl.uniform2iv( this.addr, v ); }, - setValue3iv = function( gl, v ) { gl.uniform3iv( this.addr, v ); }, - setValue4iv = function( gl, v ) { gl.uniform4iv( this.addr, v ); }, + } - // Helper to pick the right setter for the singular case + this.buffer = new bufferType( valueSize * 4 ); + // layout: [ incoming | accu0 | accu1 | orig ] + // + // interpolators can use .buffer as their .result + // the data then goes to 'incoming' + // + // 'accu0' and 'accu1' are used frame-interleaved for + // the cumulative result and are compared to detect + // changes + // + // 'orig' stores the original state of the property - getSingularSetter = function( type ) { + this._mixBufferRegion = mixFunction; - switch ( type ) { + this.cumulativeWeight = 0; - case 0x1406: return setValue1f; // FLOAT - case 0x8b50: return setValue2fv; // _VEC2 - case 0x8b51: return setValue3fv; // _VEC3 - case 0x8b52: return setValue4fv; // _VEC4 + this.useCount = 0; + this.referenceCount = 0; - case 0x8b5a: return setValue2fm; // _MAT2 - case 0x8b5b: return setValue3fm; // _MAT3 - case 0x8b5c: return setValue4fm; // _MAT4 + }; - case 0x8b5e: return setValueT1; // SAMPLER_2D - case 0x8b60: return setValueT6; // SAMPLER_CUBE + PropertyMixer.prototype = { - case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL - case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 - case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 - case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 + constructor: PropertyMixer, - } + // accumulate data in the 'incoming' region into 'accu' + accumulate: function( accuIndex, weight ) { - }, + // note: happily accumulating nothing when weight = 0, the caller knows + // the weight and shouldn't have made the call in the first place - // Array of scalars + var buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride, - setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); }, - setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); }, + currentWeight = this.cumulativeWeight; - // Array of vectors (flat or from THREE classes) + if ( currentWeight === 0 ) { - setValueV2a = function( gl, v ) { + // accuN := incoming * weight - gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); + for ( var i = 0; i !== stride; ++ i ) { - }, + buffer[ offset + i ] = buffer[ i ]; - setValueV3a = function( gl, v ) { + } - gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); + currentWeight = weight; - }, + } else { - setValueV4a = function( gl, v ) { + // accuN := accuN + incoming * weight - gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); + currentWeight += weight; + var mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); - }, + } - // Array of matrices (flat or from THREE clases) + this.cumulativeWeight = currentWeight; - setValueM2a = function( gl, v ) { + }, - gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); + // apply the state of 'accu' to the binding when accus differ + apply: function( accuIndex ) { - }, + var stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, - setValueM3a = function( gl, v ) { + weight = this.cumulativeWeight, - gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); + binding = this.binding; - }, + this.cumulativeWeight = 0; - setValueM4a = function( gl, v ) { + if ( weight < 1 ) { - gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); + // accuN := accuN + original * ( 1 - cumulativeWeight ) - }, + var originalValueOffset = stride * 3; - // Array of textures (2D / Cube) + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); - setValueT1a = function( gl, v, renderer ) { + } - var n = v.length, - units = allocTexUnits( renderer, n ); + for ( var i = stride, e = stride + stride; i !== e; ++ i ) { - gl.uniform1iv( this.addr, units ); + if ( buffer[ i ] !== buffer[ i + stride ] ) { - for ( var i = 0; i !== n; ++ i ) { + // value has changed -> update scene graph - renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); + binding.setValue( buffer, offset ); + break; - } + } - }, + } - setValueT6a = function( gl, v, renderer ) { + }, - var n = v.length, - units = allocTexUnits( renderer, n ); + // remember the state of the bound property and copy it to both accus + saveOriginalState: function() { - gl.uniform1iv( this.addr, units ); + var binding = this.binding; - for ( var i = 0; i !== n; ++ i ) { + var buffer = this.buffer, + stride = this.valueSize, - renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + originalValueOffset = stride * 3; - } + binding.getValue( buffer, originalValueOffset ); - }, + // accu[0..1] := orig -- initially detect changes against the original + for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; - // Helper to pick the right setter for a pure (bottom-level) array + } - getPureArraySetter = function( type ) { + this.cumulativeWeight = 0; - switch ( type ) { + }, - case 0x1406: return setValue1fv; // FLOAT - case 0x8b50: return setValueV2a; // _VEC2 - case 0x8b51: return setValueV3a; // _VEC3 - case 0x8b52: return setValueV4a; // _VEC4 + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState: function() { - case 0x8b5a: return setValueM2a; // _MAT2 - case 0x8b5b: return setValueM3a; // _MAT3 - case 0x8b5c: return setValueM4a; // _MAT4 + var originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); - case 0x8b5e: return setValueT1a; // SAMPLER_2D - case 0x8b60: return setValueT6a; // SAMPLER_CUBE + }, - case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL - case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 - case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 - case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 - } + // mix functions - }, + _select: function( buffer, dstOffset, srcOffset, t, stride ) { - // --- Uniform Classes --- + if ( t >= 0.5 ) { - SingleUniform = function SingleUniform( id, activeInfo, addr ) { + for ( var i = 0; i !== stride; ++ i ) { - this.id = id; - this.addr = addr; - this.setValue = getSingularSetter( activeInfo.type ); + buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; - // this.path = activeInfo.name; // DEBUG + } - }, + } - PureArrayUniform = function( id, activeInfo, addr ) { + }, - this.id = id; - this.addr = addr; - this.size = activeInfo.size; - this.setValue = getPureArraySetter( activeInfo.type ); + _slerp: function( buffer, dstOffset, srcOffset, t, stride ) { - // this.path = activeInfo.name; // DEBUG + Quaternion.slerpFlat( buffer, dstOffset, + buffer, dstOffset, buffer, srcOffset, t ); - }, + }, - StructuredUniform = function( id ) { + _lerp: function( buffer, dstOffset, srcOffset, t, stride ) { - this.id = id; + var s = 1 - t; - UniformContainer.call( this ); // mix-in + for ( var i = 0; i !== stride; ++ i ) { - }; + var j = dstOffset + i; - StructuredUniform.prototype.setValue = function( gl, value ) { + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; - // Note: Don't need an extra 'renderer' parameter, since samplers - // are not allowed in structured uniforms. + } - var seq = this.seq; + } - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + }; - var u = seq[ i ]; - u.setValue( gl, value[ u.id ] ); + /** + * + * A reference to a real property in the scene graph. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } + function PropertyBinding ( rootNode, path, parsedPath ) { + this.isPropertyBinding = true; - }; + this.path = path; + this.parsedPath = parsedPath || + PropertyBinding.parseTrackName( path ); - // --- Top-level --- + this.node = PropertyBinding.findNode( + rootNode, this.parsedPath.nodeName ) || rootNode; - // Parser - builds up the property tree from the path strings + this.rootNode = rootNode; - var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g, - // extracts - // - the identifier (member name or array index) - // - followed by an optional right bracket (found when array index) - // - followed by an optional left bracket or dot (type of subscript) - // - // Note: These portions can be read in a non-overlapping fashion and - // allow straightforward parsing of the hierarchy that WebGL encodes - // in the uniform names. + }; - addUniform = function( container, uniformObject ) { + PropertyBinding.prototype = { - container.seq.push( uniformObject ); - container.map[ uniformObject.id ] = uniformObject; + constructor: PropertyBinding, - }, + getValue: function getValue_unbound( targetArray, offset ) { - parseUniform = function( activeInfo, addr, container ) { + this.bind(); + this.getValue( targetArray, offset ); - var path = activeInfo.name, - pathLength = path.length; + // Note: This class uses a State pattern on a per-method basis: + // 'bind' sets 'this.getValue' / 'setValue' and shadows the + // prototype version of these methods with one that represents + // the bound state. When the property is not found, the methods + // become no-ops. - // reset RegExp object, because of the early exit of a previous run - RePathPart.lastIndex = 0; + }, - for (; ;) { + setValue: function getValue_unbound( sourceArray, offset ) { - var match = RePathPart.exec( path ), - matchEnd = RePathPart.lastIndex, + this.bind(); + this.setValue( sourceArray, offset ); - id = match[ 1 ], - idIsIndex = match[ 2 ] === ']', - subscript = match[ 3 ]; + }, - if ( idIsIndex ) id = id | 0; // convert to integer + // create getter / setter pair for a property in the scene graph + bind: function() { - if ( subscript === undefined || - subscript === '[' && matchEnd + 2 === pathLength ) { - // bare name or "pure" bottom-level array "[0]" suffix + var targetObject = this.node, + parsedPath = this.parsedPath, - addUniform( container, subscript === undefined ? - new SingleUniform( id, activeInfo, addr ) : - new PureArrayUniform( id, activeInfo, addr ) ); + objectName = parsedPath.objectName, + propertyName = parsedPath.propertyName, + propertyIndex = parsedPath.propertyIndex; - break; + if ( ! targetObject ) { - } else { - // step into inner node / create it in case it doesn't exist + targetObject = PropertyBinding.findNode( + this.rootNode, parsedPath.nodeName ) || this.rootNode; - var map = container.map, - next = map[ id ]; + this.node = targetObject; - if ( next === undefined ) { + } - next = new StructuredUniform( id ); - addUniform( container, next ); + // set fail state so we can just 'return' on error + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; - } + // ensure there is a value node + if ( ! targetObject ) { - container = next; + console.error( " trying to update node for track: " + this.path + " but it wasn't found." ); + return; - } + } - } + if ( objectName ) { - }, + var objectIndex = parsedPath.objectIndex; - // Root Container + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { - WebGLUniforms = function WebGLUniforms( gl, program, renderer ) { + case 'materials': - UniformContainer.call( this ); + if ( ! targetObject.material ) { - this.renderer = renderer; + console.error( ' can not bind to material as node does not have a material', this ); + return; - var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + } - for ( var i = 0; i !== n; ++ i ) { + if ( ! targetObject.material.materials ) { - var info = gl.getActiveUniform( program, i ), - path = info.name, - addr = gl.getUniformLocation( program, path ); + console.error( ' can not bind to material.materials as node.material does not have a materials array', this ); + return; - parseUniform( info, addr, this ); + } - } + targetObject = targetObject.material.materials; - }; + break; + case 'bones': - WebGLUniforms.prototype.setValue = function( gl, name, value ) { + if ( ! targetObject.skeleton ) { - var u = this.map[ name ]; + console.error( ' can not bind to bones as node does not have a skeleton', this ); + return; - if ( u !== undefined ) u.setValue( gl, value, this.renderer ); + } - }; + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. - WebGLUniforms.prototype.set = function( gl, object, name ) { + targetObject = targetObject.skeleton.bones; - var u = this.map[ name ]; + // support resolving morphTarget names into indices. + for ( var i = 0; i < targetObject.length; i ++ ) { - if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer ); + if ( targetObject[ i ].name === objectIndex ) { - }; + objectIndex = i; + break; - WebGLUniforms.prototype.setOptional = function( gl, object, name ) { + } - var v = object[ name ]; + } - if ( v !== undefined ) this.setValue( gl, name, v ); + break; - }; + default: + if ( targetObject[ objectName ] === undefined ) { - // Static interface + console.error( ' can not bind to objectName of node, undefined', this ); + return; - WebGLUniforms.upload = function( gl, seq, values, renderer ) { + } - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + targetObject = targetObject[ objectName ]; - var u = seq[ i ], - v = values[ u.id ]; + } - if ( v.needsUpdate !== false ) { - // note: always updating when .needsUpdate is undefined - u.setValue( gl, v.value, renderer ); + if ( objectIndex !== undefined ) { - } + if ( targetObject[ objectIndex ] === undefined ) { - } + console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject ); + return; - }; + } - WebGLUniforms.seqWithValue = function( seq, values ) { + targetObject = targetObject[ objectIndex ]; - var r = []; + } - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + } - var u = seq[ i ]; - if ( u.id in values ) r.push( u ); + // resolve property + var nodeProperty = targetObject[ propertyName ]; - } + if ( nodeProperty === undefined ) { - return r; + var nodeName = parsedPath.nodeName; - }; + console.error( " trying to update property for track: " + nodeName + + '.' + propertyName + " but it wasn't found.", targetObject ); + return; - WebGLUniforms.splitDynamic = function( seq, values ) { + } - var r = null, - n = seq.length, - w = 0; + // determine versioning scheme + var versioning = this.Versioning.None; - for ( var i = 0; i !== n; ++ i ) { + if ( targetObject.needsUpdate !== undefined ) { // material - var u = seq[ i ], - v = values[ u.id ]; + versioning = this.Versioning.NeedsUpdate; + this.targetObject = targetObject; - if ( v && v.dynamic === true ) { + } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform - if ( r === null ) r = []; - r.push( u ); + versioning = this.Versioning.MatrixWorldNeedsUpdate; + this.targetObject = targetObject; - } else { + } - // in-place compact 'seq', removing the matches - if ( w < i ) seq[ w ] = u; - ++ w; + // determine how the property gets bound + var bindingType = this.BindingType.Direct; - } + if ( propertyIndex !== undefined ) { + // access a sub element of the property array (only primitives are supported right now) - } + if ( propertyName === "morphTargetInfluences" ) { + // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. - if ( w < n ) seq.length = w; + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { - return r; + console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this ); + return; - }; + } - WebGLUniforms.evalDynamic = function( seq, values, object, camera ) { + if ( ! targetObject.geometry.morphTargets ) { - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this ); + return; - var v = values[ seq[ i ].id ], - f = v.onUpdateCallback; + } - if ( f !== undefined ) f.call( v, object, camera ); + for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { - } + if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) { - }; + propertyIndex = i; + break; - return WebGLUniforms; + } -} )(); + } -// File:src/renderers/webgl/plugins/LensFlarePlugin.js + } -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + bindingType = this.BindingType.ArrayElement; -THREE.LensFlarePlugin = function ( renderer, flares ) { + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; - var gl = renderer.context; - var state = renderer.state; + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { + // must use copy for Object3D.Euler/Quaternion - var vertexBuffer, elementBuffer; - var shader, program, attributes, uniforms; + bindingType = this.BindingType.HasFromToArray; - var tempTexture, occlusionTexture; + this.resolvedProperty = nodeProperty; - function init() { + } else if ( nodeProperty.length !== undefined ) { - var vertices = new Float32Array( [ - - 1, - 1, 0, 0, - 1, - 1, 1, 0, - 1, 1, 1, 1, - - 1, 1, 0, 1 - ] ); + bindingType = this.BindingType.EntireArray; - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); + this.resolvedProperty = nodeProperty; - // buffers + } else { - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); + this.propertyName = propertyName; - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + } - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; - // textures + }, - tempTexture = gl.createTexture(); - occlusionTexture = gl.createTexture(); + unbind: function() { - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + this.node = null; - state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); - gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + // back to the prototype version of getValue / setValue + // note: avoiding to mutate the shape of 'this' via 'delete' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; - shader = { + } - vertexShader: [ + }; - "uniform lowp int renderType;", + Object.assign( PropertyBinding.prototype, { // prototype, continued - "uniform vec3 screenPosition;", - "uniform vec2 scale;", - "uniform float rotation;", + // these are used to "bind" a nonexistent property + _getValue_unavailable: function() {}, + _setValue_unavailable: function() {}, - "uniform sampler2D occlusionMap;", + // initial state of these methods that calls 'bind' + _getValue_unbound: PropertyBinding.prototype.getValue, + _setValue_unbound: PropertyBinding.prototype.setValue, - "attribute vec2 position;", - "attribute vec2 uv;", + BindingType: { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }, - "varying vec2 vUV;", - "varying float vVisibility;", + Versioning: { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }, - "void main() {", + GetterByBindingType: [ - "vUV = uv;", + function getValue_direct( buffer, offset ) { - "vec2 pos = position;", + buffer[ offset ] = this.node[ this.propertyName ]; - "if ( renderType == 2 ) {", + }, - "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );", + function getValue_array( buffer, offset ) { - "vVisibility = visibility.r / 9.0;", - "vVisibility *= 1.0 - visibility.g / 9.0;", - "vVisibility *= visibility.b / 9.0;", - "vVisibility *= 1.0 - visibility.a / 9.0;", + var source = this.resolvedProperty; - "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", - "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", + for ( var i = 0, n = source.length; i !== n; ++ i ) { - "}", + buffer[ offset ++ ] = source[ i ]; - "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", + } - "}" + }, - ].join( "\n" ), + function getValue_arrayElement( buffer, offset ) { - fragmentShader: [ + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; - "uniform lowp int renderType;", + }, - "uniform sampler2D map;", - "uniform float opacity;", - "uniform vec3 color;", + function getValue_toArray( buffer, offset ) { - "varying vec2 vUV;", - "varying float vVisibility;", + this.resolvedProperty.toArray( buffer, offset ); - "void main() {", + } - // pink square + ], - "if ( renderType == 0 ) {", + SetterByBindingTypeAndVersioning: [ - "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", + [ + // Direct - // restore + function setValue_direct( buffer, offset ) { - "} else if ( renderType == 1 ) {", + this.node[ this.propertyName ] = buffer[ offset ]; - "gl_FragColor = texture2D( map, vUV );", + }, - // flare + function setValue_direct_setNeedsUpdate( buffer, offset ) { - "} else {", + this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - "vec4 texture = texture2D( map, vUV );", - "texture.a *= opacity * vVisibility;", - "gl_FragColor = texture;", - "gl_FragColor.rgb *= color;", + }, - "}", + function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { - "}" + this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - ].join( "\n" ) + } - }; + ], [ - program = createProgram( shader ); + // EntireArray - attributes = { - vertex: gl.getAttribLocation ( program, "position" ), - uv: gl.getAttribLocation ( program, "uv" ) - }; + function setValue_array( buffer, offset ) { - uniforms = { - renderType: gl.getUniformLocation( program, "renderType" ), - map: gl.getUniformLocation( program, "map" ), - occlusionMap: gl.getUniformLocation( program, "occlusionMap" ), - opacity: gl.getUniformLocation( program, "opacity" ), - color: gl.getUniformLocation( program, "color" ), - scale: gl.getUniformLocation( program, "scale" ), - rotation: gl.getUniformLocation( program, "rotation" ), - screenPosition: gl.getUniformLocation( program, "screenPosition" ) - }; + var dest = this.resolvedProperty; - } + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - /* - * Render lens flares - * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, - * reads these back and calculates occlusion. - */ + dest[ i ] = buffer[ offset ++ ]; - this.render = function ( scene, camera, viewport ) { + } - if ( flares.length === 0 ) return; + }, - var tempPosition = new THREE.Vector3(); + function setValue_array_setNeedsUpdate( buffer, offset ) { - var invAspect = viewport.w / viewport.z, - halfViewportWidth = viewport.z * 0.5, - halfViewportHeight = viewport.w * 0.5; + var dest = this.resolvedProperty; - var size = 16 / viewport.w, - scale = new THREE.Vector2( size * invAspect, size ); + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - var screenPosition = new THREE.Vector3( 1, 1, 0 ), - screenPositionPixels = new THREE.Vector2( 1, 1 ); + dest[ i ] = buffer[ offset ++ ]; - var validArea = new THREE.Box2(); + } - validArea.min.set( 0, 0 ); - validArea.max.set( viewport.z - 16, viewport.w - 16 ); + this.targetObject.needsUpdate = true; - if ( program === undefined ) { + }, - init(); + function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { - } + var dest = this.resolvedProperty; - gl.useProgram( program ); + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - state.initAttributes(); - state.enableAttribute( attributes.vertex ); - state.enableAttribute( attributes.uv ); - state.disableUnusedAttributes(); + dest[ i ] = buffer[ offset ++ ]; - // loop through all lens flares to update their occlusion and positions - // setup gl and common used attribs/uniforms + } - gl.uniform1i( uniforms.occlusionMap, 0 ); - gl.uniform1i( uniforms.map, 1 ); + this.targetObject.matrixWorldNeedsUpdate = true; - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 ); - gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); + } - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + ], [ - state.disable( gl.CULL_FACE ); - state.setDepthWrite( false ); + // ArrayElement - for ( var i = 0, l = flares.length; i < l; i ++ ) { + function setValue_arrayElement( buffer, offset ) { - size = 16 / viewport.w; - scale.set( size * invAspect, size ); + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - // calc object screen position + }, - var flare = flares[ i ]; + function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { - tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] ); + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - tempPosition.applyMatrix4( camera.matrixWorldInverse ); - tempPosition.applyProjection( camera.projectionMatrix ); + }, - // setup arrays for gl programs + function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { - screenPosition.copy( tempPosition ); + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - // horizontal and vertical coordinate of the lower left corner of the pixels to copy + } - screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8; - screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8; + ], [ - // screen cull + // HasToFromArray - if ( validArea.containsPoint( screenPositionPixels ) === true ) { + function setValue_fromArray( buffer, offset ) { - // save current RGB to temp texture + this.resolvedProperty.fromArray( buffer, offset ); - state.activeTexture( gl.TEXTURE0 ); - state.bindTexture( gl.TEXTURE_2D, null ); - state.activeTexture( gl.TEXTURE1 ); - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); + }, + function setValue_fromArray_setNeedsUpdate( buffer, offset ) { - // render pink quad + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; - gl.uniform1i( uniforms.renderType, 0 ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); + }, - state.disable( gl.BLEND ); - state.enable( gl.DEPTH_TEST ); + function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; + } - // copy result to occlusionMap + ] - state.activeTexture( gl.TEXTURE0 ); - state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); - gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); + ] + } ); - // restore graphics + PropertyBinding.Composite = + function( targetGroup, path, optionalParsedPath ) { - gl.uniform1i( uniforms.renderType, 1 ); - state.disable( gl.DEPTH_TEST ); + var parsedPath = optionalParsedPath || + PropertyBinding.parseTrackName( path ); - state.activeTexture( gl.TEXTURE1 ); - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); + }; - // update object positions + PropertyBinding.Composite.prototype = { - flare.positionScreen.copy( screenPosition ); + constructor: PropertyBinding.Composite, - if ( flare.customUpdateCallback ) { + getValue: function( array, offset ) { - flare.customUpdateCallback( flare ); + this.bind(); // bind all binding - } else { + var firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; - flare.updateLensFlares(); + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); - } + }, - // render flares + setValue: function( array, offset ) { - gl.uniform1i( uniforms.renderType, 2 ); - state.enable( gl.BLEND ); + var bindings = this._bindings; - for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - var sprite = flare.lensFlares[ j ]; + bindings[ i ].setValue( array, offset ); - if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { + } - screenPosition.x = sprite.x; - screenPosition.y = sprite.y; - screenPosition.z = sprite.z; + }, - size = sprite.size * sprite.scale / viewport.w; + bind: function() { - scale.x = size * invAspect; - scale.y = size; + var bindings = this._bindings; - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform1f( uniforms.rotation, sprite.rotation ); + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - gl.uniform1f( uniforms.opacity, sprite.opacity ); - gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); + bindings[ i ].bind(); - state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); - renderer.setTexture2D( sprite.texture, 1 ); + } - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + }, - } + unbind: function() { - } + var bindings = this._bindings; - } + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - } + bindings[ i ].unbind(); - // restore gl + } - state.enable( gl.CULL_FACE ); - state.enable( gl.DEPTH_TEST ); - state.setDepthWrite( true ); + } - renderer.resetGLState(); + }; - }; + PropertyBinding.create = function( root, path, parsedPath ) { - function createProgram ( shader ) { + if ( ! ( (root && root.isAnimationObjectGroup) ) ) { - var program = gl.createProgram(); + return new PropertyBinding( root, path, parsedPath ); - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + } else { - var prefix = "precision " + renderer.getPrecision() + " float;\n"; + return new PropertyBinding.Composite( root, path, parsedPath ); - gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); - gl.shaderSource( vertexShader, prefix + shader.vertexShader ); + } - gl.compileShader( fragmentShader ); - gl.compileShader( vertexShader ); + }; - gl.attachShader( program, fragmentShader ); - gl.attachShader( program, vertexShader ); + PropertyBinding.parseTrackName = function( trackName ) { - gl.linkProgram( program ); + // matches strings in the form of: + // nodeName.property + // nodeName.property[accessor] + // nodeName.material.property[accessor] + // uuid.property[accessor] + // uuid.objectName[objectIndex].propertyName[propertyIndex] + // parentName/nodeName.property + // parentName/parentName/nodeName.property[index] + // .bone[Armature.DEF_cog].position + // created and tested via https://regex101.com/#javascript - return program; + var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_.:\- ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/; + var matches = re.exec( trackName ); - } + if ( ! matches ) { -}; + throw new Error( "cannot parse trackName at all: " + trackName ); -// File:src/renderers/webgl/plugins/SpritePlugin.js + } -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + if ( matches.index === re.lastIndex ) { -THREE.SpritePlugin = function ( renderer, sprites ) { + re.lastIndex++; - var gl = renderer.context; - var state = renderer.state; + } - var vertexBuffer, elementBuffer; - var program, attributes, uniforms; + var results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 3 ], // allowed to be null, specified root node. + objectName: matches[ 5 ], + objectIndex: matches[ 7 ], + propertyName: matches[ 9 ], + propertyIndex: matches[ 11 ] // allowed to be null, specifies that the whole property is set. + }; - var texture; + if ( results.propertyName === null || results.propertyName.length === 0 ) { - // decompose matrixWorld + throw new Error( "can not parse propertyName from trackName: " + trackName ); - var spritePosition = new THREE.Vector3(); - var spriteRotation = new THREE.Quaternion(); - var spriteScale = new THREE.Vector3(); + } - function init() { + return results; - var vertices = new Float32Array( [ - - 0.5, - 0.5, 0, 0, - 0.5, - 0.5, 1, 0, - 0.5, 0.5, 1, 1, - - 0.5, 0.5, 0, 1 - ] ); + }; - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); + PropertyBinding.findNode = function( root, nodeName ) { - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); + if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + return root; - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + } - program = createProgram(); + // search into skeleton bones. + if ( root.skeleton ) { - attributes = { - position: gl.getAttribLocation ( program, 'position' ), - uv: gl.getAttribLocation ( program, 'uv' ) - }; + var searchSkeleton = function( skeleton ) { - uniforms = { - uvOffset: gl.getUniformLocation( program, 'uvOffset' ), - uvScale: gl.getUniformLocation( program, 'uvScale' ), + for( var i = 0; i < skeleton.bones.length; i ++ ) { - rotation: gl.getUniformLocation( program, 'rotation' ), - scale: gl.getUniformLocation( program, 'scale' ), + var bone = skeleton.bones[ i ]; - color: gl.getUniformLocation( program, 'color' ), - map: gl.getUniformLocation( program, 'map' ), - opacity: gl.getUniformLocation( program, 'opacity' ), + if ( bone.name === nodeName ) { - modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), - projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), + return bone; - fogType: gl.getUniformLocation( program, 'fogType' ), - fogDensity: gl.getUniformLocation( program, 'fogDensity' ), - fogNear: gl.getUniformLocation( program, 'fogNear' ), - fogFar: gl.getUniformLocation( program, 'fogFar' ), - fogColor: gl.getUniformLocation( program, 'fogColor' ), + } + } - alphaTest: gl.getUniformLocation( program, 'alphaTest' ) - }; + return null; - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = 8; - canvas.height = 8; + }; - var context = canvas.getContext( '2d' ); - context.fillStyle = 'white'; - context.fillRect( 0, 0, 8, 8 ); + var bone = searchSkeleton( root.skeleton ); - texture = new THREE.Texture( canvas ); - texture.needsUpdate = true; + if ( bone ) { - } + return bone; - this.render = function ( scene, camera ) { + } + } - if ( sprites.length === 0 ) return; + // search into node subtree. + if ( root.children ) { - // setup gl + var searchNodeSubtree = function( children ) { - if ( program === undefined ) { + for( var i = 0; i < children.length; i ++ ) { - init(); + var childNode = children[ i ]; - } + if ( childNode.name === nodeName || childNode.uuid === nodeName ) { - gl.useProgram( program ); + return childNode; - state.initAttributes(); - state.enableAttribute( attributes.position ); - state.enableAttribute( attributes.uv ); - state.disableUnusedAttributes(); + } - state.disable( gl.CULL_FACE ); - state.enable( gl.BLEND ); + var result = searchNodeSubtree( childNode.children ); - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 ); - gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); + if ( result ) return result; - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + } - gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); + return null; - state.activeTexture( gl.TEXTURE0 ); - gl.uniform1i( uniforms.map, 0 ); + }; - var oldFogType = 0; - var sceneFogType = 0; - var fog = scene.fog; + var subTreeNode = searchNodeSubtree( root.children ); - if ( fog ) { + if ( subTreeNode ) { - gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); + return subTreeNode; - if ( fog instanceof THREE.Fog ) { + } - gl.uniform1f( uniforms.fogNear, fog.near ); - gl.uniform1f( uniforms.fogFar, fog.far ); + } - gl.uniform1i( uniforms.fogType, 1 ); - oldFogType = 1; - sceneFogType = 1; + return null; - } else if ( fog instanceof THREE.FogExp2 ) { + }; - gl.uniform1f( uniforms.fogDensity, fog.density ); + /** + * + * A group of objects that receives a shared animation state. + * + * Usage: + * + * - Add objects you would otherwise pass as 'root' to the + * constructor or the .clipAction method of AnimationMixer. + * + * - Instead pass this object as 'root'. + * + * - You can also add and remove objects later when the mixer + * is running. + * + * Note: + * + * Objects of this class appear as one object to the mixer, + * so cache control of the individual objects must be done + * on the group. + * + * Limitation: + * + * - The animated properties must be compatible among the + * all objects in the group. + * + * - A single property can either be controlled through a + * target group or directly, but not both. + * + * @author tschw + */ - gl.uniform1i( uniforms.fogType, 2 ); - oldFogType = 2; - sceneFogType = 2; + function AnimationObjectGroup( var_args ) { + this.isAnimationObjectGroup = true; - } + this.uuid = exports.Math.generateUUID(); - } else { + // cached objects followed by the active ones + this._objects = Array.prototype.slice.call( arguments ); - gl.uniform1i( uniforms.fogType, 0 ); - oldFogType = 0; - sceneFogType = 0; + this.nCachedObjects_ = 0; // threshold + // note: read by PropertyBinding.Composite - } + var indices = {}; + this._indicesByUUID = indices; // for bookkeeping + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - // update positions and sort + indices[ arguments[ i ].uuid ] = i; - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + } - var sprite = sprites[ i ]; + this._paths = []; // inside: string + this._parsedPaths = []; // inside: { we don't care, here } + this._bindings = []; // inside: Array< PropertyBinding > + this._bindingsIndicesByPath = {}; // inside: indices in these arrays - sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); - sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; + var scope = this; - } + this.stats = { - sprites.sort( painterSortStable ); + objects: { + get total() { return scope._objects.length; }, + get inUse() { return this.total - scope.nCachedObjects_; } + }, - // render all sprites + get bindingsPerObject() { return scope._bindings.length; } - var scale = []; + }; - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + }; - var sprite = sprites[ i ]; - var material = sprite.material; + AnimationObjectGroup.prototype = { - if ( material.visible === false ) continue; + constructor: AnimationObjectGroup, - gl.uniform1f( uniforms.alphaTest, material.alphaTest ); - gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); + add: function( var_args ) { - sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); + var objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + nBindings = bindings.length; - scale[ 0 ] = spriteScale.x; - scale[ 1 ] = spriteScale.y; + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - var fogType = 0; + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - if ( scene.fog && material.fog ) { + if ( index === undefined ) { - fogType = sceneFogType; + // unknown object -> add it to the ACTIVE region - } + index = nObjects ++; + indicesByUUID[ uuid ] = index; + objects.push( object ); - if ( oldFogType !== fogType ) { + // accounting is done, now do the same for all bindings - gl.uniform1i( uniforms.fogType, fogType ); - oldFogType = fogType; + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - } + bindings[ j ].push( + new PropertyBinding( + object, paths[ j ], parsedPaths[ j ] ) ); - if ( material.map !== null ) { + } - gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y ); - gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y ); + } else if ( index < nCachedObjects ) { - } else { + var knownObject = objects[ index ]; - gl.uniform2f( uniforms.uvOffset, 0, 0 ); - gl.uniform2f( uniforms.uvScale, 1, 1 ); + // move existing object to the ACTIVE region - } + var firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ]; - gl.uniform1f( uniforms.opacity, material.opacity ); - gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; - gl.uniform1f( uniforms.rotation, material.rotation ); - gl.uniform2fv( uniforms.scale, scale ); + indicesByUUID[ uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = object; - state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - state.setDepthTest( material.depthTest ); - state.setDepthWrite( material.depthWrite ); + // accounting is done, now do the same for all bindings - if ( material.map ) { + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - renderer.setTexture2D( material.map, 0 ); + var bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + binding = bindingsForPath[ index ]; - } else { + bindingsForPath[ index ] = lastCached; - renderer.setTexture2D( texture, 0 ); + if ( binding === undefined ) { - } + // since we do not bother to create new bindings + // for objects that are cached, the binding may + // or may not exist - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + binding = new PropertyBinding( + object, paths[ j ], parsedPaths[ j ] ); - } + } - // restore gl + bindingsForPath[ firstActiveIndex ] = binding; - state.enable( gl.CULL_FACE ); + } - renderer.resetGLState(); + } else if ( objects[ index ] !== knownObject) { - }; + console.error( "Different objects with the same UUID " + + "detected. Clean the caches or recreate your " + + "infrastructure when reloading scenes..." ); - function createProgram () { + } // else the object is already where we want it to be - var program = gl.createProgram(); + } // for arguments - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + this.nCachedObjects_ = nCachedObjects; - gl.shaderSource( vertexShader, [ + }, - 'precision ' + renderer.getPrecision() + ' float;', + remove: function( var_args ) { - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform float rotation;', - 'uniform vec2 scale;', - 'uniform vec2 uvOffset;', - 'uniform vec2 uvScale;', + var objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - 'attribute vec2 position;', - 'attribute vec2 uv;', + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - 'varying vec2 vUV;', + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - 'void main() {', + if ( index !== undefined && index >= nCachedObjects ) { - 'vUV = uvOffset + uv * uvScale;', + // move existing object into the CACHED region - 'vec2 alignedPosition = position * scale;', + var lastCachedIndex = nCachedObjects ++, + firstActiveObject = objects[ lastCachedIndex ]; - 'vec2 rotatedPosition;', - 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', - 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', + indicesByUUID[ firstActiveObject.uuid ] = index; + objects[ index ] = firstActiveObject; - 'vec4 finalPosition;', + indicesByUUID[ uuid ] = lastCachedIndex; + objects[ lastCachedIndex ] = object; - 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', - 'finalPosition.xy += rotatedPosition;', - 'finalPosition = projectionMatrix * finalPosition;', + // accounting is done, now do the same for all bindings - 'gl_Position = finalPosition;', + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - '}' + var bindingsForPath = bindings[ j ], + firstActive = bindingsForPath[ lastCachedIndex ], + binding = bindingsForPath[ index ]; - ].join( '\n' ) ); + bindingsForPath[ index ] = firstActive; + bindingsForPath[ lastCachedIndex ] = binding; - gl.shaderSource( fragmentShader, [ + } - 'precision ' + renderer.getPrecision() + ' float;', + } - 'uniform vec3 color;', - 'uniform sampler2D map;', - 'uniform float opacity;', + } // for arguments - 'uniform int fogType;', - 'uniform vec3 fogColor;', - 'uniform float fogDensity;', - 'uniform float fogNear;', - 'uniform float fogFar;', - 'uniform float alphaTest;', + this.nCachedObjects_ = nCachedObjects; - 'varying vec2 vUV;', + }, - 'void main() {', + // remove & forget + uncache: function( var_args ) { - 'vec4 texture = texture2D( map, vUV );', + var objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - 'if ( texture.a < alphaTest ) discard;', + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - 'if ( fogType > 0 ) {', + if ( index !== undefined ) { - 'float depth = gl_FragCoord.z / gl_FragCoord.w;', - 'float fogFactor = 0.0;', + delete indicesByUUID[ uuid ]; - 'if ( fogType == 1 ) {', + if ( index < nCachedObjects ) { - 'fogFactor = smoothstep( fogNear, fogFar, depth );', + // object is cached, shrink the CACHED region - '} else {', + var firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ], + lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - 'const float LOG2 = 1.442695;', - 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', - 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', + // last cached object takes this object's place + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; - '}', + // last object goes to the activated slot and pop + indicesByUUID[ lastObject.uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = lastObject; + objects.pop(); - 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', + // accounting is done, now do the same for all bindings - '}', + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - '}' + var bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + last = bindingsForPath[ lastIndex ]; - ].join( '\n' ) ); + bindingsForPath[ index ] = lastCached; + bindingsForPath[ firstActiveIndex ] = last; + bindingsForPath.pop(); - gl.compileShader( vertexShader ); - gl.compileShader( fragmentShader ); + } - gl.attachShader( program, vertexShader ); - gl.attachShader( program, fragmentShader ); + } else { - gl.linkProgram( program ); + // object is active, just swap with the last and pop - return program; + var lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - } + indicesByUUID[ lastObject.uuid ] = index; + objects[ index ] = lastObject; + objects.pop(); - function painterSortStable ( a, b ) { + // accounting is done, now do the same for all bindings - if ( a.renderOrder !== b.renderOrder ) { + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - return a.renderOrder - b.renderOrder; + var bindingsForPath = bindings[ j ]; - } else if ( a.z !== b.z ) { + bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; + bindingsForPath.pop(); - return b.z - a.z; + } - } else { + } // cached or active - return b.id - a.id; + } // if object is known - } + } // for arguments - } + this.nCachedObjects_ = nCachedObjects; -}; + }, -// File:src/Three.Legacy.js + // Internal interface used by befriended PropertyBinding.Composite: -/** - * @author mrdoob / http://mrdoob.com/ - */ + subscribe_: function( path, parsedPath ) { + // returns an array of bindings for the given path that is changed + // according to the contained objects in the group -Object.assign( THREE, { - Face4: function ( a, b, c, d, normal, color, materialIndex ) { - console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ); - return new THREE.Face3( a, b, c, normal, color, materialIndex ); - }, - LineStrip: 0, - LinePieces: 1, - MeshFaceMaterial: THREE.MultiMaterial, - PointCloud: function ( geometry, material ) { - console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); - return new THREE.Points( geometry, material ); - }, - Particle: THREE.Sprite, - ParticleSystem: function ( geometry, material ) { - console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); - return new THREE.Points( geometry, material ); - }, - PointCloudMaterial: function ( parameters ) { - console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); - return new THREE.PointsMaterial( parameters ); - }, - ParticleBasicMaterial: function ( parameters ) { - console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); - return new THREE.PointsMaterial( parameters ); - }, - ParticleSystemMaterial: function ( parameters ) { - console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); - return new THREE.PointsMaterial( parameters ); - }, - Vertex: function ( x, y, z ) { - console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); - return new THREE.Vector3( x, y, z ); - } -} ); + var indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ], + bindings = this._bindings; -// + if ( index !== undefined ) return bindings[ index ]; -Object.assign( THREE.Box2.prototype, { - empty: function () { - console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); - }, - isIntersectionBox: function ( box ) { - console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - } -} ); + var paths = this._paths, + parsedPaths = this._parsedPaths, + objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + bindingsForPath = new Array( nObjects ); -Object.assign( THREE.Box3.prototype, { - empty: function () { - console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); - }, - isIntersectionBox: function ( box ) { - console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - }, - isIntersectionSphere: function ( sphere ) { - console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); - } -} ); - -Object.assign( THREE.Matrix3.prototype, { - multiplyVector3: function ( vector ) { - console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); - return vector.applyMatrix3( this ); - }, - multiplyVector3Array: function ( a ) { - console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); - return this.applyToVector3Array( a ); - } -} ); - -Object.assign( THREE.Matrix4.prototype, { - extractPosition: function ( m ) { - console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); - return this.copyPosition( m ); - }, - setRotationFromQuaternion: function ( q ) { - console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); - return this.makeRotationFromQuaternion( q ); - }, - multiplyVector3: function ( vector ) { - console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); - return vector.applyProjection( this ); - }, - multiplyVector4: function ( vector ) { - console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - }, - multiplyVector3Array: function ( a ) { - console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); - return this.applyToVector3Array( a ); - }, - rotateAxis: function ( v ) { - console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); - v.transformDirection( this ); - }, - crossVector: function ( vector ) { - console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - }, - translate: function ( v ) { - console.error( 'THREE.Matrix4: .translate() has been removed.' ); - }, - rotateX: function ( angle ) { - console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); - }, - rotateY: function ( angle ) { - console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); - }, - rotateZ: function ( angle ) { - console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); - }, - rotateByAxis: function ( axis, angle ) { - console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); - } -} ); - -Object.assign( THREE.Plane.prototype, { - isIntersectionLine: function ( line ) { - console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); - return this.intersectsLine( line ); - } -} ); - -Object.assign( THREE.Quaternion.prototype, { - multiplyVector3: function ( vector ) { - console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); - return vector.applyQuaternion( this ); - } -} ); - -Object.assign( THREE.Ray.prototype, { - isIntersectionBox: function ( box ) { - console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - }, - isIntersectionPlane: function ( plane ) { - console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); - return this.intersectsPlane( plane ); - }, - isIntersectionSphere: function ( sphere ) { - console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); - } -} ); - -Object.assign( THREE.Vector3.prototype, { - setEulerFromRotationMatrix: function () { - console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); - }, - setEulerFromQuaternion: function () { - console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); - }, - getPositionFromMatrix: function ( m ) { - console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); - return this.setFromMatrixPosition( m ); - }, - getScaleFromMatrix: function ( m ) { - console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); - return this.setFromMatrixScale( m ); - }, - getColumnFromMatrix: function ( index, matrix ) { - console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); - return this.setFromMatrixColumn( matrix, index ); - } -} ); - -// - -Object.assign( THREE.Object3D.prototype, { - getChildByName: function ( name ) { - console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); - return this.getObjectByName( name ); - }, - renderDepth: function ( value ) { - console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); - }, - translate: function ( distance, axis ) { - console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); - return this.translateOnAxis( axis, distance ); - } -} ); - -Object.defineProperties( THREE.Object3D.prototype, { - eulerOrder: { - get: function () { - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - return this.rotation.order; - }, - set: function ( value ) { - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - this.rotation.order = value; - } - }, - useQuaternion: { - get: function () { - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); - }, - set: function ( value ) { - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); - } - } -} ); - -Object.defineProperties( THREE.LOD.prototype, { - objects: { - get: function () { - console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); - return this.levels; - } - } -} ); - -// - -THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { - - console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " + - "Use .setFocalLength and .filmGauge for a photographic setup." ); - - if ( filmGauge !== undefined ) this.filmGauge = filmGauge; - this.setFocalLength( focalLength ); - -}; - -// - -Object.defineProperties( THREE.Light.prototype, { - onlyShadow: { - set: function ( value ) { - console.warn( 'THREE.Light: .onlyShadow has been removed.' ); - } - }, - shadowCameraFov: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); - this.shadow.camera.fov = value; - } - }, - shadowCameraLeft: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' ); - this.shadow.camera.left = value; - } - }, - shadowCameraRight: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' ); - this.shadow.camera.right = value; - } - }, - shadowCameraTop: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); - this.shadow.camera.top = value; - } - }, - shadowCameraBottom: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); - this.shadow.camera.bottom = value; - } - }, - shadowCameraNear: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); - this.shadow.camera.near = value; - } - }, - shadowCameraFar: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); - this.shadow.camera.far = value; - } - }, - shadowCameraVisible: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); - } - }, - shadowBias: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); - this.shadow.bias = value; - } - }, - shadowDarkness: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); - } - }, - shadowMapWidth: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); - this.shadow.mapSize.width = value; - } - }, - shadowMapHeight: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); - this.shadow.mapSize.height = value; - } - } -} ); - -// - -Object.defineProperties( THREE.BufferAttribute.prototype, { - length: { - get: function () { - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); - return this.array.length; - } - } -} ); - -Object.assign( THREE.BufferGeometry.prototype, { - addIndex: function ( index ) { - console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); - this.setIndex( index ); - }, - addDrawCall: function ( start, count, indexOffset ) { - if ( indexOffset !== undefined ) { - console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); - } - console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); - this.addGroup( start, count ); - }, - clearDrawCalls: function () { - console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); - this.clearGroups(); - }, - computeTangents: function () { - console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' ); - }, - computeOffsets: function () { - console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); - } -} ); - -Object.defineProperties( THREE.BufferGeometry.prototype, { - drawcalls: { - get: function () { - console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); - return this.groups; - } - }, - offsets: { - get: function () { - console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); - return this.groups; - } - } -} ); - -// - -Object.defineProperties( THREE.Material.prototype, { - wrapAround: { - get: function () { - console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' ); - }, - set: function ( value ) { - console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' ); - } - }, - wrapRGB: { - get: function () { - console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' ); - return new THREE.Color(); - } - } -} ); - -Object.defineProperties( THREE.MeshPhongMaterial.prototype, { - metal: { - get: function () { - console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' ); - return false; - }, - set: function ( value ) { - console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' ); - } - } -} ); - -Object.defineProperties( THREE.ShaderMaterial.prototype, { - derivatives: { - get: function () { - console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - return this.extensions.derivatives; - }, - set: function ( value ) { - console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - this.extensions.derivatives = value; - } - } -} ); - -// - -THREE.EventDispatcher.prototype = Object.assign( Object.create( { - - // Note: Extra base ensures these properties are not 'assign'ed. - - constructor: THREE.EventDispatcher, - - apply: function ( target ) { - - console.warn( "THREE.EventDispatcher: .apply is deprecated, " + - "just inherit or Object.assign the prototype to mix-in." ); - - Object.assign( target, this ); - - } - -} ), THREE.EventDispatcher.prototype ); - -// - -Object.assign( THREE.WebGLRenderer.prototype, { - supportsFloatTextures: function () { - console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); - return this.extensions.get( 'OES_texture_float' ); - }, - supportsHalfFloatTextures: function () { - console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); - return this.extensions.get( 'OES_texture_half_float' ); - }, - supportsStandardDerivatives: function () { - console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); - return this.extensions.get( 'OES_standard_derivatives' ); - }, - supportsCompressedTextureS3TC: function () { - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); - }, - supportsCompressedTexturePVRTC: function () { - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - }, - supportsBlendMinMax: function () { - console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); - return this.extensions.get( 'EXT_blend_minmax' ); - }, - supportsVertexTextures: function () { - return this.capabilities.vertexTextures; - }, - supportsInstancedArrays: function () { - console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); - return this.extensions.get( 'ANGLE_instanced_arrays' ); - }, - enableScissorTest: function ( boolean ) { - console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); - this.setScissorTest( boolean ); - }, - initMaterial: function () { - console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); - }, - addPrePlugin: function () { - console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); - }, - addPostPlugin: function () { - console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); - }, - updateShadowMap: function () { - console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); - } -} ); - -Object.defineProperties( THREE.WebGLRenderer.prototype, { - shadowMapEnabled: { - get: function () { - return this.shadowMap.enabled; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); - this.shadowMap.enabled = value; - } - }, - shadowMapType: { - get: function () { - return this.shadowMap.type; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); - this.shadowMap.type = value; - } - }, - shadowMapCullFace: { - get: function () { - return this.shadowMap.cullFace; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' ); - this.shadowMap.cullFace = value; - } - } -} ); - -Object.defineProperties( THREE.WebGLShadowMap.prototype, { - cullFace: { - get: function () { - return this.renderReverseSided ? THREE.CullFaceFront : THREE.CullFaceBack; - }, - set: function ( cullFace ) { - var value = ( cullFace !== THREE.CullFaceBack ); - console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." ); - this.renderReverseSided = value; - } - } -} ); - -// - -Object.defineProperties( THREE.WebGLRenderTarget.prototype, { - wrapS: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - return this.texture.wrapS; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - this.texture.wrapS = value; - } - }, - wrapT: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - return this.texture.wrapT; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - this.texture.wrapT = value; - } - }, - magFilter: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - return this.texture.magFilter; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - this.texture.magFilter = value; - } - }, - minFilter: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - return this.texture.minFilter; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - this.texture.minFilter = value; - } - }, - anisotropy: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - return this.texture.anisotropy; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - this.texture.anisotropy = value; - } - }, - offset: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - return this.texture.offset; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - this.texture.offset = value; - } - }, - repeat: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - return this.texture.repeat; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - this.texture.repeat = value; - } - }, - format: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - return this.texture.format; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - this.texture.format = value; - } - }, - type: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - return this.texture.type; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - this.texture.type = value; - } - }, - generateMipmaps: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - return this.texture.generateMipmaps; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - this.texture.generateMipmaps = value; - } - } -} ); - -// - -Object.assign( THREE.Audio.prototype, { - load: function ( file ) { - console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' ); - var scope = this; - var audioLoader = new THREE.AudioLoader(); - audioLoader.load( file, function ( buffer ) { - scope.setBuffer( buffer ); - } ); - return this; - } -} ); - -Object.assign( THREE.AudioAnalyser.prototype, { - getData: function ( file ) { - console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); - return this.getFrequencyData(); - } -} ); - -// - -THREE.GeometryUtils = { - - merge: function ( geometry1, geometry2, materialIndexOffset ) { - - console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); - - var matrix; - - if ( geometry2 instanceof THREE.Mesh ) { - - geometry2.matrixAutoUpdate && geometry2.updateMatrix(); - - matrix = geometry2.matrix; - geometry2 = geometry2.geometry; - - } - - geometry1.merge( geometry2, matrix, materialIndexOffset ); - - }, - - center: function ( geometry ) { - - console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); - return geometry.center(); - - } - -}; - -THREE.ImageUtils = { - - crossOrigin: undefined, - - loadTexture: function ( url, mapping, onLoad, onError ) { - - console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); - - var loader = new THREE.TextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); - - var texture = loader.load( url, onLoad, undefined, onError ); - - if ( mapping ) texture.mapping = mapping; - - return texture; - - }, - - loadTextureCube: function ( urls, mapping, onLoad, onError ) { - - console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); - - var loader = new THREE.CubeTextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); - - var texture = loader.load( urls, onLoad, undefined, onError ); - - if ( mapping ) texture.mapping = mapping; - - return texture; - - }, - - loadCompressedTexture: function () { - - console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); - - }, - - loadCompressedTextureCube: function () { - - console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); - - } - -}; - -// - -THREE.Projector = function () { - - console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' ); - - this.projectVector = function ( vector, camera ) { - - console.warn( 'THREE.Projector: .projectVector() is now vector.project().' ); - vector.project( camera ); - - }; - - this.unprojectVector = function ( vector, camera ) { - - console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' ); - vector.unproject( camera ); - - }; - - this.pickingRay = function ( vector, camera ) { - - console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' ); - - }; - -}; - -// - -THREE.CanvasRenderer = function () { - - console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' ); - - this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - this.clear = function () {}; - this.render = function () {}; - this.setClearColor = function () {}; - this.setSize = function () {}; - -}; - -// File:src/extras/CurveUtils.js - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - */ - -THREE.CurveUtils = { - - tangentQuadraticBezier: function ( t, p0, p1, p2 ) { - - return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); - - }, - - // Puay Bing, thanks for helping with this derivative! - - tangentCubicBezier: function ( t, p0, p1, p2, p3 ) { - - return - 3 * p0 * ( 1 - t ) * ( 1 - t ) + - 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) + - 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 + - 3 * t * t * p3; - - }, - - tangentSpline: function ( t, p0, p1, p2, p3 ) { - - // To check if my formulas are correct - - var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1 - var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t - var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2 - var h11 = 3 * t * t - 2 * t; // t3 − t2 - - return h00 + h10 + h01 + h11; - - }, - - // Catmull-Rom - - interpolate: function( p0, p1, p2, p3, t ) { - - var v0 = ( p2 - p0 ) * 0.5; - var v1 = ( p3 - p1 ) * 0.5; - var t2 = t * t; - var t3 = t * t2; - return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - - } - -}; - -// File:src/extras/SceneUtils.js - -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.SceneUtils = { - - createMultiMaterialObject: function ( geometry, materials ) { - - var group = new THREE.Group(); - - for ( var i = 0, l = materials.length; i < l; i ++ ) { - - group.add( new THREE.Mesh( geometry, materials[ i ] ) ); - - } - - return group; - - }, - - detach: function ( child, parent, scene ) { - - child.applyMatrix( parent.matrixWorld ); - parent.remove( child ); - scene.add( child ); - - }, - - attach: function ( child, scene, parent ) { - - var matrixWorldInverse = new THREE.Matrix4(); - matrixWorldInverse.getInverse( parent.matrixWorld ); - child.applyMatrix( matrixWorldInverse ); - - scene.remove( child ); - parent.add( child ); - - } - -}; - -// File:src/extras/ShapeUtils.js - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - */ - -THREE.ShapeUtils = { - - // calculate area of the contour polygon - - area: function ( contour ) { - - var n = contour.length; - var a = 0.0; - - for ( var p = n - 1, q = 0; q < n; p = q ++ ) { - - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - - } - - return a * 0.5; - - }, - - triangulate: ( function () { - - /** - * This code is a quick port of code written in C++ which was submitted to - * flipcode.com by John W. Ratcliff // July 22, 2000 - * See original code and more information here: - * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml - * - * ported to actionscript by Zevan Rosser - * www.actionsnippet.com - * - * ported to javascript by Joshua Koo - * http://www.lab4games.net/zz85/blog - * - */ - - function snip( contour, u, v, w, n, verts ) { - - var p; - var ax, ay, bx, by; - var cx, cy, px, py; - - ax = contour[ verts[ u ] ].x; - ay = contour[ verts[ u ] ].y; - - bx = contour[ verts[ v ] ].x; - by = contour[ verts[ v ] ].y; - - cx = contour[ verts[ w ] ].x; - cy = contour[ verts[ w ] ].y; - - if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false; - - var aX, aY, bX, bY, cX, cY; - var apx, apy, bpx, bpy, cpx, cpy; - var cCROSSap, bCROSScp, aCROSSbp; - - aX = cx - bx; aY = cy - by; - bX = ax - cx; bY = ay - cy; - cX = bx - ax; cY = by - ay; - - for ( p = 0; p < n; p ++ ) { - - px = contour[ verts[ p ] ].x; - py = contour[ verts[ p ] ].y; - - if ( ( ( px === ax ) && ( py === ay ) ) || - ( ( px === bx ) && ( py === by ) ) || - ( ( px === cx ) && ( py === cy ) ) ) continue; - - apx = px - ax; apy = py - ay; - bpx = px - bx; bpy = py - by; - cpx = px - cx; cpy = py - cy; - - // see if p is inside triangle abc - - aCROSSbp = aX * bpy - aY * bpx; - cCROSSap = cX * apy - cY * apx; - bCROSScp = bX * cpy - bY * cpx; - - if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false; - - } - - return true; - - } - - // takes in an contour array and returns - - return function triangulate( contour, indices ) { - - var n = contour.length; - - if ( n < 3 ) return null; - - var result = [], - verts = [], - vertIndices = []; - - /* we want a counter-clockwise polygon in verts */ - - var u, v, w; - - if ( THREE.ShapeUtils.area( contour ) > 0.0 ) { - - for ( v = 0; v < n; v ++ ) verts[ v ] = v; - - } else { - - for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; - - } - - var nv = n; - - /* remove nv - 2 vertices, creating 1 triangle every time */ - - var count = 2 * nv; /* error detection */ - - for ( v = nv - 1; nv > 2; ) { - - /* if we loop, it is probably a non-simple polygon */ - - if ( ( count -- ) <= 0 ) { - - //** Triangulate: ERROR - probable bad polygon! - - //throw ( "Warning, unable to triangulate polygon!" ); - //return null; - // Sometimes warning is fine, especially polygons are triangulated in reverse. - console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' ); - - if ( indices ) return vertIndices; - return result; - - } - - /* three consecutive vertices in current polygon, */ - - u = v; if ( nv <= u ) u = 0; /* previous */ - v = u + 1; if ( nv <= v ) v = 0; /* new v */ - w = v + 1; if ( nv <= w ) w = 0; /* next */ - - if ( snip( contour, u, v, w, nv, verts ) ) { - - var a, b, c, s, t; - - /* true names of the vertices */ - - a = verts[ u ]; - b = verts[ v ]; - c = verts[ w ]; - - /* output Triangle */ - - result.push( [ contour[ a ], - contour[ b ], - contour[ c ] ] ); - - - vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); - - /* remove v from the remaining polygon */ - - for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { - - verts[ s ] = verts[ t ]; - - } - - nv --; - - /* reset error detection counter */ - - count = 2 * nv; - - } - - } - - if ( indices ) return vertIndices; - return result; - - } - - } )(), - - triangulateShape: function ( contour, holes ) { - - function removeDupEndPts(points) { - - var l = points.length; - - if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { - - points.pop(); - - } - - } - - removeDupEndPts( contour ); - holes.forEach( removeDupEndPts ); - - function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { - - // inOtherPt needs to be collinear to the inSegment - if ( inSegPt1.x !== inSegPt2.x ) { - - if ( inSegPt1.x < inSegPt2.x ) { - - return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); - - } else { - - return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); - - } - - } else { - - if ( inSegPt1.y < inSegPt2.y ) { - - return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); - - } else { - - return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); - - } - - } - - } - - function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { - - var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; - var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; - - var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; - var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; - - var limit = seg1dy * seg2dx - seg1dx * seg2dy; - var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; - - if ( Math.abs( limit ) > Number.EPSILON ) { - - // not parallel - - var perpSeg2; - if ( limit > 0 ) { - - if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; - - } else { - - if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; - - } - - // i.e. to reduce rounding errors - // intersection at endpoint of segment#1? - if ( perpSeg2 === 0 ) { - - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; - return [ inSeg1Pt1 ]; - - } - if ( perpSeg2 === limit ) { - - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; - return [ inSeg1Pt2 ]; - - } - // intersection at endpoint of segment#2? - if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ]; - if ( perpSeg1 === limit ) return [ inSeg2Pt2 ]; - - // return real intersection point - var factorSeg1 = perpSeg2 / limit; - return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, - y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; - - } else { - - // parallel or collinear - if ( ( perpSeg1 !== 0 ) || - ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return []; - - // they are collinear or degenerate - var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point? - var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point? - // both segments are points - if ( seg1Pt && seg2Pt ) { - - if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) || - ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points - return [ inSeg1Pt1 ]; // they are the same point - - } - // segment#1 is a single point - if ( seg1Pt ) { - - if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 - return [ inSeg1Pt1 ]; - - } - // segment#2 is a single point - if ( seg2Pt ) { - - if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 - return [ inSeg2Pt1 ]; - - } - - // they are collinear segments, which might overlap - var seg1min, seg1max, seg1minVal, seg1maxVal; - var seg2min, seg2max, seg2minVal, seg2maxVal; - if ( seg1dx !== 0 ) { - - // the segments are NOT on a vertical line - if ( inSeg1Pt1.x < inSeg1Pt2.x ) { - - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; - - } else { - - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; - - } - if ( inSeg2Pt1.x < inSeg2Pt2.x ) { - - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; - - } else { - - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; - - } - - } else { - - // the segments are on a vertical line - if ( inSeg1Pt1.y < inSeg1Pt2.y ) { - - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; - - } else { - - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; - - } - if ( inSeg2Pt1.y < inSeg2Pt2.y ) { - - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; - - } else { - - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; - - } - - } - if ( seg1minVal <= seg2minVal ) { - - if ( seg1maxVal < seg2minVal ) return []; - if ( seg1maxVal === seg2minVal ) { - - if ( inExcludeAdjacentSegs ) return []; - return [ seg2min ]; - - } - if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; - return [ seg2min, seg2max ]; - - } else { - - if ( seg1minVal > seg2maxVal ) return []; - if ( seg1minVal === seg2maxVal ) { - - if ( inExcludeAdjacentSegs ) return []; - return [ seg1min ]; - - } - if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; - return [ seg1min, seg2max ]; - - } - - } - - } - - function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { - - // The order of legs is important - - // translation of all points, so that Vertex is at (0,0) - var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y; - var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y; - var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y; - - // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. - var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; - var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; - - if ( Math.abs( from2toAngle ) > Number.EPSILON ) { - - // angle != 180 deg. - - var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; - // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); - - if ( from2toAngle > 0 ) { - - // main angle < 180 deg. - return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); - - } else { - - // main angle > 180 deg. - return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); - - } - - } else { - - // angle == 180 deg. - // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); - return ( from2otherAngle > 0 ); - - } - - } - - - function removeHoles( contour, holes ) { - - var shape = contour.concat(); // work on this shape - var hole; - - function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { - - // Check if hole point lies within angle around shape point - var lastShapeIdx = shape.length - 1; - - var prevShapeIdx = inShapeIdx - 1; - if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; - - var nextShapeIdx = inShapeIdx + 1; - if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; - - var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] ); - if ( ! insideAngle ) { - - // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); - return false; - - } - - // Check if shape point lies within angle around hole point - var lastHoleIdx = hole.length - 1; - - var prevHoleIdx = inHoleIdx - 1; - if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; - - var nextHoleIdx = inHoleIdx + 1; - if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; - - insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] ); - if ( ! insideAngle ) { - - // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); - return false; - - } - - return true; - - } - - function intersectsShapeEdge( inShapePt, inHolePt ) { - - // checks for intersections with shape edges - var sIdx, nextIdx, intersection; - for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) { - - nextIdx = sIdx + 1; nextIdx %= shape.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true ); - if ( intersection.length > 0 ) return true; - - } - - return false; - - } - - var indepHoles = []; - - function intersectsHoleEdge( inShapePt, inHolePt ) { - - // checks for intersections with hole edges - var ihIdx, chkHole, - hIdx, nextIdx, intersection; - for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { - - chkHole = holes[ indepHoles[ ihIdx ]]; - for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { - - nextIdx = hIdx + 1; nextIdx %= chkHole.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true ); - if ( intersection.length > 0 ) return true; - - } - - } - return false; - - } - - var holeIndex, shapeIndex, - shapePt, holePt, - holeIdx, cutKey, failedCuts = [], - tmpShape1, tmpShape2, - tmpHole1, tmpHole2; - - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - - indepHoles.push( h ); - - } - - var minShapeIndex = 0; - var counter = indepHoles.length * 2; - while ( indepHoles.length > 0 ) { - - counter --; - if ( counter < 0 ) { - - console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); - break; - - } - - // search for shape-vertex and hole-vertex, - // which can be connected without intersections - for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) { - - shapePt = shape[ shapeIndex ]; - holeIndex = - 1; - - // search for hole which can be reached without intersections - for ( var h = 0; h < indepHoles.length; h ++ ) { - - holeIdx = indepHoles[ h ]; - - // prevent multiple checks - cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; - if ( failedCuts[ cutKey ] !== undefined ) continue; - - hole = holes[ holeIdx ]; - for ( var h2 = 0; h2 < hole.length; h2 ++ ) { - - holePt = hole[ h2 ]; - if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; - if ( intersectsShapeEdge( shapePt, holePt ) ) continue; - if ( intersectsHoleEdge( shapePt, holePt ) ) continue; - - holeIndex = h2; - indepHoles.splice( h, 1 ); - - tmpShape1 = shape.slice( 0, shapeIndex + 1 ); - tmpShape2 = shape.slice( shapeIndex ); - tmpHole1 = hole.slice( holeIndex ); - tmpHole2 = hole.slice( 0, holeIndex + 1 ); - - shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); - - minShapeIndex = shapeIndex; - - // Debug only, to show the selected cuts - // glob_CutLines.push( [ shapePt, holePt ] ); - - break; - - } - if ( holeIndex >= 0 ) break; // hole-vertex found - - failedCuts[ cutKey ] = true; // remember failure - - } - if ( holeIndex >= 0 ) break; // hole-vertex found - - } - - } - - return shape; /* shape with no holes */ - - } - - - var i, il, f, face, - key, index, - allPointsMap = {}; - - // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first. - - var allpoints = contour.concat(); - - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - - Array.prototype.push.apply( allpoints, holes[ h ] ); - - } - - //console.log( "allpoints",allpoints, allpoints.length ); - - // prepare all points map - - for ( i = 0, il = allpoints.length; i < il; i ++ ) { - - key = allpoints[ i ].x + ":" + allpoints[ i ].y; - - if ( allPointsMap[ key ] !== undefined ) { - - console.warn( "THREE.ShapeUtils: Duplicate point", key, i ); - - } - - allPointsMap[ key ] = i; - - } - - // remove holes by cutting paths to holes and adding them to the shape - var shapeWithoutHoles = removeHoles( contour, holes ); - - var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape - //console.log( "triangles",triangles, triangles.length ); - - // check all face vertices against all points map - - for ( i = 0, il = triangles.length; i < il; i ++ ) { - - face = triangles[ i ]; - - for ( f = 0; f < 3; f ++ ) { - - key = face[ f ].x + ":" + face[ f ].y; - - index = allPointsMap[ key ]; - - if ( index !== undefined ) { - - face[ f ] = index; - - } - - } - - } - - return triangles.concat(); - - }, - - isClockWise: function ( pts ) { - - return THREE.ShapeUtils.area( pts ) < 0; - - }, - - // Bezier Curves formulas obtained from - // http://en.wikipedia.org/wiki/B%C3%A9zier_curve - - // Quad Bezier Functions - - b2: ( function () { - - function b2p0( t, p ) { - - var k = 1 - t; - return k * k * p; - - } - - function b2p1( t, p ) { - - return 2 * ( 1 - t ) * t * p; - - } - - function b2p2( t, p ) { - - return t * t * p; - - } - - return function b2( t, p0, p1, p2 ) { - - return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 ); - - }; - - } )(), - - // Cubic Bezier Functions - - b3: ( function () { - - function b3p0( t, p ) { - - var k = 1 - t; - return k * k * k * p; - - } - - function b3p1( t, p ) { - - var k = 1 - t; - return 3 * k * k * t * p; - - } - - function b3p2( t, p ) { - - var k = 1 - t; - return 3 * k * t * t * p; - - } - - function b3p3( t, p ) { - - return t * t * t * p; - - } - - return function b3( t, p0, p1, p2, p3 ) { - - return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 ); - - }; - - } )() - -}; - -// File:src/extras/core/Curve.js - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Extensible curve object - * - * Some common of Curve methods - * .getPoint(t), getTangent(t) - * .getPointAt(u), getTagentAt(u) - * .getPoints(), .getSpacedPoints() - * .getLength() - * .updateArcLengths() - * - * This following classes subclasses THREE.Curve: - * - * -- 2d classes -- - * THREE.LineCurve - * THREE.QuadraticBezierCurve - * THREE.CubicBezierCurve - * THREE.SplineCurve - * THREE.ArcCurve - * THREE.EllipseCurve - * - * -- 3d classes -- - * THREE.LineCurve3 - * THREE.QuadraticBezierCurve3 - * THREE.CubicBezierCurve3 - * THREE.SplineCurve3 - * - * A series of curves can be represented as a THREE.CurvePath - * - **/ - -/************************************************************** - * Abstract Curve base class - **************************************************************/ - -THREE.Curve = function () { - -}; - -THREE.Curve.prototype = { - - constructor: THREE.Curve, - - // Virtual base class method to overwrite and implement in subclasses - // - t [0 .. 1] - - getPoint: function ( t ) { - - console.warn( "THREE.Curve: Warning, getPoint() not implemented!" ); - return null; - - }, - - // Get point at relative position in curve according to arc length - // - u [0 .. 1] - - getPointAt: function ( u ) { - - var t = this.getUtoTmapping( u ); - return this.getPoint( t ); - - }, - - // Get sequence of points using getPoint( t ) - - getPoints: function ( divisions ) { - - if ( ! divisions ) divisions = 5; - - var points = []; - - for ( var d = 0; d <= divisions; d ++ ) { - - points.push( this.getPoint( d / divisions ) ); - - } - - return points; - - }, - - // Get sequence of points using getPointAt( u ) - - getSpacedPoints: function ( divisions ) { - - if ( ! divisions ) divisions = 5; - - var points = []; - - for ( var d = 0; d <= divisions; d ++ ) { - - points.push( this.getPointAt( d / divisions ) ); - - } - - return points; - - }, - - // Get total curve arc length - - getLength: function () { - - var lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; - - }, - - // Get list of cumulative segment lengths - - getLengths: function ( divisions ) { - - if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200; - - if ( this.cacheArcLengths - && ( this.cacheArcLengths.length === divisions + 1 ) - && ! this.needsUpdate ) { - - //console.log( "cached", this.cacheArcLengths ); - return this.cacheArcLengths; - - } - - this.needsUpdate = false; - - var cache = []; - var current, last = this.getPoint( 0 ); - var p, sum = 0; - - cache.push( 0 ); - - for ( p = 1; p <= divisions; p ++ ) { - - current = this.getPoint ( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; - - } - - this.cacheArcLengths = cache; - - return cache; // { sums: cache, sum:sum }; Sum is in the last element. - - }, - - updateArcLengths: function() { - - this.needsUpdate = true; - this.getLengths(); - - }, - - // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant - - getUtoTmapping: function ( u, distance ) { - - var arcLengths = this.getLengths(); - - var i = 0, il = arcLengths.length; - - var targetArcLength; // The targeted u distance value to get - - if ( distance ) { - - targetArcLength = distance; - - } else { - - targetArcLength = u * arcLengths[ il - 1 ]; - - } - - //var time = Date.now(); - - // binary search for the index with largest value smaller than target u distance - - var low = 0, high = il - 1, comparison; - - while ( low <= high ) { - - i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats - - comparison = arcLengths[ i ] - targetArcLength; - - if ( comparison < 0 ) { - - low = i + 1; - - } else if ( comparison > 0 ) { - - high = i - 1; - - } else { - - high = i; - break; - - // DONE - - } - - } - - i = high; - - //console.log('b' , i, low, high, Date.now()- time); - - if ( arcLengths[ i ] === targetArcLength ) { - - var t = i / ( il - 1 ); - return t; - - } - - // we could get finer grain at lengths, or use simple interpolation between two points - - var lengthBefore = arcLengths[ i ]; - var lengthAfter = arcLengths[ i + 1 ]; - - var segmentLength = lengthAfter - lengthBefore; - - // determine where we are between the 'before' and 'after' points - - var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - - // add that fractional amount to t - - var t = ( i + segmentFraction ) / ( il - 1 ); - - return t; - - }, - - // Returns a unit vector tangent at t - // In case any sub curve does not implement its tangent derivation, - // 2 points a small delta apart will be used to find its gradient - // which seems to give a reasonable approximation - - getTangent: function( t ) { - - var delta = 0.0001; - var t1 = t - delta; - var t2 = t + delta; - - // Capping in case of danger - - if ( t1 < 0 ) t1 = 0; - if ( t2 > 1 ) t2 = 1; - - var pt1 = this.getPoint( t1 ); - var pt2 = this.getPoint( t2 ); - - var vec = pt2.clone().sub( pt1 ); - return vec.normalize(); - - }, - - getTangentAt: function ( u ) { - - var t = this.getUtoTmapping( u ); - return this.getTangent( t ); - - } - -}; - -// TODO: Transformation for Curves? - -/************************************************************** - * 3D Curves - **************************************************************/ - -// A Factory method for creating new curve subclasses - -THREE.Curve.create = function ( constructor, getPointFunc ) { - - constructor.prototype = Object.create( THREE.Curve.prototype ); - constructor.prototype.constructor = constructor; - constructor.prototype.getPoint = getPointFunc; - - return constructor; - -}; - -// File:src/extras/core/CurvePath.js - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - **/ - -/************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ - -THREE.CurvePath = function () { - - this.curves = []; - - this.autoClose = false; // Automatically closes the path - -}; - -THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype ), { - - constructor: THREE.CurvePath, - - add: function ( curve ) { - - this.curves.push( curve ); - - }, - - closePath: function () { - - // Add a line curve if start and end of lines are not connected - var startPoint = this.curves[ 0 ].getPoint( 0 ); - var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); - - if ( ! startPoint.equals( endPoint ) ) { + index = bindings.length; - this.curves.push( new THREE.LineCurve( endPoint, startPoint ) ); + indicesByPath[ path ] = index; - } - - }, - - // To get accurate point with reference to - // entire path distance at time t, - // following has to be done: - - // 1. Length of each sub path have to be known - // 2. Locate and identify type of curve - // 3. Get t for the curve - // 4. Return curve.getPointAt(t') - - getPoint: function ( t ) { - - var d = t * this.getLength(); - var curveLengths = this.getCurveLengths(); - var i = 0; - - // To think about boundaries points. - - while ( i < curveLengths.length ) { - - if ( curveLengths[ i ] >= d ) { - - var diff = curveLengths[ i ] - d; - var curve = this.curves[ i ]; - - var segmentLength = curve.getLength(); - var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; - - return curve.getPointAt( u ); - - } - - i ++; - - } - - return null; - - // loop where sum != 0, sum > d , sum+1 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) { - - points.push( points[ 0 ] ); - - } - - return points; - - }, - - /************************************************************** - * Create Geometries Helpers - **************************************************************/ - - /// Generate geometry from path points (for Line or Points objects) - - createPointsGeometry: function ( divisions ) { - - var pts = this.getPoints( divisions ); - return this.createGeometry( pts ); - - }, - - // Generate geometry from equidistant sampling along the path - - createSpacedPointsGeometry: function ( divisions ) { - - var pts = this.getSpacedPoints( divisions ); - return this.createGeometry( pts ); - - }, - - createGeometry: function ( points ) { - - var geometry = new THREE.Geometry(); - - for ( var i = 0, l = points.length; i < l; i ++ ) { - - var point = points[ i ]; - geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) ); - - } - - return geometry; - - } - -} ); - -// File:src/extras/core/Font.js - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Font = function ( data ) { - - this.data = data; - -}; - -Object.assign( THREE.Font.prototype, { + if ( index !== undefined ) { - generateShapes: function ( text, size, divisions ) { + var paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + lastBindingsIndex = bindings.length - 1, + lastBindings = bindings[ lastBindingsIndex ], + lastBindingsPath = path[ lastBindingsIndex ]; - function createPaths( text ) { + indicesByPath[ lastBindingsPath ] = index; - var chars = String( text ).split( '' ); - var scale = size / data.resolution; - var offset = 0; + bindings[ index ] = lastBindings; + bindings.pop(); - var paths = []; + parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; + parsedPaths.pop(); - for ( var i = 0; i < chars.length; i ++ ) { + paths[ index ] = paths[ lastBindingsIndex ]; + paths.pop(); - var ret = createPath( chars[ i ], scale, offset ); - offset += ret.offset; + } - paths.push( ret.path ); + } - } + }; - return paths; + /** + * + * Action provided by AnimationMixer for scheduling clip playback on specific + * objects. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + * + */ - } - - function createPath( c, scale, offset ) { + function AnimationAction() { + this.isAnimationAction = true; - var glyph = data.glyphs[ c ] || data.glyphs[ '?' ]; + throw new Error( "THREE.AnimationAction: " + + "Use mixer.clipAction for construction." ); - if ( ! glyph ) return; + }; - var path = new THREE.ShapePath(); + AnimationAction._new = + function AnimationAction( mixer, clip, localRoot ) { - var pts = [], b2 = THREE.ShapeUtils.b2, b3 = THREE.ShapeUtils.b3; - var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot || null; - if ( glyph.o ) { + var tracks = clip.tracks, + nTracks = tracks.length, + interpolants = new Array( nTracks ); - var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); + var interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; - for ( var i = 0, l = outline.length; i < l; ) { + for ( var i = 0; i !== nTracks; ++ i ) { - var action = outline[ i ++ ]; + var interpolant = tracks[ i ].createInterpolant( null ); + interpolants[ i ] = interpolant; + interpolant.settings = interpolantSettings; - switch ( action ) { + } - case 'm': // moveTo + this._interpolantSettings = interpolantSettings; - x = outline[ i ++ ] * scale + offset; - y = outline[ i ++ ] * scale; + this._interpolants = interpolants; // bound by the mixer - path.moveTo( x, y ); + // inside: PropertyMixer (managed by the mixer) + this._propertyBindings = new Array( nTracks ); - break; + this._cacheIndex = null; // for the memory manager + this._byClipCacheIndex = null; // for the memory manager - case 'l': // lineTo + this._timeScaleInterpolant = null; + this._weightInterpolant = null; - x = outline[ i ++ ] * scale + offset; - y = outline[ i ++ ] * scale; + this.loop = LoopRepeat; + this._loopCount = -1; - path.lineTo( x, y ); + // global mixer time when the action is to be started + // it's set back to 'null' upon start of the action + this._startTime = null; - break; + // scaled local time of the action + // gets clamped or wrapped to 0..clip.duration according to loop + this.time = 0; - case 'q': // quadraticCurveTo + this.timeScale = 1; + this._effectiveTimeScale = 1; - cpx = outline[ i ++ ] * scale + offset; - cpy = outline[ i ++ ] * scale; - cpx1 = outline[ i ++ ] * scale + offset; - cpy1 = outline[ i ++ ] * scale; + this.weight = 1; + this._effectiveWeight = 1; - path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); + this.repetitions = Infinity; // no. of repetitions when looping - laste = pts[ pts.length - 1 ]; + this.paused = false; // false -> zero effective time scale + this.enabled = true; // true -> zero effective weight - if ( laste ) { + this.clampWhenFinished = false; // keep feeding the last frame? - cpx0 = laste.x; - cpy0 = laste.y; + this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate + this.zeroSlopeAtEnd = true; // clips for start, loop and end - for ( var i2 = 1; i2 <= divisions; i2 ++ ) { + }; - var t = i2 / divisions; - b2( t, cpx0, cpx1, cpx ); - b2( t, cpy0, cpy1, cpy ); + AnimationAction._new.prototype = { - } + constructor: AnimationAction._new, - } + // State & Scheduling - break; + play: function() { - case 'b': // bezierCurveTo + this._mixer._activateAction( this ); - cpx = outline[ i ++ ] * scale + offset; - cpy = outline[ i ++ ] * scale; - cpx1 = outline[ i ++ ] * scale + offset; - cpy1 = outline[ i ++ ] * scale; - cpx2 = outline[ i ++ ] * scale + offset; - cpy2 = outline[ i ++ ] * scale; + return this; - path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); + }, - laste = pts[ pts.length - 1 ]; + stop: function() { - if ( laste ) { + this._mixer._deactivateAction( this ); - cpx0 = laste.x; - cpy0 = laste.y; + return this.reset(); - for ( var i2 = 1; i2 <= divisions; i2 ++ ) { + }, - var t = i2 / divisions; - b3( t, cpx0, cpx1, cpx2, cpx ); - b3( t, cpy0, cpy1, cpy2, cpy ); + reset: function() { - } + this.paused = false; + this.enabled = true; - } + this.time = 0; // restart clip + this._loopCount = -1; // forget previous loops + this._startTime = null; // forget scheduling - break; + return this.stopFading().stopWarping(); - } + }, - } + isRunning: function() { - } + var start = this._startTime; - return { offset: glyph.ha * scale, path: path }; - - } + return this.enabled && ! this.paused && this.timeScale !== 0 && + this._startTime === null && this._mixer._isActiveAction( this ); - // + }, - if ( size === undefined ) size = 100; - if ( divisions === undefined ) divisions = 4; + // return true when play has been called + isScheduled: function() { - var data = this.data; + return this._mixer._isActiveAction( this ); - var paths = createPaths( text ); - var shapes = []; + }, - for ( var p = 0, pl = paths.length; p < pl; p ++ ) { + startAt: function( time ) { - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); + this._startTime = time; - } + return this; - return shapes; + }, - } + setLoop: function( mode, repetitions ) { -} ); + this.loop = mode; + this.repetitions = repetitions; -// File:src/extras/core/Path.js + return this; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Creates free form 2d path using series of points, lines or curves. - * - **/ + }, -THREE.Path = function ( points ) { + // Weight - THREE.CurvePath.call( this ); - this.currentPoint = new THREE.Vector2(); + // set the weight stopping any scheduled fading + // although .enabled = false yields an effective weight of zero, this + // method does *not* change .enabled, because it would be confusing + setEffectiveWeight: function( weight ) { - if ( points ) { + this.weight = weight; - this.fromPoints( points ); + // note: same logic as when updated at runtime + this._effectiveWeight = this.enabled ? weight : 0; - } + return this.stopFading(); -}; + }, -THREE.Path.prototype = Object.assign( Object.create( THREE.CurvePath.prototype ), { + // return the weight considering fading and .enabled + getEffectiveWeight: function() { - constructor: THREE.Path, + return this._effectiveWeight; - // Create path using straight lines to connect all points - // - vectors: array of Vector2 - fromPoints: function ( vectors ) { + }, - this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); + fadeIn: function( duration ) { - for ( var i = 1, l = vectors.length; i < l; i ++ ) { + return this._scheduleFading( duration, 0, 1 ); - this.lineTo( vectors[ i ].x, vectors[ i ].y ); + }, - } + fadeOut: function( duration ) { - }, + return this._scheduleFading( duration, 1, 0 ); - moveTo: function ( x, y ) { + }, - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + crossFadeFrom: function( fadeOutAction, duration, warp ) { - }, + var mixer = this._mixer; - lineTo: function ( x, y ) { + fadeOutAction.fadeOut( duration ); + this.fadeIn( duration ); - var curve = new THREE.LineCurve( this.currentPoint.clone(), new THREE.Vector2( x, y ) ); - this.curves.push( curve ); + if( warp ) { - this.currentPoint.set( x, y ); + var fadeInDuration = this._clip.duration, + fadeOutDuration = fadeOutAction._clip.duration, - }, + startEndRatio = fadeOutDuration / fadeInDuration, + endStartRatio = fadeInDuration / fadeOutDuration; - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + fadeOutAction.warp( 1.0, startEndRatio, duration ); + this.warp( endStartRatio, 1.0, duration ); - var curve = new THREE.QuadraticBezierCurve( - this.currentPoint.clone(), - new THREE.Vector2( aCPx, aCPy ), - new THREE.Vector2( aX, aY ) - ); + } - this.curves.push( curve ); + return this; - this.currentPoint.set( aX, aY ); + }, - }, + crossFadeTo: function( fadeInAction, duration, warp ) { - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + return fadeInAction.crossFadeFrom( this, duration, warp ); - var curve = new THREE.CubicBezierCurve( - this.currentPoint.clone(), - new THREE.Vector2( aCP1x, aCP1y ), - new THREE.Vector2( aCP2x, aCP2y ), - new THREE.Vector2( aX, aY ) - ); + }, - this.curves.push( curve ); + stopFading: function() { - this.currentPoint.set( aX, aY ); + var weightInterpolant = this._weightInterpolant; - }, + if ( weightInterpolant !== null ) { - splineThru: function ( pts /*Array of Vector*/ ) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant( weightInterpolant ); - var npts = [ this.currentPoint.clone() ].concat( pts ); + } - var curve = new THREE.SplineCurve( npts ); - this.curves.push( curve ); + return this; - this.currentPoint.copy( pts[ pts.length - 1 ] ); + }, - }, + // Time Scale Control - arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + // set the weight stopping any scheduled warping + // although .paused = true yields an effective time scale of zero, this + // method does *not* change .paused, because it would be confusing + setEffectiveTimeScale: function( timeScale ) { - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 :timeScale; - this.absarc( aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); + return this.stopWarping(); - }, + }, - absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + // return the time scale considering warping and .paused + getEffectiveTimeScale: function() { - this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + return this._effectiveTimeScale; - }, + }, - ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + setDuration: function( duration ) { - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; + this.timeScale = this._clip.duration / duration; - this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + return this.stopWarping(); - }, + }, - absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + syncWith: function( action ) { - var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + this.time = action.time; + this.timeScale = action.timeScale; - if ( this.curves.length > 0 ) { + return this.stopWarping(); - // if a previous curve is present, attempt to join - var firstPoint = curve.getPoint( 0 ); + }, - if ( ! firstPoint.equals( this.currentPoint ) ) { + halt: function( duration ) { - this.lineTo( firstPoint.x, firstPoint.y ); + return this.warp( this._effectiveTimeScale, 0, duration ); - } + }, - } + warp: function( startTimeScale, endTimeScale, duration ) { - this.curves.push( curve ); + var mixer = this._mixer, now = mixer.time, + interpolant = this._timeScaleInterpolant, - var lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); + timeScale = this.timeScale; - } + if ( interpolant === null ) { -} ); + interpolant = mixer._lendControlInterpolant(), + this._timeScaleInterpolant = interpolant; + } -// minimal class for proxing functions to Path. Replaces old "extractSubpaths()" -THREE.ShapePath = function() { - this.subPaths = []; - this.currentPath = null; -} + var times = interpolant.parameterPositions, + values = interpolant.sampleValues; -THREE.ShapePath.prototype = { - moveTo: function ( x, y ) { - this.currentPath = new THREE.Path(); - this.subPaths.push(this.currentPath); - this.currentPath.moveTo( x, y ); - }, - lineTo: function ( x, y ) { - this.currentPath.lineTo( x, y ); - }, - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); - }, - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); - }, - splineThru: function ( pts ) { - this.currentPath.splineThru( pts ); - }, + times[ 0 ] = now; + times[ 1 ] = now + duration; - toShapes: function ( isCCW, noHoles ) { + values[ 0 ] = startTimeScale / timeScale; + values[ 1 ] = endTimeScale / timeScale; - function toShapesNoHoles( inSubpaths ) { + return this; - var shapes = []; + }, - for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { + stopWarping: function() { - var tmpPath = inSubpaths[ i ]; + var timeScaleInterpolant = this._timeScaleInterpolant; - var tmpShape = new THREE.Shape(); - tmpShape.curves = tmpPath.curves; + if ( timeScaleInterpolant !== null ) { - shapes.push( tmpShape ); + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); - } + } - return shapes; + return this; - } + }, - function isPointInsidePolygon( inPt, inPolygon ) { + // Object Accessors - var polyLen = inPolygon.length; + getMixer: function() { - // inPt on polygon contour => immediate success or - // toggling of inside/outside at every single! intersection point of an edge - // with the horizontal line through inPt, left of inPt - // not counting lowerY endpoints of edges and whole edges on that line - var inside = false; - for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { + return this._mixer; - var edgeLowPt = inPolygon[ p ]; - var edgeHighPt = inPolygon[ q ]; + }, - var edgeDx = edgeHighPt.x - edgeLowPt.x; - var edgeDy = edgeHighPt.y - edgeLowPt.y; + getClip: function() { - if ( Math.abs( edgeDy ) > Number.EPSILON ) { + return this._clip; - // not parallel - if ( edgeDy < 0 ) { + }, - edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; - edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + getRoot: function() { - } - if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + return this._localRoot || this._mixer._root; - if ( inPt.y === edgeLowPt.y ) { + }, - if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! + // Interna - } else { + _update: function( time, deltaTime, timeDirection, accuIndex ) { + // called by the mixer - var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y ); - if ( perpEdge === 0 ) return true; // inPt is on contour ? - if ( perpEdge < 0 ) continue; - inside = ! inside; // true intersection left of inPt + var startTime = this._startTime; - } + if ( startTime !== null ) { - } else { + // check for scheduled start of action - // parallel or collinear - if ( inPt.y !== edgeLowPt.y ) continue; // parallel - // edge lies on the same horizontal line as inPt - if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || - ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! - // continue; + var timeRunning = ( time - startTime ) * timeDirection; + if ( timeRunning < 0 || timeDirection === 0 ) { - } + return; // yet to come / don't decide when delta = 0 - } + } - return inside; + // start - } + this._startTime = null; // unschedule + deltaTime = timeDirection * timeRunning; - var isClockWise = THREE.ShapeUtils.isClockWise; + } - var subPaths = this.subPaths; - if ( subPaths.length === 0 ) return []; + // apply time scale and advance time - if ( noHoles === true ) return toShapesNoHoles( subPaths ); + deltaTime *= this._updateTimeScale( time ); + var clipTime = this._updateTime( deltaTime ); + // note: _updateTime may disable the action resulting in + // an effective weight of 0 - var solid, tmpPath, tmpShape, shapes = []; + var weight = this._updateWeight( time ); - if ( subPaths.length === 1 ) { + if ( weight > 0 ) { - tmpPath = subPaths[ 0 ]; - tmpShape = new THREE.Shape(); - tmpShape.curves = tmpPath.curves; - shapes.push( tmpShape ); - return shapes; + var interpolants = this._interpolants; + var propertyMixers = this._propertyBindings; - } + for ( var j = 0, m = interpolants.length; j !== m; ++ j ) { - var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); - holesFirst = isCCW ? ! holesFirst : holesFirst; + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulate( accuIndex, weight ); - // console.log("Holes first", holesFirst); + } - var betterShapeHoles = []; - var newShapes = []; - var newShapeHoles = []; - var mainIdx = 0; - var tmpPoints; + } - newShapes[ mainIdx ] = undefined; - newShapeHoles[ mainIdx ] = []; + }, - for ( var i = 0, l = subPaths.length; i < l; i ++ ) { + _updateWeight: function( time ) { - tmpPath = subPaths[ i ]; - tmpPoints = tmpPath.getPoints(); - solid = isClockWise( tmpPoints ); - solid = isCCW ? ! solid : solid; + var weight = 0; - if ( solid ) { + if ( this.enabled ) { - if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; + weight = this.weight; + var interpolant = this._weightInterpolant; - newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints }; - newShapes[ mainIdx ].s.curves = tmpPath.curves; + if ( interpolant !== null ) { - if ( holesFirst ) mainIdx ++; - newShapeHoles[ mainIdx ] = []; + var interpolantValue = interpolant.evaluate( time )[ 0 ]; - //console.log('cw', i); + weight *= interpolantValue; - } else { + if ( time > interpolant.parameterPositions[ 1 ] ) { - newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + this.stopFading(); - //console.log('ccw', i); + if ( interpolantValue === 0 ) { - } + // faded out, disable + this.enabled = false; - } + } - // only Holes? -> probably all Shapes with wrong orientation - if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); + } + } - if ( newShapes.length > 1 ) { + } - var ambiguous = false; - var toChange = []; + this._effectiveWeight = weight; + return weight; - for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + }, - betterShapeHoles[ sIdx ] = []; + _updateTimeScale: function( time ) { - } + var timeScale = 0; - for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + if ( ! this.paused ) { - var sho = newShapeHoles[ sIdx ]; + timeScale = this.timeScale; - for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { + var interpolant = this._timeScaleInterpolant; - var ho = sho[ hIdx ]; - var hole_unassigned = true; + if ( interpolant !== null ) { - for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + var interpolantValue = interpolant.evaluate( time )[ 0 ]; - if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { + timeScale *= interpolantValue; - if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); - if ( hole_unassigned ) { + if ( time > interpolant.parameterPositions[ 1 ] ) { - hole_unassigned = false; - betterShapeHoles[ s2Idx ].push( ho ); + this.stopWarping(); - } else { + if ( timeScale === 0 ) { - ambiguous = true; + // motion has halted, pause + this.paused = true; - } + } else { - } + // warp done - apply final time scale + this.timeScale = timeScale; - } - if ( hole_unassigned ) { + } - betterShapeHoles[ sIdx ].push( ho ); + } - } + } - } + } - } - // console.log("ambiguous: ", ambiguous); - if ( toChange.length > 0 ) { + this._effectiveTimeScale = timeScale; + return timeScale; - // console.log("to change: ", toChange); - if ( ! ambiguous ) newShapeHoles = betterShapeHoles; + }, - } + _updateTime: function( deltaTime ) { - } + var time = this.time + deltaTime; - var tmpHoles; + if ( deltaTime === 0 ) return time; - for ( var i = 0, il = newShapes.length; i < il; i ++ ) { + var duration = this._clip.duration, - tmpShape = newShapes[ i ].s; - shapes.push( tmpShape ); - tmpHoles = newShapeHoles[ i ]; + loop = this.loop, + loopCount = this._loopCount; - for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + if ( loop === LoopOnce ) { - tmpShape.holes.push( tmpHoles[ j ].h ); + if ( loopCount === -1 ) { + // just started - } + this.loopCount = 0; + this._setEndings( true, true, false ); - } + } - //console.log("shape", shapes); + handle_stop: { - return shapes; + if ( time >= duration ) { - } -} + time = duration; -// File:src/extras/core/Shape.js + } else if ( time < 0 ) { -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Defines a 2d shape plane using paths. - **/ + time = 0; -// STEP 1 Create a path. -// STEP 2 Turn path into shape. -// STEP 3 ExtrudeGeometry takes in Shape/Shapes -// STEP 3a - Extract points from each shape, turn to vertices -// STEP 3b - Triangulate each shape, add faces. + } else break handle_stop; -THREE.Shape = function () { + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - THREE.Path.apply( this, arguments ); + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime < 0 ? -1 : 1 + } ); - this.holes = []; + } -}; + } else { // repetitive Repeat or PingPong -THREE.Shape.prototype = Object.assign( Object.create( THREE.Path.prototype ), { + var pingPong = ( loop === LoopPingPong ); - constructor: THREE.Shape, + if ( loopCount === -1 ) { + // just started - // Convenience method to return ExtrudeGeometry + if ( deltaTime >= 0 ) { - extrude: function ( options ) { + loopCount = 0; - return new THREE.ExtrudeGeometry( this, options ); + this._setEndings( + true, this.repetitions === 0, pingPong ); - }, + } else { - // Convenience method to return ShapeGeometry + // when looping in reverse direction, the initial + // transition through zero counts as a repetition, + // so leave loopCount at -1 - makeGeometry: function ( options ) { + this._setEndings( + this.repetitions === 0, true, pingPong ); - return new THREE.ShapeGeometry( this, options ); + } - }, + } - getPointsHoles: function ( divisions ) { + if ( time >= duration || time < 0 ) { + // wrap around - var holesPts = []; + var loopDelta = Math.floor( time / duration ); // signed + time -= duration * loopDelta; - for ( var i = 0, l = this.holes.length; i < l; i ++ ) { + loopCount += Math.abs( loopDelta ); - holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + var pending = this.repetitions - loopCount; - } + if ( pending < 0 ) { + // have to stop (switch state, clamp time, fire event) - return holesPts; + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - }, + time = deltaTime > 0 ? duration : 0; - // Get points of shape and holes (keypoints based on segments parameter) + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime > 0 ? 1 : -1 + } ); - extractAllPoints: function ( divisions ) { + } else { + // keep running - return { + if ( pending === 0 ) { + // entering the last round - shape: this.getPoints( divisions ), - holes: this.getPointsHoles( divisions ) + var atStart = deltaTime < 0; + this._setEndings( atStart, ! atStart, pingPong ); - }; + } else { - }, + this._setEndings( false, false, pingPong ); - extractPoints: function ( divisions ) { + } - return this.extractAllPoints( divisions ); + this._loopCount = loopCount; - } + this._mixer.dispatchEvent( { + type: 'loop', action: this, loopDelta: loopDelta + } ); -} ); + } -// File:src/extras/curves/LineCurve.js + } -/************************************************************** - * Line - **************************************************************/ + if ( pingPong && ( loopCount & 1 ) === 1 ) { + // invert time for the "pong round" -THREE.LineCurve = function ( v1, v2 ) { + this.time = time; + return duration - time; - this.v1 = v1; - this.v2 = v2; + } -}; + } -THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.LineCurve.prototype.constructor = THREE.LineCurve; + this.time = time; + return time; -THREE.LineCurve.prototype.getPoint = function ( t ) { + }, - if ( t === 1 ) { + _setEndings: function( atStart, atEnd, pingPong ) { - return this.v2.clone(); + var settings = this._interpolantSettings; - } + if ( pingPong ) { - var point = this.v2.clone().sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; - return point; + } else { -}; + // assuming for LoopOnce atStart == atEnd == true -// Line curve is linear, so we can overwrite default getPointAt + if ( atStart ) { -THREE.LineCurve.prototype.getPointAt = function ( u ) { + settings.endingStart = this.zeroSlopeAtStart ? + ZeroSlopeEnding : ZeroCurvatureEnding; - return this.getPoint( u ); + } else { -}; + settings.endingStart = WrapAroundEnding; -THREE.LineCurve.prototype.getTangent = function( t ) { + } - var tangent = this.v2.clone().sub( this.v1 ); + if ( atEnd ) { - return tangent.normalize(); + settings.endingEnd = this.zeroSlopeAtEnd ? + ZeroSlopeEnding : ZeroCurvatureEnding; -}; + } else { -// File:src/extras/curves/QuadraticBezierCurve.js + settings.endingEnd = WrapAroundEnding; -/************************************************************** - * Quadratic Bezier curve - **************************************************************/ + } + } -THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { + }, - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + _scheduleFading: function( duration, weightNow, weightThen ) { -}; + var mixer = this._mixer, now = mixer.time, + interpolant = this._weightInterpolant; -THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve; + if ( interpolant === null ) { + interpolant = mixer._lendControlInterpolant(), + this._weightInterpolant = interpolant; -THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { + } - var b2 = THREE.ShapeUtils.b2; + var times = interpolant.parameterPositions, + values = interpolant.sampleValues; - return new THREE.Vector2( - b2( t, this.v0.x, this.v1.x, this.v2.x ), - b2( t, this.v0.y, this.v1.y, this.v2.y ) - ); + times[ 0 ] = now; values[ 0 ] = weightNow; + times[ 1 ] = now + duration; values[ 1 ] = weightThen; -}; + return this; + } -THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) { + }; - var tangentQuadraticBezier = THREE.CurveUtils.tangentQuadraticBezier; + /** + * + * Player for AnimationClips. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - return new THREE.Vector2( - tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ), - tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ) - ).normalize(); + function AnimationMixer( root ) { + this.isAnimationMixer = true; -}; + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; -// File:src/extras/curves/CubicBezierCurve.js + this.time = 0; -/************************************************************** - * Cubic Bezier curve - **************************************************************/ + this.timeScale = 1.0; -THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { + }; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, { -}; + // return an action for a clip optionally using a custom root target + // object (this method allocates a lot of dynamic memory in case a + // previously unknown clip/root combination is specified) + clipAction: function( clip, optionalRoot ) { -THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve; + var root = optionalRoot || this._root, + rootUuid = root.uuid, -THREE.CubicBezierCurve.prototype.getPoint = function ( t ) { + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, - var b3 = THREE.ShapeUtils.b3; + clipUuid = clipObject !== null ? clipObject.uuid : clip, - return new THREE.Vector2( - b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), - b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) - ); + actionsForClip = this._actionsByClip[ clipUuid ], + prototypeAction = null; -}; + if ( actionsForClip !== undefined ) { -THREE.CubicBezierCurve.prototype.getTangent = function( t ) { + var existingAction = + actionsForClip.actionByRoot[ rootUuid ]; - var tangentCubicBezier = THREE.CurveUtils.tangentCubicBezier; + if ( existingAction !== undefined ) { - return new THREE.Vector2( - tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), - tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) - ).normalize(); + return existingAction; -}; + } -// File:src/extras/curves/SplineCurve.js + // we know the clip, so we don't have to parse all + // the bindings again but can just copy + prototypeAction = actionsForClip.knownActions[ 0 ]; -/************************************************************** - * Spline curve - **************************************************************/ + // also, take the clip from the prototype action + if ( clipObject === null ) + clipObject = prototypeAction._clip; -THREE.SplineCurve = function ( points /* array of Vector2 */ ) { + } - this.points = ( points == undefined ) ? [] : points; + // clip must be known when specified via string + if ( clipObject === null ) return null; -}; + // allocate all resources required to run it + var newAction = new AnimationMixer._Action( this, clipObject, optionalRoot ); -THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.SplineCurve.prototype.constructor = THREE.SplineCurve; + this._bindAction( newAction, prototypeAction ); -THREE.SplineCurve.prototype.getPoint = function ( t ) { + // and make the action known to the memory manager + this._addInactiveAction( newAction, clipUuid, rootUuid ); - var points = this.points; - var point = ( points.length - 1 ) * t; + return newAction; - var intPoint = Math.floor( point ); - var weight = point - intPoint; + }, - var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; - var point1 = points[ intPoint ]; - var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; - var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + // get an existing action + existingAction: function( clip, optionalRoot ) { - var interpolate = THREE.CurveUtils.interpolate; + var root = optionalRoot || this._root, + rootUuid = root.uuid, - return new THREE.Vector2( - interpolate( point0.x, point1.x, point2.x, point3.x, weight ), - interpolate( point0.y, point1.y, point2.y, point3.y, weight ) - ); + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, -}; + clipUuid = clipObject ? clipObject.uuid : clip, -// File:src/extras/curves/EllipseCurve.js + actionsForClip = this._actionsByClip[ clipUuid ]; -/************************************************************** - * Ellipse curve - **************************************************************/ + if ( actionsForClip !== undefined ) { -THREE.EllipseCurve = function( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + return actionsForClip.actionByRoot[ rootUuid ] || null; - this.aX = aX; - this.aY = aY; + } - this.xRadius = xRadius; - this.yRadius = yRadius; + return null; - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; + }, - this.aClockwise = aClockwise; + // deactivates all previously scheduled actions + stopAllAction: function() { - this.aRotation = aRotation || 0; + var actions = this._actions, + nActions = this._nActiveActions, + bindings = this._bindings, + nBindings = this._nActiveBindings; -}; + this._nActiveActions = 0; + this._nActiveBindings = 0; -THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve; + for ( var i = 0; i !== nActions; ++ i ) { -THREE.EllipseCurve.prototype.getPoint = function( t ) { + actions[ i ].reset(); - var twoPi = Math.PI * 2; - var deltaAngle = this.aEndAngle - this.aStartAngle; - var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + } - // ensures that deltaAngle is 0 .. 2 PI - while ( deltaAngle < 0 ) deltaAngle += twoPi; - while ( deltaAngle > twoPi ) deltaAngle -= twoPi; + for ( var i = 0; i !== nBindings; ++ i ) { - if ( deltaAngle < Number.EPSILON ) { + bindings[ i ].useCount = 0; - if ( samePoints ) { + } - deltaAngle = 0; + return this; - } else { + }, - deltaAngle = twoPi; + // advance the time and update apply the animation + update: function( deltaTime ) { - } + deltaTime *= this.timeScale; - } + var actions = this._actions, + nActions = this._nActiveActions, - if ( this.aClockwise === true && ! samePoints ) { + time = this.time += deltaTime, + timeDirection = Math.sign( deltaTime ), - if ( deltaAngle === twoPi ) { + accuIndex = this._accuIndex ^= 1; - deltaAngle = - twoPi; + // run active actions - } else { + for ( var i = 0; i !== nActions; ++ i ) { - deltaAngle = deltaAngle - twoPi; + var action = actions[ i ]; - } + if ( action.enabled ) { - } + action._update( time, deltaTime, timeDirection, accuIndex ); - var angle = this.aStartAngle + t * deltaAngle; - var x = this.aX + this.xRadius * Math.cos( angle ); - var y = this.aY + this.yRadius * Math.sin( angle ); + } - if ( this.aRotation !== 0 ) { + } - var cos = Math.cos( this.aRotation ); - var sin = Math.sin( this.aRotation ); + // update scene graph - var tx = x - this.aX; - var ty = y - this.aY; + var bindings = this._bindings, + nBindings = this._nActiveBindings; - // Rotate the point about the center of the ellipse. - x = tx * cos - ty * sin + this.aX; - y = tx * sin + ty * cos + this.aY; + for ( var i = 0; i !== nBindings; ++ i ) { - } + bindings[ i ].apply( accuIndex ); - return new THREE.Vector2( x, y ); + } -}; + return this; -// File:src/extras/curves/ArcCurve.js + }, -/************************************************************** - * Arc curve - **************************************************************/ + // return this mixer's root target object + getRoot: function() { -THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + return this._root; - THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + }, -}; + // free all resources specific to a particular clip + uncacheClip: function( clip ) { -THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype ); -THREE.ArcCurve.prototype.constructor = THREE.ArcCurve; + var actions = this._actions, + clipUuid = clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; -// File:src/extras/curves/LineCurve3.js + if ( actionsForClip !== undefined ) { -/************************************************************** - * Line3D - **************************************************************/ + // note: just calling _removeInactiveAction would mess up the + // iteration state and also require updating the state we can + // just throw away -THREE.LineCurve3 = THREE.Curve.create( + var actionsToRemove = actionsForClip.knownActions; - function ( v1, v2 ) { + for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) { - this.v1 = v1; - this.v2 = v2; + var action = actionsToRemove[ i ]; - }, + this._deactivateAction( action ); - function ( t ) { + var cacheIndex = action._cacheIndex, + lastInactiveAction = actions[ actions.length - 1 ]; - if ( t === 1 ) { + action._cacheIndex = null; + action._byClipCacheIndex = null; - return this.v2.clone(); + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); - } + this._removeInactiveBindingsForAction( action ); - var vector = new THREE.Vector3(); + } - vector.subVectors( this.v2, this.v1 ); // diff - vector.multiplyScalar( t ); - vector.add( this.v1 ); + delete actionsByClip[ clipUuid ]; - return vector; + } - } + }, -); + // free all resources specific to a particular root target object + uncacheRoot: function( root ) { -// File:src/extras/curves/QuadraticBezierCurve3.js + var rootUuid = root.uuid, + actionsByClip = this._actionsByClip; -/************************************************************** - * Quadratic Bezier 3D curve - **************************************************************/ + for ( var clipUuid in actionsByClip ) { -THREE.QuadraticBezierCurve3 = THREE.Curve.create( + var actionByRoot = actionsByClip[ clipUuid ].actionByRoot, + action = actionByRoot[ rootUuid ]; - function ( v0, v1, v2 ) { + if ( action !== undefined ) { - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + this._deactivateAction( action ); + this._removeInactiveAction( action ); - }, + } - function ( t ) { + } - var b2 = THREE.ShapeUtils.b2; + var bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ]; - return new THREE.Vector3( - b2( t, this.v0.x, this.v1.x, this.v2.x ), - b2( t, this.v0.y, this.v1.y, this.v2.y ), - b2( t, this.v0.z, this.v1.z, this.v2.z ) - ); + if ( bindingByName !== undefined ) { - } + for ( var trackName in bindingByName ) { -); + var binding = bindingByName[ trackName ]; + binding.restoreOriginalState(); + this._removeInactiveBinding( binding ); -// File:src/extras/curves/CubicBezierCurve3.js + } -/************************************************************** - * Cubic Bezier 3D curve - **************************************************************/ + } -THREE.CubicBezierCurve3 = THREE.Curve.create( + }, - function ( v0, v1, v2, v3 ) { + // remove a targeted clip from the cache + uncacheAction: function( clip, optionalRoot ) { - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + var action = this.existingAction( clip, optionalRoot ); - }, + if ( action !== null ) { - function ( t ) { + this._deactivateAction( action ); + this._removeInactiveAction( action ); - var b3 = THREE.ShapeUtils.b3; + } - return new THREE.Vector3( - b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), - b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ), - b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ) - ); + } - } + } ); -); + AnimationMixer._Action = AnimationAction._new; -// File:src/extras/curves/SplineCurve3.js + // Implementation details: -/************************************************************** - * Spline 3D curve - **************************************************************/ + Object.assign( AnimationMixer.prototype, { + _bindAction: function( action, prototypeAction ) { -THREE.SplineCurve3 = THREE.Curve.create( + var root = action._localRoot || this._root, + tracks = action._clip.tracks, + nTracks = tracks.length, + bindings = action._propertyBindings, + interpolants = action._interpolants, + rootUuid = root.uuid, + bindingsByRoot = this._bindingsByRootAndName, + bindingsByName = bindingsByRoot[ rootUuid ]; - function ( points /* array of Vector3 */ ) { + if ( bindingsByName === undefined ) { - console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' ); - this.points = ( points == undefined ) ? [] : points; + bindingsByName = {}; + bindingsByRoot[ rootUuid ] = bindingsByName; - }, + } - function ( t ) { + for ( var i = 0; i !== nTracks; ++ i ) { - var points = this.points; - var point = ( points.length - 1 ) * t; + var track = tracks[ i ], + trackName = track.name, + binding = bindingsByName[ trackName ]; - var intPoint = Math.floor( point ); - var weight = point - intPoint; + if ( binding !== undefined ) { - var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ]; - var point1 = points[ intPoint ]; - var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; - var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + bindings[ i ] = binding; - var interpolate = THREE.CurveUtils.interpolate; + } else { - return new THREE.Vector3( - interpolate( point0.x, point1.x, point2.x, point3.x, weight ), - interpolate( point0.y, point1.y, point2.y, point3.y, weight ), - interpolate( point0.z, point1.z, point2.z, point3.z, weight ) - ); + binding = bindings[ i ]; - } + if ( binding !== undefined ) { -); + // existing binding, make sure the cache knows -// File:src/extras/curves/CatmullRomCurve3.js + if ( binding._cacheIndex === null ) { -/** - * @author zz85 https://github.com/zz85 - * - * Centripetal CatmullRom Curve - which is useful for avoiding - * cusps and self-intersections in non-uniform catmull rom curves. - * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf - * - * curve.type accepts centripetal(default), chordal and catmullrom - * curve.tension is used for catmullrom which defaults to 0.5 - */ + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); -THREE.CatmullRomCurve3 = ( function() { + } - var - tmp = new THREE.Vector3(), - px = new CubicPoly(), - py = new CubicPoly(), - pz = new CubicPoly(); + continue; - /* - Based on an optimized c++ solution in - - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ - - http://ideone.com/NoEbVM + } - This CubicPoly class could be used for reusing some variables and calculations, - but for three.js curve use, it could be possible inlined and flatten into a single function call - which can be placed in CurveUtils. - */ + var path = prototypeAction && prototypeAction. + _propertyBindings[ i ].binding.parsedPath; - function CubicPoly() { + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), + track.ValueTypeName, track.getValueSize() ); - } + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); - /* - * Compute coefficients for a cubic polynomial - * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 - * such that - * p(0) = x0, p(1) = x1 - * and - * p'(0) = t0, p'(1) = t1. - */ - CubicPoly.prototype.init = function( x0, x1, t0, t1 ) { - - this.c0 = x0; - this.c1 = t0; - this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; - this.c3 = 2 * x0 - 2 * x1 + t0 + t1; + bindings[ i ] = binding; - }; + } - CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) { + interpolants[ i ].resultBuffer = binding.buffer; - // compute tangents when parameterized in [t1,t2] - var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; - var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; + } - // rescale tangents for parametrization in [0,1] - t1 *= dt1; - t2 *= dt1; + }, - // initCubicPoly - this.init( x1, x2, t1, t2 ); + _activateAction: function( action ) { - }; + if ( ! this._isActiveAction( action ) ) { - // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4 - CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) { + if ( action._cacheIndex === null ) { - this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + // this action has been forgotten by the cache, but the user + // appears to be still using it -> rebind - }; + var rootUuid = ( action._localRoot || this._root ).uuid, + clipUuid = action._clip.uuid, + actionsForClip = this._actionsByClip[ clipUuid ]; - CubicPoly.prototype.calc = function( t ) { + this._bindAction( action, + actionsForClip && actionsForClip.knownActions[ 0 ] ); - var t2 = t * t; - var t3 = t2 * t; - return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3; + this._addInactiveAction( action, clipUuid, rootUuid ); - }; + } - // Subclass Three.js curve - return THREE.Curve.create( + var bindings = action._propertyBindings; - function ( p /* array of Vector3 */ ) { + // increment reference counts / sort out state + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - this.points = p || []; - this.closed = false; + var binding = bindings[ i ]; - }, + if ( binding.useCount ++ === 0 ) { - function ( t ) { + this._lendBinding( binding ); + binding.saveOriginalState(); - var points = this.points, - point, intPoint, weight, l; + } - l = points.length; + } - if ( l < 2 ) console.log( 'duh, you need at least 2 points' ); + this._lendAction( action ); - point = ( l - ( this.closed ? 0 : 1 ) ) * t; - intPoint = Math.floor( point ); - weight = point - intPoint; + } - if ( this.closed ) { + }, - intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; + _deactivateAction: function( action ) { - } else if ( weight === 0 && intPoint === l - 1 ) { + if ( this._isActiveAction( action ) ) { - intPoint = l - 2; - weight = 1; + var bindings = action._propertyBindings; - } + // decrement reference counts / sort out state + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - var p0, p1, p2, p3; // 4 points + var binding = bindings[ i ]; - if ( this.closed || intPoint > 0 ) { + if ( -- binding.useCount === 0 ) { - p0 = points[ ( intPoint - 1 ) % l ]; + binding.restoreOriginalState(); + this._takeBackBinding( binding ); - } else { + } - // extrapolate first point - tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); - p0 = tmp; + } - } + this._takeBackAction( action ); - p1 = points[ intPoint % l ]; - p2 = points[ ( intPoint + 1 ) % l ]; + } - if ( this.closed || intPoint + 2 < l ) { + }, - p3 = points[ ( intPoint + 2 ) % l ]; + // Memory manager - } else { + _initMemoryManager: function() { - // extrapolate last point - tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); - p3 = tmp; + this._actions = []; // 'nActiveActions' followed by inactive ones + this._nActiveActions = 0; - } + this._actionsByClip = {}; + // inside: + // { + // knownActions: Array< _Action > - used as prototypes + // actionByRoot: _Action - lookup + // } - if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) { - // init Centripetal / Chordal Catmull-Rom - var pow = this.type === 'chordal' ? 0.5 : 0.25; - var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); - var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); - var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + this._bindings = []; // 'nActiveBindings' followed by inactive ones + this._nActiveBindings = 0; - // safety check for repeated points - if ( dt1 < 1e-4 ) dt1 = 1.0; - if ( dt0 < 1e-4 ) dt0 = dt1; - if ( dt2 < 1e-4 ) dt2 = dt1; + this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > - px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); - py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); - pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); - } else if ( this.type === 'catmullrom' ) { + this._controlInterpolants = []; // same game as above + this._nActiveControlInterpolants = 0; - var tension = this.tension !== undefined ? this.tension : 0.5; - px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension ); - py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension ); - pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension ); + var scope = this; - } + this.stats = { - var v = new THREE.Vector3( - px.calc( weight ), - py.calc( weight ), - pz.calc( weight ) - ); + actions: { + get total() { return scope._actions.length; }, + get inUse() { return scope._nActiveActions; } + }, + bindings: { + get total() { return scope._bindings.length; }, + get inUse() { return scope._nActiveBindings; } + }, + controlInterpolants: { + get total() { return scope._controlInterpolants.length; }, + get inUse() { return scope._nActiveControlInterpolants; } + } - return v; + }; - } + }, - ); + // Memory management for _Action objects -} )(); + _isActiveAction: function( action ) { -// File:src/extras/curves/ClosedSplineCurve3.js + var index = action._cacheIndex; + return index !== null && index < this._nActiveActions; -/************************************************************** - * Closed Spline 3D curve - **************************************************************/ + }, + _addInactiveAction: function( action, clipUuid, rootUuid ) { -THREE.ClosedSplineCurve3 = function ( points ) { + var actions = this._actions, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; - console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' ); + if ( actionsForClip === undefined ) { - THREE.CatmullRomCurve3.call( this, points ); - this.type = 'catmullrom'; - this.closed = true; + actionsForClip = { -}; + knownActions: [ action ], + actionByRoot: {} -THREE.ClosedSplineCurve3.prototype = Object.create( THREE.CatmullRomCurve3.prototype ); + }; -// File:src/extras/geometries/BoxGeometry.js + action._byClipCacheIndex = 0; -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as - */ + actionsByClip[ clipUuid ] = actionsForClip; -THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + } else { - THREE.Geometry.call( this ); + var knownActions = actionsForClip.knownActions; - this.type = 'BoxGeometry'; + action._byClipCacheIndex = knownActions.length; + knownActions.push( action ); - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + } - this.fromBufferGeometry( new THREE.BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); - this.mergeVertices(); + action._cacheIndex = actions.length; + actions.push( action ); -}; + actionsForClip.actionByRoot[ rootUuid ] = action; -THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry; + }, -THREE.CubeGeometry = THREE.BoxGeometry; + _removeInactiveAction: function( action ) { -// File:src/extras/geometries/BoxBufferGeometry.js + var actions = this._actions, + lastInactiveAction = actions[ actions.length - 1 ], + cacheIndex = action._cacheIndex; -/** - * @author Mugen87 / https://github.com/Mugen87 - */ + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); -THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + action._cacheIndex = null; - THREE.BufferGeometry.call( this ); - this.type = 'BoxBufferGeometry'; + var clipUuid = action._clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ], + knownActionsForClip = actionsForClip.knownActions, - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + lastKnownAction = + knownActionsForClip[ knownActionsForClip.length - 1 ], - var scope = this; + byClipCacheIndex = action._byClipCacheIndex; - // segments - widthSegments = Math.floor( widthSegments ) || 1; - heightSegments = Math.floor( heightSegments ) || 1; - depthSegments = Math.floor( depthSegments ) || 1; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; + knownActionsForClip.pop(); - // these are used to calculate buffer length - var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments ); - var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments ); + action._byClipCacheIndex = null; - // buffers - var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); - var vertices = new Float32Array( vertexCount * 3 ); - var normals = new Float32Array( vertexCount * 3 ); - var uvs = new Float32Array( vertexCount * 2 ); - // offset variables - var vertexBufferOffset = 0; - var uvBufferOffset = 0; - var indexBufferOffset = 0; - var numberOfVertices = 0; + var actionByRoot = actionsForClip.actionByRoot, + rootUuid = ( actions._localRoot || this._root ).uuid; - // group variables - var groupStart = 0; + delete actionByRoot[ rootUuid ]; - // build each side of the box geometry - buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px - buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx - buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py - buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny - buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz - buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz + if ( knownActionsForClip.length === 0 ) { - // build geometry - this.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + delete actionsByClip[ clipUuid ]; - // helper functions + } - function calculateVertexCount ( w, h, d ) { + this._removeInactiveBindingsForAction( action ); - var vertices = 0; + }, - // calculate the amount of vertices for each side (plane) - vertices += (w + 1) * (h + 1) * 2; // xy - vertices += (w + 1) * (d + 1) * 2; // xz - vertices += (d + 1) * (h + 1) * 2; // zy + _removeInactiveBindingsForAction: function( action ) { - return vertices; + var bindings = action._propertyBindings; + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - } + var binding = bindings[ i ]; - function calculateIndexCount ( w, h, d ) { + if ( -- binding.referenceCount === 0 ) { - var index = 0; + this._removeInactiveBinding( binding ); - // calculate the amount of squares for each side - index += w * h * 2; // xy - index += w * d * 2; // xz - index += d * h * 2; // zy + } - return index * 6; // two triangles per square => six vertices per square + } - } + }, - function buildPlane ( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + _lendAction: function( action ) { - var segmentWidth = width / gridX; - var segmentHeight = height / gridY; + // [ active actions | inactive actions ] + // [ active actions >| inactive actions ] + // s a + // <-swap-> + // a s - var widthHalf = width / 2; - var heightHalf = height / 2; - var depthHalf = depth / 2; + var actions = this._actions, + prevIndex = action._cacheIndex, - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + lastActiveIndex = this._nActiveActions ++, - var vertexCounter = 0; - var groupCount = 0; + firstInactiveAction = actions[ lastActiveIndex ]; - var vector = new THREE.Vector3(); + action._cacheIndex = lastActiveIndex; + actions[ lastActiveIndex ] = action; - // generate vertices, normals and uvs + firstInactiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = firstInactiveAction; - for ( var iy = 0; iy < gridY1; iy ++ ) { + }, - var y = iy * segmentHeight - heightHalf; + _takeBackAction: function( action ) { - for ( var ix = 0; ix < gridX1; ix ++ ) { + // [ active actions | inactive actions ] + // [ active actions |< inactive actions ] + // a s + // <-swap-> + // s a - var x = ix * segmentWidth - widthHalf; + var actions = this._actions, + prevIndex = action._cacheIndex, - // set values to correct vector component - vector[ u ] = x * udir; - vector[ v ] = y * vdir; - vector[ w ] = depthHalf; + firstInactiveIndex = -- this._nActiveActions, - // now apply vector to vertex buffer - vertices[ vertexBufferOffset ] = vector.x; - vertices[ vertexBufferOffset + 1 ] = vector.y; - vertices[ vertexBufferOffset + 2 ] = vector.z; + lastActiveAction = actions[ firstInactiveIndex ]; - // set values to correct vector component - vector[ u ] = 0; - vector[ v ] = 0; - vector[ w ] = depth > 0 ? 1 : - 1; + action._cacheIndex = firstInactiveIndex; + actions[ firstInactiveIndex ] = action; - // now apply vector to normal buffer - normals[ vertexBufferOffset ] = vector.x; - normals[ vertexBufferOffset + 1 ] = vector.y; - normals[ vertexBufferOffset + 2 ] = vector.z; + lastActiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = lastActiveAction; - // uvs - uvs[ uvBufferOffset ] = ix / gridX; - uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY ); + }, - // update offsets and counters - vertexBufferOffset += 3; - uvBufferOffset += 2; - vertexCounter += 1; + // Memory management for PropertyMixer objects - } + _addInactiveBinding: function( binding, rootUuid, trackName ) { - } + var bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], - // 1. you need three indices to draw a single face - // 2. a single segment consists of two faces - // 3. so we need to generate six (2*3) indices per segment + bindings = this._bindings; - for ( iy = 0; iy < gridY; iy ++ ) { + if ( bindingByName === undefined ) { - for ( ix = 0; ix < gridX; ix ++ ) { + bindingByName = {}; + bindingsByRoot[ rootUuid ] = bindingByName; - // indices - var a = numberOfVertices + ix + gridX1 * iy; - var b = numberOfVertices + ix + gridX1 * ( iy + 1 ); - var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; + } - // face one - indices[ indexBufferOffset ] = a; - indices[ indexBufferOffset + 1 ] = b; - indices[ indexBufferOffset + 2 ] = d; + bindingByName[ trackName ] = binding; - // face two - indices[ indexBufferOffset + 3 ] = b; - indices[ indexBufferOffset + 4 ] = c; - indices[ indexBufferOffset + 5 ] = d; + binding._cacheIndex = bindings.length; + bindings.push( binding ); - // update offsets and counters - indexBufferOffset += 6; - groupCount += 6; + }, - } + _removeInactiveBinding: function( binding ) { - } + var bindings = this._bindings, + propBinding = binding.binding, + rootUuid = propBinding.rootNode.uuid, + trackName = propBinding.path, + bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, materialIndex ); + lastInactiveBinding = bindings[ bindings.length - 1 ], + cacheIndex = binding._cacheIndex; - // calculate new start value for groups - groupStart += groupCount; + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[ cacheIndex ] = lastInactiveBinding; + bindings.pop(); - // update total number of vertices - numberOfVertices += vertexCounter; + delete bindingByName[ trackName ]; - } + remove_empty_map: { -}; + for ( var _ in bindingByName ) break remove_empty_map; -THREE.BoxBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.BoxBufferGeometry.prototype.constructor = THREE.BoxBufferGeometry; + delete bindingsByRoot[ rootUuid ]; -// File:src/extras/geometries/CircleGeometry.js + } -/** - * @author hughes - */ + }, -THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) { + _lendBinding: function( binding ) { - THREE.Geometry.call( this ); + var bindings = this._bindings, + prevIndex = binding._cacheIndex, - this.type = 'CircleGeometry'; + lastActiveIndex = this._nActiveBindings ++, - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + firstInactiveBinding = bindings[ lastActiveIndex ]; - this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); + binding._cacheIndex = lastActiveIndex; + bindings[ lastActiveIndex ] = binding; -}; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = firstInactiveBinding; -THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry; + }, -// File:src/extras/geometries/CircleBufferGeometry.js + _takeBackBinding: function( binding ) { -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + var bindings = this._bindings, + prevIndex = binding._cacheIndex, -THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) { + firstInactiveIndex = -- this._nActiveBindings, - THREE.BufferGeometry.call( this ); + lastActiveBinding = bindings[ firstInactiveIndex ]; - this.type = 'CircleBufferGeometry'; + binding._cacheIndex = firstInactiveIndex; + bindings[ firstInactiveIndex ] = binding; - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + lastActiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = lastActiveBinding; - radius = radius || 50; - segments = segments !== undefined ? Math.max( 3, segments ) : 8; + }, - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - var vertices = segments + 2; + // Memory management of Interpolants for weight and time scale - var positions = new Float32Array( vertices * 3 ); - var normals = new Float32Array( vertices * 3 ); - var uvs = new Float32Array( vertices * 2 ); + _lendControlInterpolant: function() { - // center data is already zero, but need to set a few extras - normals[ 2 ] = 1.0; - uvs[ 0 ] = 0.5; - uvs[ 1 ] = 0.5; + var interpolants = this._controlInterpolants, + lastActiveIndex = this._nActiveControlInterpolants ++, + interpolant = interpolants[ lastActiveIndex ]; - for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) { + if ( interpolant === undefined ) { - var segment = thetaStart + s / segments * thetaLength; + interpolant = new LinearInterpolant( + new Float32Array( 2 ), new Float32Array( 2 ), + 1, this._controlInterpolantsResultBuffer ); - positions[ i ] = radius * Math.cos( segment ); - positions[ i + 1 ] = radius * Math.sin( segment ); + interpolant.__cacheIndex = lastActiveIndex; + interpolants[ lastActiveIndex ] = interpolant; - normals[ i + 2 ] = 1; // normal z + } - uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2; - uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2; + return interpolant; - } + }, - var indices = []; + _takeBackControlInterpolant: function( interpolant ) { - for ( var i = 1; i <= segments; i ++ ) { + var interpolants = this._controlInterpolants, + prevIndex = interpolant.__cacheIndex, - indices.push( i, i + 1, 0 ); + firstInactiveIndex = -- this._nActiveControlInterpolants, - } + lastActiveInterpolant = interpolants[ firstInactiveIndex ]; - this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[ firstInactiveIndex ] = interpolant; - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[ prevIndex ] = lastActiveInterpolant; -}; + }, -THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry; + _controlInterpolantsResultBuffer: new Float32Array( 1 ) -// File:src/extras/geometries/CylinderBufferGeometry.js + } ); -/** - * @author Mugen87 / https://github.com/Mugen87 - */ + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + function Uniform ( value ) { + this.isUniform = true; - THREE.BufferGeometry.call( this ); + if ( typeof value === 'string' ) { - this.type = 'CylinderBufferGeometry'; + console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); + value = arguments[ 1 ]; - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } - var scope = this; + this.value = value; - radiusTop = radiusTop !== undefined ? radiusTop : 20; - radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; - height = height !== undefined ? height : 100; + this.dynamic = false; - radialSegments = Math.floor( radialSegments ) || 8; - heightSegments = Math.floor( heightSegments ) || 1; + }; - openEnded = openEnded !== undefined ? openEnded : false; - thetaStart = thetaStart !== undefined ? thetaStart : 0.0; - thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI; + Uniform.prototype = { - // used to calculate buffer length + constructor: Uniform, - var nbCap = 0; + onUpdate: function ( callback ) { - if ( openEnded === false ) { + this.dynamic = true; + this.onUpdateCallback = callback; - if ( radiusTop > 0 ) nbCap ++; - if ( radiusBottom > 0 ) nbCap ++; + return this; - } + } - var vertexCount = calculateVertexCount(); - var indexCount = calculateIndexCount(); + }; - // buffers + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + function InstancedBufferGeometry () { + this.isInstancedBufferGeometry = this.isBufferGeometry = true; - // helper variables + BufferGeometry.call( this ); - var index = 0, - indexOffset = 0, - indexArray = [], - halfHeight = height / 2; + this.type = 'InstancedBufferGeometry'; + this.maxInstancedCount = undefined; - // group variables - var groupStart = 0; + }; - // generate geometry + InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry; - generateTorso(); + InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { - if ( openEnded === false ) { + this.groups.push( { - if ( radiusTop > 0 ) generateCap( true ); - if ( radiusBottom > 0 ) generateCap( false ); + start: start, + count: count, + instances: instances - } + } ); - // build geometry + }; - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + InstancedBufferGeometry.prototype.copy = function ( source ) { - // helper functions + var index = source.index; - function calculateVertexCount() { + if ( index !== null ) { - var count = ( radialSegments + 1 ) * ( heightSegments + 1 ); + this.setIndex( index.clone() ); - if ( openEnded === false ) { + } - count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap ); + var attributes = source.attributes; - } + for ( var name in attributes ) { - return count; + var attribute = attributes[ name ]; + this.addAttribute( name, attribute.clone() ); - } + } - function calculateIndexCount() { + var groups = source.groups; - var count = radialSegments * heightSegments * 2 * 3; + for ( var i = 0, l = groups.length; i < l; i ++ ) { - if ( openEnded === false ) { + var group = groups[ i ]; + this.addGroup( group.start, group.count, group.instances ); - count += radialSegments * nbCap * 3; + } - } + return this; - return count; + }; - } + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - function generateTorso() { + function InterleavedBufferAttribute ( interleavedBuffer, itemSize, offset, normalized ) { + this.isInterleavedBufferAttribute = true; - var x, y; - var normal = new THREE.Vector3(); - var vertex = new THREE.Vector3(); + this.uuid = exports.Math.generateUUID(); - var groupCount = 0; + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; - // this will be used to calculate the normal - var tanTheta = ( radiusBottom - radiusTop ) / height; + this.normalized = normalized === true; - // generate vertices, normals and uvs + }; - for ( y = 0; y <= heightSegments; y ++ ) { - var indexRow = []; + InterleavedBufferAttribute.prototype = { - var v = y / heightSegments; + constructor: InterleavedBufferAttribute, - // calculate the radius of the current row - var radius = v * ( radiusBottom - radiusTop ) + radiusTop; + get length() { - for ( x = 0; x <= radialSegments; x ++ ) { + console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); + return this.array.length; - var u = x / radialSegments; + }, - // vertex - vertex.x = radius * Math.sin( u * thetaLength + thetaStart ); - vertex.y = - v * height + halfHeight; - vertex.z = radius * Math.cos( u * thetaLength + thetaStart ); - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + get count() { - // normal - normal.copy( vertex ); + return this.data.count; - // handle special case if radiusTop/radiusBottom is zero + }, - if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) { + get array() { - normal.x = Math.sin( u * thetaLength + thetaStart ); - normal.z = Math.cos( u * thetaLength + thetaStart ); + return this.data.array; - } + }, - normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize(); - normals.setXYZ( index, normal.x, normal.y, normal.z ); + setX: function ( index, x ) { - // uv - uvs.setXY( index, u, 1 - v ); + this.data.array[ index * this.data.stride + this.offset ] = x; - // save index of vertex in respective row - indexRow.push( index ); + return this; - // increase index - index ++; + }, - } + setY: function ( index, y ) { - // now save vertices of the row in our index array - indexArray.push( indexRow ); + this.data.array[ index * this.data.stride + this.offset + 1 ] = y; - } + return this; - // generate indices + }, - for ( x = 0; x < radialSegments; x ++ ) { + setZ: function ( index, z ) { - for ( y = 0; y < heightSegments; y ++ ) { + this.data.array[ index * this.data.stride + this.offset + 2 ] = z; - // we use the index array to access the correct indices - var i1 = indexArray[ y ][ x ]; - var i2 = indexArray[ y + 1 ][ x ]; - var i3 = indexArray[ y + 1 ][ x + 1 ]; - var i4 = indexArray[ y ][ x + 1 ]; + return this; - // face one - indices.setX( indexOffset, i1 ); indexOffset ++; - indices.setX( indexOffset, i2 ); indexOffset ++; - indices.setX( indexOffset, i4 ); indexOffset ++; + }, - // face two - indices.setX( indexOffset, i2 ); indexOffset ++; - indices.setX( indexOffset, i3 ); indexOffset ++; - indices.setX( indexOffset, i4 ); indexOffset ++; + setW: function ( index, w ) { - // update counters - groupCount += 6; + this.data.array[ index * this.data.stride + this.offset + 3 ] = w; - } + return this; - } + }, - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, 0 ); + getX: function ( index ) { - // calculate new start value for groups - groupStart += groupCount; + return this.data.array[ index * this.data.stride + this.offset ]; - } + }, - function generateCap( top ) { + getY: function ( index ) { - var x, centerIndexStart, centerIndexEnd; + return this.data.array[ index * this.data.stride + this.offset + 1 ]; - var uv = new THREE.Vector2(); - var vertex = new THREE.Vector3(); + }, - var groupCount = 0; + getZ: function ( index ) { - var radius = ( top === true ) ? radiusTop : radiusBottom; - var sign = ( top === true ) ? 1 : - 1; + return this.data.array[ index * this.data.stride + this.offset + 2 ]; - // save the index of the first center vertex - centerIndexStart = index; + }, - // first we generate the center vertex data of the cap. - // because the geometry needs one set of uvs per face, - // we must generate a center vertex per face/segment + getW: function ( index ) { - for ( x = 1; x <= radialSegments; x ++ ) { + return this.data.array[ index * this.data.stride + this.offset + 3 ]; - // vertex - vertices.setXYZ( index, 0, halfHeight * sign, 0 ); + }, - // normal - normals.setXYZ( index, 0, sign, 0 ); + setXY: function ( index, x, y ) { - // uv - uv.x = 0.5; - uv.y = 0.5; + index = index * this.data.stride + this.offset; - uvs.setXY( index, uv.x, uv.y ); + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; - // increase index - index ++; + return this; - } + }, - // save the index of the last center vertex - centerIndexEnd = index; + setXYZ: function ( index, x, y, z ) { - // now we generate the surrounding vertices, normals and uvs + index = index * this.data.stride + this.offset; - for ( x = 0; x <= radialSegments; x ++ ) { + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; - var u = x / radialSegments; - var theta = u * thetaLength + thetaStart; + return this; - var cosTheta = Math.cos( theta ); - var sinTheta = Math.sin( theta ); + }, - // vertex - vertex.x = radius * sinTheta; - vertex.y = halfHeight * sign; - vertex.z = radius * cosTheta; - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + setXYZW: function ( index, x, y, z, w ) { - // normal - normals.setXYZ( index, 0, sign, 0 ); + index = index * this.data.stride + this.offset; - // uv - uv.x = ( cosTheta * 0.5 ) + 0.5; - uv.y = ( sinTheta * 0.5 * sign ) + 0.5; - uvs.setXY( index, uv.x, uv.y ); + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + this.data.array[ index + 3 ] = w; - // increase index - index ++; + return this; - } + } - // generate indices + }; - for ( x = 0; x < radialSegments; x ++ ) { + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - var c = centerIndexStart + x; - var i = centerIndexEnd + x; + function InterleavedBuffer ( array, stride ) { + this.isInterleavedBuffer = true; - if ( top === true ) { + this.uuid = exports.Math.generateUUID(); - // face top - indices.setX( indexOffset, i ); indexOffset ++; - indices.setX( indexOffset, i + 1 ); indexOffset ++; - indices.setX( indexOffset, c ); indexOffset ++; + this.array = array; + this.stride = stride; - } else { + this.dynamic = false; + this.updateRange = { offset: 0, count: - 1 }; - // face bottom - indices.setX( indexOffset, i + 1 ); indexOffset ++; - indices.setX( indexOffset, i ); indexOffset ++; - indices.setX( indexOffset, c ); indexOffset ++; + this.version = 0; - } + }; - // update counters - groupCount += 3; + InterleavedBuffer.prototype = { - } + constructor: InterleavedBuffer, - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + get length () { - // calculate new start value for groups - groupStart += groupCount; + return this.array.length; - } + }, -}; + get count () { -THREE.CylinderBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.CylinderBufferGeometry.prototype.constructor = THREE.CylinderBufferGeometry; + return this.array.length / this.stride; -// File:src/extras/geometries/CylinderGeometry.js + }, -/** - * @author mrdoob / http://mrdoob.com/ - */ + set needsUpdate( value ) { -THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + if ( value === true ) this.version ++; - THREE.Geometry.call( this ); + }, - this.type = 'CylinderGeometry'; + setDynamic: function ( value ) { - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.dynamic = value; - this.fromBufferGeometry( new THREE.CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); - this.mergeVertices(); + return this; -}; + }, -THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry; + copy: function ( source ) { -// File:src/extras/geometries/ConeBufferGeometry.js + this.array = new source.array.constructor( source.array ); + this.stride = source.stride; + this.dynamic = source.dynamic; -/* - * @author: abelnation / http://github.com/abelnation - */ + return this; -THREE.ConeBufferGeometry = function ( - radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ) { - - THREE.CylinderBufferGeometry.call( this, - 0, radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ); - - this.type = 'ConeBufferGeometry'; - - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + }, -}; + copyAt: function ( index1, attribute, index2 ) { -THREE.ConeBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.ConeBufferGeometry.prototype.constructor = THREE.ConeBufferGeometry; + index1 *= this.stride; + index2 *= attribute.stride; -// File:src/extras/geometries/ConeGeometry.js + for ( var i = 0, l = this.stride; i < l; i ++ ) { -/** - * @author abelnation / http://github.com/abelnation - */ + this.array[ index1 + i ] = attribute.array[ index2 + i ]; -THREE.ConeGeometry = function ( - radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ) { - - THREE.CylinderGeometry.call( this, - 0, radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ); - - this.type = 'ConeGeometry'; - - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } -}; + return this; -THREE.ConeGeometry.prototype = Object.create( THREE.CylinderGeometry.prototype ); -THREE.ConeGeometry.prototype.constructor = THREE.ConeGeometry; + }, -// File:src/extras/geometries/EdgesGeometry.js + set: function ( value, offset ) { -/** - * @author WestLangley / http://github.com/WestLangley - */ + if ( offset === undefined ) offset = 0; -THREE.EdgesGeometry = function ( geometry, thresholdAngle ) { + this.array.set( value, offset ); - THREE.BufferGeometry.call( this ); + return this; - thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; + }, - var thresholdDot = Math.cos( THREE.Math.DEG2RAD * thresholdAngle ); + clone: function () { - var edge = [ 0, 0 ], hash = {}; + return new this.constructor().copy( this ); - function sortFunction( a, b ) { + } - return a - b; + }; - } + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - var keys = [ 'a', 'b', 'c' ]; + function InstancedInterleavedBuffer ( array, stride, meshPerAttribute ) { + this.isInstancedInterleavedBuffer = this.isInterleavedBuffer = true; - var geometry2; + InterleavedBuffer.call( this, array, stride ); - if ( geometry instanceof THREE.BufferGeometry ) { + this.meshPerAttribute = meshPerAttribute || 1; - geometry2 = new THREE.Geometry(); - geometry2.fromBufferGeometry( geometry ); + }; - } else { + InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype ); + InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer; - geometry2 = geometry.clone(); + InstancedInterleavedBuffer.prototype.copy = function ( source ) { - } + InterleavedBuffer.prototype.copy.call( this, source ); - geometry2.mergeVertices(); - geometry2.computeFaceNormals(); + this.meshPerAttribute = source.meshPerAttribute; - var vertices = geometry2.vertices; - var faces = geometry2.faces; + return this; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + }; - var face = faces[ i ]; + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - for ( var j = 0; j < 3; j ++ ) { + function InstancedBufferAttribute ( array, itemSize, meshPerAttribute ) { + this.isInstancedBufferAttribute = this.isBufferAttribute = true; - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); + BufferAttribute.call( this, array, itemSize ); - var key = edge.toString(); + this.meshPerAttribute = meshPerAttribute || 1; - if ( hash[ key ] === undefined ) { + }; - hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; + InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute; - } else { + InstancedBufferAttribute.prototype.copy = function ( source ) { - hash[ key ].face2 = i; + BufferAttribute.prototype.copy.call( this, source ); - } + this.meshPerAttribute = source.meshPerAttribute; - } + return this; - } + }; - var coords = []; + /** + * @author mrdoob / http://mrdoob.com/ + * @author bhouston / http://clara.io/ + * @author stephomi / http://stephaneginier.com/ + */ - for ( var key in hash ) { + function Raycaster ( origin, direction, near, far ) { + this.isRaycaster = true; - var h = hash[ key ]; + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) { + this.near = near || 0; + this.far = far || Infinity; - var vertex = vertices[ h.vert1 ]; - coords.push( vertex.x ); - coords.push( vertex.y ); - coords.push( vertex.z ); + this.params = { + Mesh: {}, + Line: {}, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; - vertex = vertices[ h.vert2 ]; - coords.push( vertex.x ); - coords.push( vertex.y ); - coords.push( vertex.z ); + Object.defineProperties( this.params, { + PointCloud: { + get: function () { + console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); + return this.Points; + } + } + } ); - } + }; - } + function ascSort( a, b ) { - this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) ); + return a.distance - b.distance; -}; + } -THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry; + function intersectObject( object, raycaster, intersects, recursive ) { -// File:src/extras/geometries/ExtrudeGeometry.js + if ( object.visible === false ) return; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - * Creates extruded geometry from a path shape. - * - * parameters = { - * - * curveSegments: , // number of points on the curves - * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too - * amount: , // Depth to extrude the shape - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into the original shape bevel goes - * bevelSize: , // how far from shape outline is bevel - * bevelSegments: , // number of bevel layers - * - * extrudePath: // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined) - * frames: // containing arrays of tangents, normals, binormals - * - * uvGenerator: // object that provides UV generator functions - * - * } - **/ - -THREE.ExtrudeGeometry = function ( shapes, options ) { - - if ( typeof( shapes ) === "undefined" ) { - - shapes = []; - return; + object.raycast( raycaster, intersects ); - } + if ( recursive === true ) { - THREE.Geometry.call( this ); + var children = object.children; - this.type = 'ExtrudeGeometry'; + for ( var i = 0, l = children.length; i < l; i ++ ) { - shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + intersectObject( children[ i ], raycaster, intersects, true ); - this.addShapeList( shapes, options ); + } - this.computeFaceNormals(); + } - // can't really use automatic vertex normals - // as then front and back sides get smoothed too - // should do separate smoothing just for sides + } - //this.computeVertexNormals(); + // - //console.log( "took", ( Date.now() - startTime ) ); + Raycaster.prototype = { -}; + constructor: Raycaster, -THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry; + linePrecision: 1, -THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { + set: function ( origin, direction ) { - var sl = shapes.length; + // direction is assumed to be normalized (for accurate distance calculations) - for ( var s = 0; s < sl; s ++ ) { + this.ray.set( origin, direction ); - var shape = shapes[ s ]; - this.addShape( shape, options ); + }, - } + setFromCamera: function ( coords, camera ) { -}; + if ( (camera && camera.isPerspectiveCamera) ) { -THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); - var amount = options.amount !== undefined ? options.amount : 100; + } else if ( (camera && camera.isOrthographicCamera) ) { - var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10 - var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8 - var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera + this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); - var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false + } else { - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + console.error( 'THREE.Raycaster: Unsupported camera type.' ); - var steps = options.steps !== undefined ? options.steps : 1; + } - var extrudePath = options.extrudePath; - var extrudePts, extrudeByPath = false; + }, - // Use default WorldUVGenerator if no UV generators are specified. - var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator; + intersectObject: function ( object, recursive ) { - var splineTube, binormal, normal, position2; - if ( extrudePath ) { + var intersects = []; - extrudePts = extrudePath.getSpacedPoints( steps ); + intersectObject( object, this, intersects, recursive ); - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion + intersects.sort( ascSort ); - // SETUP TNB variables + return intersects; - // Reuse TNB from TubeGeomtry for now. - // TODO1 - have a .isClosed in spline? + }, - splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false ); + intersectObjects: function ( objects, recursive ) { - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + var intersects = []; - binormal = new THREE.Vector3(); - normal = new THREE.Vector3(); - position2 = new THREE.Vector3(); + if ( Array.isArray( objects ) === false ) { - } + console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); + return intersects; - // Safeguards if bevels are not enabled + } - if ( ! bevelEnabled ) { + for ( var i = 0, l = objects.length; i < l; i ++ ) { - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; + intersectObject( objects[ i ], this, intersects, recursive ); - } + } - // Variables initialization + intersects.sort( ascSort ); - var ahole, h, hl; // looping of holes - var scope = this; + return intersects; - var shapesOffset = this.vertices.length; + } - var shapePoints = shape.extractPoints( curveSegments ); + }; - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + /** + * @author alteredq / http://alteredqualia.com/ + */ - var reverse = ! THREE.ShapeUtils.isClockWise( vertices ); + function Clock ( autoStart ) { + this.isClock = true; - if ( reverse ) { + this.autoStart = ( autoStart !== undefined ) ? autoStart : true; - vertices = vertices.reverse(); + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; - // Maybe we should also check if holes are in the opposite direction, just to be safe ... + this.running = false; - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + }; - ahole = holes[ h ]; + Clock.prototype = { - if ( THREE.ShapeUtils.isClockWise( ahole ) ) { + constructor: Clock, - holes[ h ] = ahole.reverse(); + start: function () { - } + this.startTime = ( performance || Date ).now(); - } + this.oldTime = this.startTime; + this.running = true; - reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! + }, - } + stop: function () { + this.getElapsedTime(); + this.running = false; - var faces = THREE.ShapeUtils.triangulateShape( vertices, holes ); + }, - /* Vertices */ + getElapsedTime: function () { - var contour = vertices; // vertices has all points but contour has only points of circumference + this.getDelta(); + return this.elapsedTime; - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + }, - ahole = holes[ h ]; + getDelta: function () { - vertices = vertices.concat( ahole ); + var diff = 0; - } + if ( this.autoStart && ! this.running ) { + this.start(); - function scalePt2 ( pt, vec, size ) { + } - if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); + if ( this.running ) { - return vec.clone().multiplyScalar( size ).add( pt ); + var newTime = ( performance || Date ).now(); - } + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; - var b, bs, t, z, - vert, vlen = vertices.length, - face, flen = faces.length; + this.elapsedTime += diff; + } - // Find directions for point movement + return diff; + } - function getBevelVec( inPt, inPrev, inNext ) { + }; - // computes for inPt the corresponding point inPt' on a new contour - // shifted by 1 unit (length of normalized vector) to the left - // if we walk along contour clockwise, this new contour is outside the old one - // - // inPt' is the intersection of the two lines parallel to the two - // adjacent edges of inPt at a distance of 1 unit on the left side. + /** + * Spline from Tween.js, slightly optimized (and trashed) + * http://sole.github.com/tween.js/examples/05_spline.html + * + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt + function Spline ( points ) { + this.isSpline = true; - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html + this.points = points; - var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; - var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + var c = [], v3 = { x: 0, y: 0, z: 0 }, + point, intPoint, weight, w2, w3, + pa, pb, pc, pd; - var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + this.initFromArray = function ( a ) { - // check for collinear edges - var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + this.points = []; - if ( Math.abs( collinear0 ) > Number.EPSILON ) { + for ( var i = 0; i < a.length; i ++ ) { - // not collinear + this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; - // length of vectors for normalizing + } - var v_prev_len = Math.sqrt( v_prev_lensq ); - var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); + }; - // shift adjacent points by unit vectors to the left + this.getPoint = function ( k ) { - var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); - var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + point = ( this.points.length - 1 ) * k; + intPoint = Math.floor( point ); + weight = point - intPoint; - var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); - var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; + c[ 1 ] = intPoint; + c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1; + c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2; - // scaling factor for v_prev to intersection point + pa = this.points[ c[ 0 ] ]; + pb = this.points[ c[ 1 ] ]; + pc = this.points[ c[ 2 ] ]; + pd = this.points[ c[ 3 ] ]; - var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - - ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / - ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + w2 = weight * weight; + w3 = weight * w2; - // vector from inPt to intersection point + v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 ); + v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 ); + v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 ); - v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); - v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + return v3; - // Don't normalize!, otherwise sharp corners become ugly - // but prevent crazy spikes - var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); - if ( v_trans_lensq <= 2 ) { + }; - return new THREE.Vector2( v_trans_x, v_trans_y ); + this.getControlPointsArray = function () { - } else { + var i, p, l = this.points.length, + coords = []; - shrink_by = Math.sqrt( v_trans_lensq / 2 ); + for ( i = 0; i < l; i ++ ) { - } + p = this.points[ i ]; + coords[ i ] = [ p.x, p.y, p.z ]; - } else { + } - // handle special case of collinear edges + return coords; - var direction_eq = false; // assumes: opposite - if ( v_prev_x > Number.EPSILON ) { + }; - if ( v_next_x > Number.EPSILON ) { + // approximate length by summing linear segments - direction_eq = true; + this.getLength = function ( nSubDivisions ) { - } + var i, index, nSamples, position, + point = 0, intPoint = 0, oldIntPoint = 0, + oldPosition = new Vector3(), + tmpVec = new Vector3(), + chunkLengths = [], + totalLength = 0; - } else { + // first point has 0 length - if ( v_prev_x < - Number.EPSILON ) { + chunkLengths[ 0 ] = 0; - if ( v_next_x < - Number.EPSILON ) { + if ( ! nSubDivisions ) nSubDivisions = 100; - direction_eq = true; + nSamples = this.points.length * nSubDivisions; - } + oldPosition.copy( this.points[ 0 ] ); - } else { + for ( i = 1; i < nSamples; i ++ ) { - if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + index = i / nSamples; - direction_eq = true; + position = this.getPoint( index ); + tmpVec.copy( position ); - } + totalLength += tmpVec.distanceTo( oldPosition ); - } + oldPosition.copy( position ); - } + point = ( this.points.length - 1 ) * index; + intPoint = Math.floor( point ); - if ( direction_eq ) { + if ( intPoint !== oldIntPoint ) { - // console.log("Warning: lines are a straight sequence"); - v_trans_x = - v_prev_y; - v_trans_y = v_prev_x; - shrink_by = Math.sqrt( v_prev_lensq ); + chunkLengths[ intPoint ] = totalLength; + oldIntPoint = intPoint; - } else { + } - // console.log("Warning: lines are a straight spike"); - v_trans_x = v_prev_x; - v_trans_y = v_prev_y; - shrink_by = Math.sqrt( v_prev_lensq / 2 ); + } - } + // last point ends with total length - } + chunkLengths[ chunkLengths.length ] = totalLength; - return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + return { chunks: chunkLengths, total: totalLength }; - } + }; + this.reparametrizeByArcLength = function ( samplingCoef ) { - var contourMovements = []; + var i, j, + index, indexCurrent, indexNext, + realDistance, + sampling, position, + newpoints = [], + tmpVec = new Vector3(), + sl = this.getLength(); - for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); - if ( j === il ) j = 0; - if ( k === il ) k = 0; + for ( i = 1; i < this.points.length; i ++ ) { - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) + //tmpVec.copy( this.points[ i - 1 ] ); + //linearDistance = tmpVec.distanceTo( this.points[ i ] ); - contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ]; - } + sampling = Math.ceil( samplingCoef * realDistance / sl.total ); - var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); + indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); + indexNext = i / ( this.points.length - 1 ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + for ( j = 1; j < sampling - 1; j ++ ) { - ahole = holes[ h ]; + index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); - oneHoleMovements = []; + position = this.getPoint( index ); + newpoints.push( tmpVec.copy( position ).clone() ); - for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + } - if ( j === il ) j = 0; - if ( k === il ) k = 0; + newpoints.push( tmpVec.copy( this.points[ i ] ).clone() ); - // (j)---(i)---(k) - oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + } - } + this.points = newpoints; - holesMovements.push( oneHoleMovements ); - verticesMovements = verticesMovements.concat( oneHoleMovements ); + }; - } + // Catmull-Rom + function interpolate( p0, p1, p2, p3, t, t2, t3 ) { - // Loop bevelSegments, 1 for the front, 1 for the back + var v0 = ( p2 - p0 ) * 0.5, + v1 = ( p3 - p1 ) * 0.5; - for ( b = 0; b < bevelSegments; b ++ ) { + return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; - //for ( b = bevelSegments; b > 0; b -- ) { + } - t = b / bevelSegments; - z = bevelThickness * ( 1 - t ); + }; - //z = bevelThickness * t; - bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved - //bs = bevelSize * t; // linear + /** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + * + * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system + * + * The poles (phi) are at the positive and negative y axis. + * The equator starts at positive z. + */ - // contract shape + function Spherical ( radius, phi, theta ) { + this.isSpherical = true; - for ( i = 0, il = contour.length; i < il; i ++ ) { + this.radius = ( radius !== undefined ) ? radius : 1.0; + this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole + this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + return this; - v( vert.x, vert.y, - z ); + }; - } + Spherical.prototype = { - // expand holes + constructor: Spherical, - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + set: function ( radius, phi, theta ) { - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + this.radius = radius; + this.phi = phi; + this.theta = theta; - for ( i = 0, il = ahole.length; i < il; i ++ ) { + return this; - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + }, - v( vert.x, vert.y, - z ); + clone: function () { - } + return new this.constructor().copy( this ); - } + }, - } + copy: function ( other ) { - bs = bevelSize; + this.radius.copy( other.radius ); + this.phi.copy( other.phi ); + this.theta.copy( other.theta ); - // Back facing vertices + return this; - for ( i = 0; i < vlen; i ++ ) { + }, - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + // restrict phi to be betwee EPS and PI-EPS + makeSafe: function() { - if ( ! extrudeByPath ) { + var EPS = 0.000001; + this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); - v( vert.x, vert.y, 0 ); + return this; - } else { + }, - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + setFromVector3: function( vec3 ) { - normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + this.radius = vec3.length(); + + if ( this.radius === 0 ) { + + this.theta = 0; + this.phi = 0; + + } else { + + this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis + this.phi = Math.acos( exports.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle + + } + + return this; + + }, + + }; + + /** + * @author alteredq / http://alteredqualia.com/ + */ + + function MorphBlendMesh( geometry, material ) { + this.isMorphBlendMesh = this.isMesh = true; + + Mesh.call( this, geometry, material ); + + this.animationsMap = {}; + this.animationsList = []; + + // prepare default animation + // (all frames played together in 1 second) + + var numFrames = this.geometry.morphTargets.length; + + var name = "__default"; + + var startFrame = 0; + var endFrame = numFrames - 1; + + var fps = numFrames / 1; + + this.createAnimation( name, startFrame, endFrame, fps ); + this.setAnimationWeight( name, 1 ); + + }; + + MorphBlendMesh.prototype = Object.create( Mesh.prototype ); + MorphBlendMesh.prototype.constructor = MorphBlendMesh; + + MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { + + var animation = { + + start: start, + end: end, + + length: end - start + 1, + + fps: fps, + duration: ( end - start ) / fps, + + lastFrame: 0, + currentFrame: 0, + + active: false, + + time: 0, + direction: 1, + weight: 1, + + directionBackwards: false, + mirroredLoop: false + + }; + + this.animationsMap[ name ] = animation; + this.animationsList.push( animation ); + + }; + + MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { + + var pattern = /([a-z]+)_?(\d+)/i; + + var firstAnimation, frameRanges = {}; + + var geometry = this.geometry; + + for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + + var morph = geometry.morphTargets[ i ]; + var chunks = morph.name.match( pattern ); + + if ( chunks && chunks.length > 1 ) { + + var name = chunks[ 1 ]; + + if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity }; + + var range = frameRanges[ name ]; + + if ( i < range.start ) range.start = i; + if ( i > range.end ) range.end = i; + + if ( ! firstAnimation ) firstAnimation = name; + + } + + } + + for ( var name in frameRanges ) { + + var range = frameRanges[ name ]; + this.createAnimation( name, range.start, range.end, fps ); + + } + + this.firstAnimation = firstAnimation; + + }; + + MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.direction = 1; + animation.directionBackwards = false; + + } + + }; + + MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.direction = - 1; + animation.directionBackwards = true; + + } + + }; + + MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.fps = fps; + animation.duration = ( animation.end - animation.start ) / animation.fps; + + } + + }; + + MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.duration = duration; + animation.fps = ( animation.end - animation.start ) / animation.duration; + + } + + }; + + MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.weight = weight; + + } + + }; + + MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.time = time; + + } + + }; + + MorphBlendMesh.prototype.getAnimationTime = function ( name ) { + + var time = 0; + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + time = animation.time; + + } + + return time; + + }; + + MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { + + var duration = - 1; + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + duration = animation.duration; + + } + + return duration; + + }; + + MorphBlendMesh.prototype.playAnimation = function ( name ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.time = 0; + animation.active = true; + + } else { + + console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" ); + + } + + }; + + MorphBlendMesh.prototype.stopAnimation = function ( name ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.active = false; + + } + + }; + + MorphBlendMesh.prototype.update = function ( delta ) { + + for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { + + var animation = this.animationsList[ i ]; + + if ( ! animation.active ) continue; + + var frameTime = animation.duration / animation.length; + + animation.time += animation.direction * delta; + + if ( animation.mirroredLoop ) { + + if ( animation.time > animation.duration || animation.time < 0 ) { + + animation.direction *= - 1; + + if ( animation.time > animation.duration ) { + + animation.time = animation.duration; + animation.directionBackwards = true; + + } + + if ( animation.time < 0 ) { + + animation.time = 0; + animation.directionBackwards = false; + + } + + } + + } else { + + animation.time = animation.time % animation.duration; + + if ( animation.time < 0 ) animation.time += animation.duration; + + } + + var keyframe = animation.start + exports.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); + var weight = animation.weight; + + if ( keyframe !== animation.currentFrame ) { + + this.morphTargetInfluences[ animation.lastFrame ] = 0; + this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; + + this.morphTargetInfluences[ keyframe ] = 0; + + animation.lastFrame = animation.currentFrame; + animation.currentFrame = keyframe; + + } + + var mix = ( animation.time % frameTime ) / frameTime; + + if ( animation.directionBackwards ) mix = 1 - mix; + + if ( animation.currentFrame !== animation.lastFrame ) { + + this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; + this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; + + } else { + + this.morphTargetInfluences[ animation.currentFrame ] = weight; + + } + + } + + }; + + /** + * @author alteredq / http://alteredqualia.com/ + */ + + function ImmediateRenderObject ( material ) { + this.isImmediateRenderObject = this.isObject3D = true; + + Object3D.call( this ); + + this.material = material; + this.render = function ( renderCallback ) {}; + + }; + + ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); + ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function WireframeGeometry ( geometry ) { + this.isWireframeGeometry = this.isBufferGeometry = true; - position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + BufferGeometry.call( this ); - v( position2.x, position2.y, position2.z ); + var edge = [ 0, 0 ], hash = {}; - } + function sortFunction( a, b ) { - } + return a - b; - // Add stepped vertices... - // Including front facing vertices + } - var s; + var keys = [ 'a', 'b', 'c' ]; - for ( s = 1; s <= steps; s ++ ) { + if ( (geometry && geometry.isGeometry) ) { - for ( i = 0; i < vlen; i ++ ) { + var vertices = geometry.vertices; + var faces = geometry.faces; + var numEdges = 0; - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + // allocate maximal size + var edges = new Uint32Array( 6 * faces.length ); - if ( ! extrudeByPath ) { + for ( var i = 0, l = faces.length; i < l; i ++ ) { - v( vert.x, vert.y, amount / steps * s ); + var face = faces[ i ]; - } else { + for ( var j = 0; j < 3; j ++ ) { - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + edge[ 0 ] = face[ keys[ j ] ]; + edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; + edge.sort( sortFunction ); - normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + var key = edge.toString(); - position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + if ( hash[ key ] === undefined ) { - v( position2.x, position2.y, position2.z ); + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; - } + } - } + } - } + } + var coords = new Float32Array( numEdges * 2 * 3 ); - // Add bevel segments planes + for ( var i = 0, l = numEdges; i < l; i ++ ) { - //for ( b = 1; b <= bevelSegments; b ++ ) { - for ( b = bevelSegments - 1; b >= 0; b -- ) { + for ( var j = 0; j < 2; j ++ ) { - t = b / bevelSegments; - z = bevelThickness * ( 1 - t ); - //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) ); - bs = bevelSize * Math.sin ( t * Math.PI / 2 ); + var vertex = vertices[ edges [ 2 * i + j ] ]; - // contract shape + var index = 6 * i + 3 * j; + coords[ index + 0 ] = vertex.x; + coords[ index + 1 ] = vertex.y; + coords[ index + 2 ] = vertex.z; - for ( i = 0, il = contour.length; i < il; i ++ ) { + } - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - v( vert.x, vert.y, amount + z ); + } - } + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - // expand holes + } else if ( (geometry && geometry.isBufferGeometry) ) { - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + if ( geometry.index !== null ) { - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + // Indexed BufferGeometry - for ( i = 0, il = ahole.length; i < il; i ++ ) { + var indices = geometry.index.array; + var vertices = geometry.attributes.position; + var groups = geometry.groups; + var numEdges = 0; - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + if ( groups.length === 0 ) { - if ( ! extrudeByPath ) { + geometry.addGroup( 0, indices.length ); - v( vert.x, vert.y, amount + z ); + } - } else { + // allocate maximal size + var edges = new Uint32Array( 2 * indices.length ); - v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + for ( var o = 0, ol = groups.length; o < ol; ++ o ) { - } + var group = groups[ o ]; - } + var start = group.start; + var count = group.count; - } + for ( var i = start, il = start + count; i < il; i += 3 ) { - } + for ( var j = 0; j < 3; j ++ ) { - /* Faces */ + edge[ 0 ] = indices[ i + j ]; + edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ]; + edge.sort( sortFunction ); - // Top and bottom faces + var key = edge.toString(); - buildLidFaces(); + if ( hash[ key ] === undefined ) { - // Sides faces + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; - buildSideFaces(); + } + } - ///// Internal functions + } - function buildLidFaces() { + } - if ( bevelEnabled ) { + var coords = new Float32Array( numEdges * 2 * 3 ); - var layer = 0; // steps + 1 - var offset = vlen * layer; + for ( var i = 0, l = numEdges; i < l; i ++ ) { - // Bottom faces + for ( var j = 0; j < 2; j ++ ) { - for ( i = 0; i < flen; i ++ ) { + var index = 6 * i + 3 * j; + var index2 = edges[ 2 * i + j ]; - face = faces[ i ]; - f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + coords[ index + 0 ] = vertices.getX( index2 ); + coords[ index + 1 ] = vertices.getY( index2 ); + coords[ index + 2 ] = vertices.getZ( index2 ); - } + } - layer = steps + bevelSegments * 2; - offset = vlen * layer; + } - // Top faces + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - for ( i = 0; i < flen; i ++ ) { + } else { - face = faces[ i ]; - f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + // non-indexed BufferGeometry - } + var vertices = geometry.attributes.position.array; + var numEdges = vertices.length / 3; + var numTris = numEdges / 3; - } else { + var coords = new Float32Array( numEdges * 2 * 3 ); - // Bottom faces + for ( var i = 0, l = numTris; i < l; i ++ ) { - for ( i = 0; i < flen; i ++ ) { + for ( var j = 0; j < 3; j ++ ) { - face = faces[ i ]; - f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + var index = 18 * i + 6 * j; - } + var index1 = 9 * i + 3 * j; + coords[ index + 0 ] = vertices[ index1 ]; + coords[ index + 1 ] = vertices[ index1 + 1 ]; + coords[ index + 2 ] = vertices[ index1 + 2 ]; - // Top faces + var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 ); + coords[ index + 3 ] = vertices[ index2 ]; + coords[ index + 4 ] = vertices[ index2 + 1 ]; + coords[ index + 5 ] = vertices[ index2 + 2 ]; - for ( i = 0; i < flen; i ++ ) { + } - face = faces[ i ]; - f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + } - } + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - } + } - } + } - // Create faces for the z-sides of the shape + }; - function buildSideFaces() { + WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); + WireframeGeometry.prototype.constructor = WireframeGeometry; - var layeroffset = 0; - sidewalls( contour, layeroffset ); - layeroffset += contour.length; + /** + * @author mrdoob / http://mrdoob.com/ + */ - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + function WireframeHelper ( object, hex ) { + this.isWireframeHelper = this.isLineSegments = true; - ahole = holes[ h ]; - sidewalls( ahole, layeroffset ); + var color = ( hex !== undefined ) ? hex : 0xffffff; - //, true - layeroffset += ahole.length; + LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) ); - } + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - } + }; - function sidewalls( contour, layeroffset ) { + WireframeHelper.prototype = Object.create( LineSegments.prototype ); + WireframeHelper.prototype.constructor = WireframeHelper; - var j, k; - i = contour.length; + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - while ( -- i >= 0 ) { + function VertexNormalsHelper ( object, size, hex, linewidth ) { + this.isVertexNormalsHelper = this.isLineSegments = true; - j = i; - k = i - 1; - if ( k < 0 ) k = contour.length - 1; + this.object = object; - //console.log('b', i,j, i-1, k,vertices.length); + this.size = ( size !== undefined ) ? size : 1; - var s = 0, sl = steps + bevelSegments * 2; + var color = ( hex !== undefined ) ? hex : 0xff0000; - for ( s = 0; s < sl; s ++ ) { + var width = ( linewidth !== undefined ) ? linewidth : 1; - var slen1 = vlen * s; - var slen2 = vlen * ( s + 1 ); + // - var a = layeroffset + j + slen1, - b = layeroffset + k + slen1, - c = layeroffset + k + slen2, - d = layeroffset + j + slen2; + var nNormals = 0; - f4( a, b, c, d, contour, s, sl, j, k ); + var objGeometry = this.object.geometry; - } + if ( (objGeometry && objGeometry.isGeometry) ) { - } + nNormals = objGeometry.faces.length * 3; - } + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { + nNormals = objGeometry.attributes.normal.count; - function v( x, y, z ) { + } - scope.vertices.push( new THREE.Vector3( x, y, z ) ); + // - } + var geometry = new BufferGeometry(); - function f3( a, b, c ) { + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; + geometry.addAttribute( 'position', positions ); - scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); - var uvs = uvgen.generateTopUV( scope, a, b, c ); + // - scope.faceVertexUvs[ 0 ].push( uvs ); + this.matrixAutoUpdate = false; - } + this.update(); - function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { + }; - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; - d += shapesOffset; + VertexNormalsHelper.prototype = Object.create( LineSegments.prototype ); + VertexNormalsHelper.prototype.constructor = VertexNormalsHelper; - scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) ); - scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) ); + VertexNormalsHelper.prototype.update = ( function () { - var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); - scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); - scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); + return function update() { - } + var keys = [ 'a', 'b', 'c' ]; -}; + this.object.updateMatrixWorld( true ); -THREE.ExtrudeGeometry.WorldUVGenerator = { + normalMatrix.getNormalMatrix( this.object.matrixWorld ); - generateTopUV: function ( geometry, indexA, indexB, indexC ) { + var matrixWorld = this.object.matrixWorld; - var vertices = geometry.vertices; + var position = this.geometry.attributes.position; - var a = vertices[ indexA ]; - var b = vertices[ indexB ]; - var c = vertices[ indexC ]; + // - return [ - new THREE.Vector2( a.x, a.y ), - new THREE.Vector2( b.x, b.y ), - new THREE.Vector2( c.x, c.y ) - ]; + var objGeometry = this.object.geometry; - }, + if ( (objGeometry && objGeometry.isGeometry) ) { - generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) { + var vertices = objGeometry.vertices; - var vertices = geometry.vertices; + var faces = objGeometry.faces; - var a = vertices[ indexA ]; - var b = vertices[ indexB ]; - var c = vertices[ indexC ]; - var d = vertices[ indexD ]; + var idx = 0; - if ( Math.abs( a.y - b.y ) < 0.01 ) { + for ( var i = 0, l = faces.length; i < l; i ++ ) { - return [ - new THREE.Vector2( a.x, 1 - a.z ), - new THREE.Vector2( b.x, 1 - b.z ), - new THREE.Vector2( c.x, 1 - c.z ), - new THREE.Vector2( d.x, 1 - d.z ) - ]; + var face = faces[ i ]; - } else { + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - return [ - new THREE.Vector2( a.y, 1 - a.z ), - new THREE.Vector2( b.y, 1 - b.z ), - new THREE.Vector2( c.y, 1 - c.z ), - new THREE.Vector2( d.y, 1 - d.z ) - ]; + var vertex = vertices[ face[ keys[ j ] ] ]; - } + var normal = face.vertexNormals[ j ]; - } -}; + v1.copy( vertex ).applyMatrix4( matrixWorld ); -// File:src/extras/geometries/ShapeGeometry.js + v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); -/** - * @author jonobr1 / http://jonobr1.com - * - * Creates a one-sided polygonal geometry from a path shape. Similar to - * ExtrudeGeometry. - * - * parameters = { - * - * curveSegments: , // number of points on the curves. NOT USED AT THE MOMENT. - * - * material: // material index for front and back faces - * uvGenerator: // object that provides UV generator functions - * - * } - **/ + position.setXYZ( idx, v1.x, v1.y, v1.z ); -THREE.ShapeGeometry = function ( shapes, options ) { + idx = idx + 1; - THREE.Geometry.call( this ); + position.setXYZ( idx, v2.x, v2.y, v2.z ); - this.type = 'ShapeGeometry'; + idx = idx + 1; - if ( Array.isArray( shapes ) === false ) shapes = [ shapes ]; + } - this.addShapeList( shapes, options ); + } - this.computeFaceNormals(); + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { -}; + var objPos = objGeometry.attributes.position; -THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry; + var objNorm = objGeometry.attributes.normal; -/** - * Add an array of shapes to THREE.ShapeGeometry. - */ -THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { + var idx = 0; - for ( var i = 0, l = shapes.length; i < l; i ++ ) { + // for simplicity, ignore index and drawcalls, and render every normal - this.addShape( shapes[ i ], options ); + for ( var j = 0, jl = objPos.count; j < jl; j ++ ) { - } + v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld ); - return this; + v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) ); -}; + v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); -/** - * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. - */ -THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { + position.setXYZ( idx, v1.x, v1.y, v1.z ); - if ( options === undefined ) options = {}; - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + idx = idx + 1; - var material = options.material; - var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; + position.setXYZ( idx, v2.x, v2.y, v2.z ); - // + idx = idx + 1; - var i, l, hole; + } - var shapesOffset = this.vertices.length; - var shapePoints = shape.extractPoints( curveSegments ); + } - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + position.needsUpdate = true; - var reverse = ! THREE.ShapeUtils.isClockWise( vertices ); + return this; - if ( reverse ) { + }; - vertices = vertices.reverse(); + }() ); - // Maybe we should also check if holes are in the opposite direction, just to be safe... + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - for ( i = 0, l = holes.length; i < l; i ++ ) { + function SpotLightHelper ( light ) { + this.isSpotLightHelper = this.isObject3D = true; - hole = holes[ i ]; + Object3D.call( this ); - if ( THREE.ShapeUtils.isClockWise( hole ) ) { + this.light = light; + this.light.updateMatrixWorld(); - holes[ i ] = hole.reverse(); + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - } + var geometry = new BufferGeometry(); - } + var positions = [ + 0, 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, 1, + 0, 0, 0, - 1, 0, 1, + 0, 0, 0, 0, 1, 1, + 0, 0, 0, 0, - 1, 1 + ]; - reverse = false; + for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { - } + var p1 = ( i / l ) * Math.PI * 2; + var p2 = ( j / l ) * Math.PI * 2; - var faces = THREE.ShapeUtils.triangulateShape( vertices, holes ); + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); - // Vertices + } - for ( i = 0, l = holes.length; i < l; i ++ ) { + geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) ); - hole = holes[ i ]; - vertices = vertices.concat( hole ); + var material = new LineBasicMaterial( { fog: false } ); - } + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); - // + this.update(); - var vert, vlen = vertices.length; - var face, flen = faces.length; + }; - for ( i = 0; i < vlen; i ++ ) { + SpotLightHelper.prototype = Object.create( Object3D.prototype ); + SpotLightHelper.prototype.constructor = SpotLightHelper; - vert = vertices[ i ]; + SpotLightHelper.prototype.dispose = function () { - this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) ); + this.cone.geometry.dispose(); + this.cone.material.dispose(); - } + }; - for ( i = 0; i < flen; i ++ ) { + SpotLightHelper.prototype.update = function () { - face = faces[ i ]; + var vector = new Vector3(); + var vector2 = new Vector3(); - var a = face[ 0 ] + shapesOffset; - var b = face[ 1 ] + shapesOffset; - var c = face[ 2 ] + shapesOffset; + return function update() { - this.faces.push( new THREE.Face3( a, b, c, null, null, material ) ); - this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); + var coneLength = this.light.distance ? this.light.distance : 1000; + var coneWidth = coneLength * Math.tan( this.light.angle ); - } + this.cone.scale.set( coneWidth, coneWidth, coneLength ); -}; + vector.setFromMatrixPosition( this.light.matrixWorld ); + vector2.setFromMatrixPosition( this.light.target.matrixWorld ); -// File:src/extras/geometries/LatheBufferGeometry.js + this.cone.lookAt( vector2.sub( vector ) ); -/** - * @author Mugen87 / https://github.com/Mugen87 - */ + this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - // points - to create a closed torus, one must use a set of points - // like so: [ a, b, c, d, a ], see first is the same as last. - // segments - the number of circumference segments to create - // phiStart - the starting radian - // phiLength - the radian (0 to 2PI) range of the lathed section - // 2PI is a closed lathe, less than 2PI is a portion. + }; -THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) { + }(); - THREE.BufferGeometry.call( this ); + /** + * @author Sean Griffin / http://twitter.com/sgrif + * @author Michael Guerrero / http://realitymeltdown.com + * @author mrdoob / http://mrdoob.com/ + * @author ikerr / http://verold.com + */ - this.type = 'LatheBufferGeometry'; + function SkeletonHelper ( object ) { + this.isSkeletonHelper = this.isLineSegments = true; - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + this.bones = this.getBoneList( object ); - segments = Math.floor( segments ) || 12; - phiStart = phiStart || 0; - phiLength = phiLength || Math.PI * 2; + var geometry = new Geometry(); - // clamp phiLength so it's in range of [ 0, 2PI ] - phiLength = THREE.Math.clamp( phiLength, 0, Math.PI * 2 ); + for ( var i = 0; i < this.bones.length; i ++ ) { - // these are used to calculate buffer length - var vertexCount = ( segments + 1 ) * points.length; - var indexCount = segments * points.length * 2 * 3; + var bone = this.bones[ i ]; - // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + if ( (bone.parent && bone.parent.isBone) ) { - // helper variables - var index = 0, indexOffset = 0, base; - var inversePointLength = 1.0 / ( points.length - 1 ); - var inverseSegments = 1.0 / segments; - var vertex = new THREE.Vector3(); - var uv = new THREE.Vector2(); - var i, j; + geometry.vertices.push( new Vector3() ); + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( 0, 0, 1 ) ); + geometry.colors.push( new Color( 0, 1, 0 ) ); - // generate vertices and uvs + } - for ( i = 0; i <= segments; i ++ ) { + } - var phi = phiStart + i * inverseSegments * phiLength; + geometry.dynamic = true; - var sin = Math.sin( phi ); - var cos = Math.cos( phi ); + var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } ); - for ( j = 0; j <= ( points.length - 1 ); j ++ ) { + LineSegments.call( this, geometry, material ); - // vertex - vertex.x = points[ j ].x * sin; - vertex.y = points[ j ].y; - vertex.z = points[ j ].x * cos; - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + this.root = object; - // uv - uv.x = i / segments; - uv.y = j / ( points.length - 1 ); - uvs.setXY( index, uv.x, uv.y ); + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - // increase index - index ++; + this.update(); - } + }; - } - // generate indices + SkeletonHelper.prototype = Object.create( LineSegments.prototype ); + SkeletonHelper.prototype.constructor = SkeletonHelper; - for ( i = 0; i < segments; i ++ ) { + SkeletonHelper.prototype.getBoneList = function( object ) { - for ( j = 0; j < ( points.length - 1 ); j ++ ) { + var boneList = []; - base = j + i * points.length; + if ( (object && object.isBone) ) { - // indices - var a = base; - var b = base + points.length; - var c = base + points.length + 1; - var d = base + 1; + boneList.push( object ); - // face one - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + } - // face two - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + for ( var i = 0; i < object.children.length; i ++ ) { - } + boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); - } + } - // build geometry + return boneList; - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'uv', uvs ); + }; - // generate normals + SkeletonHelper.prototype.update = function () { - this.computeVertexNormals(); + var geometry = this.geometry; - // if the geometry is closed, we need to average the normals along the seam. - // because the corresponding vertices are identical (but still have different UVs). + var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld ); - if( phiLength === Math.PI * 2 ) { + var boneMatrix = new Matrix4(); - var normals = this.attributes.normal.array; - var n1 = new THREE.Vector3(); - var n2 = new THREE.Vector3(); - var n = new THREE.Vector3(); + var j = 0; - // this is the buffer offset for the last line of vertices - base = segments * points.length * 3; + for ( var i = 0; i < this.bones.length; i ++ ) { - for( i = 0, j = 0; i < points.length; i ++, j += 3 ) { + var bone = this.bones[ i ]; - // select the normal of the vertex in the first line - n1.x = normals[ j + 0 ]; - n1.y = normals[ j + 1 ]; - n1.z = normals[ j + 2 ]; + if ( (bone.parent && bone.parent.isBone) ) { - // select the normal of the vertex in the last line - n2.x = normals[ base + j + 0 ]; - n2.y = normals[ base + j + 1 ]; - n2.z = normals[ base + j + 2 ]; + boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); + geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); - // average normals - n.addVectors( n1, n2 ).normalize(); + boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); + geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); - // assign the new values to both normals - normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; - normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; - normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; + j += 2; - } // next row + } - } + } -}; + geometry.verticesNeedUpdate = true; -THREE.LatheBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.LatheBufferGeometry.prototype.constructor = THREE.LatheBufferGeometry; + geometry.computeBoundingSphere(); -// File:src/extras/geometries/LatheGeometry.js + }; -/** - * @author astrodud / http://astrodud.isgreat.org/ - * @author zz85 / https://github.com/zz85 - * @author bhouston / http://clara.io - */ + /** + * @author benaadams / https://twitter.com/ben_a_adams + * based on THREE.SphereGeometry + */ -// points - to create a closed torus, one must use a set of points -// like so: [ a, b, c, d, a ], see first is the same as last. -// segments - the number of circumference segments to create -// phiStart - the starting radian -// phiLength - the radian (0 to 2PI) range of the lathed section -// 2PI is a closed lathe, less than 2PI is a portion. + function SphereBufferGeometry ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + this.isSphereBufferGeometry = this.isBufferGeometry = true; -THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) { + BufferGeometry.call( this ); - THREE.Geometry.call( this ); + this.type = 'SphereBufferGeometry'; - this.type = 'LatheGeometry'; + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + radius = radius || 50; - this.fromBufferGeometry( new THREE.LatheBufferGeometry( points, segments, phiStart, phiLength ) ); - this.mergeVertices(); + widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); -}; + phiStart = phiStart !== undefined ? phiStart : 0; + phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; -THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry; + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; -// File:src/extras/geometries/PlaneGeometry.js + var thetaEnd = thetaStart + thetaLength; -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as - */ + var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) ); -THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) { + var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - THREE.Geometry.call( this ); + var index = 0, vertices = [], normal = new Vector3(); - this.type = 'PlaneGeometry'; + for ( var y = 0; y <= heightSegments; y ++ ) { - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + var verticesRow = []; - this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); + var v = y / heightSegments; -}; + for ( var x = 0; x <= widthSegments; x ++ ) { -THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry; + var u = x / widthSegments; -// File:src/extras/geometries/PlaneBufferGeometry.js + var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + var py = radius * Math.cos( thetaStart + v * thetaLength ); + var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as - */ + normal.set( px, py, pz ).normalize(); -THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) { + positions.setXYZ( index, px, py, pz ); + normals.setXYZ( index, normal.x, normal.y, normal.z ); + uvs.setXY( index, u, 1 - v ); - THREE.BufferGeometry.call( this ); + verticesRow.push( index ); - this.type = 'PlaneBufferGeometry'; + index ++; - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + } - var width_half = width / 2; - var height_half = height / 2; + vertices.push( verticesRow ); - var gridX = Math.floor( widthSegments ) || 1; - var gridY = Math.floor( heightSegments ) || 1; + } - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + var indices = []; - var segment_width = width / gridX; - var segment_height = height / gridY; + for ( var y = 0; y < heightSegments; y ++ ) { - var vertices = new Float32Array( gridX1 * gridY1 * 3 ); - var normals = new Float32Array( gridX1 * gridY1 * 3 ); - var uvs = new Float32Array( gridX1 * gridY1 * 2 ); + for ( var x = 0; x < widthSegments; x ++ ) { - var offset = 0; - var offset2 = 0; + var v1 = vertices[ y ][ x + 1 ]; + var v2 = vertices[ y ][ x ]; + var v3 = vertices[ y + 1 ][ x ]; + var v4 = vertices[ y + 1 ][ x + 1 ]; - for ( var iy = 0; iy < gridY1; iy ++ ) { + if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 ); + if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 ); - var y = iy * segment_height - height_half; + } - for ( var ix = 0; ix < gridX1; ix ++ ) { + } - var x = ix * segment_width - width_half; + this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) ); + this.addAttribute( 'position', positions ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - vertices[ offset ] = x; - vertices[ offset + 1 ] = - y; + this.boundingSphere = new Sphere( new Vector3(), radius ); - normals[ offset + 2 ] = 1; + }; - uvs[ offset2 ] = ix / gridX; - uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); + SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; - offset += 3; - offset2 += 2; + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - } + function PointLightHelper ( light, sphereSize ) { + this.isPointLightHelper = this.isMesh = true; - } + this.light = light; + this.light.updateMatrixWorld(); - offset = 0; + var geometry = new SphereBufferGeometry( sphereSize, 4, 2 ); + var material = new MeshBasicMaterial( { wireframe: true, fog: false } ); + material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); + Mesh.call( this, geometry, material ); - for ( var iy = 0; iy < gridY; iy ++ ) { + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; - for ( var ix = 0; ix < gridX; ix ++ ) { + /* + var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); + var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); - var a = ix + gridX1 * iy; - var b = ix + gridX1 * ( iy + 1 ); - var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = ( ix + 1 ) + gridX1 * iy; + this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); - indices[ offset ] = a; - indices[ offset + 1 ] = b; - indices[ offset + 2 ] = d; + var d = light.distance; - indices[ offset + 3 ] = b; - indices[ offset + 4 ] = c; - indices[ offset + 5 ] = d; + if ( d === 0.0 ) { - offset += 6; + this.lightDistance.visible = false; - } + } else { - } + this.lightDistance.scale.set( d, d, d ); - this.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + } -}; + this.add( this.lightDistance ); + */ -THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry; + }; -// File:src/extras/geometries/RingBufferGeometry.js + PointLightHelper.prototype = Object.create( Mesh.prototype ); + PointLightHelper.prototype.constructor = PointLightHelper; -/** - * @author Mugen87 / https://github.com/Mugen87 - */ + PointLightHelper.prototype.dispose = function () { -THREE.RingBufferGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + this.geometry.dispose(); + this.material.dispose(); - THREE.BufferGeometry.call( this ); + }; - this.type = 'RingBufferGeometry'; + PointLightHelper.prototype.update = function () { - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - innerRadius = innerRadius || 20; - outerRadius = outerRadius || 50; + /* + var d = this.light.distance; - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + if ( d === 0.0 ) { - thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; - phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; + this.lightDistance.visible = false; - // these are used to calculate buffer length - var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 ); - var indexCount = thetaSegments * phiSegments * 2 * 3; + } else { - // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); - // some helper variables - var index = 0, indexOffset = 0, segment; - var radius = innerRadius; - var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - var vertex = new THREE.Vector3(); - var uv = new THREE.Vector2(); - var j, i; + } + */ - // generate vertices, normals and uvs + }; - // values are generate from the inside of the ring to the outside + /** + * @author mrdoob / http://mrdoob.com/ + */ - for ( j = 0; j <= phiSegments; j ++ ) { + function SphereGeometry ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + this.isSphereGeometry = this.isGeometry = true; - for ( i = 0; i <= thetaSegments; i ++ ) { + Geometry.call( this ); - segment = thetaStart + i / thetaSegments * thetaLength; + this.type = 'SphereGeometry'; - // vertex - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - // normal - normals.setXYZ( index, 0, 0, 1 ); + this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); - // uv - uv.x = ( vertex.x / outerRadius + 1 ) / 2; - uv.y = ( vertex.y / outerRadius + 1 ) / 2; - uvs.setXY( index, uv.x, uv.y ); + }; - // increase index - index++; + SphereGeometry.prototype = Object.create( Geometry.prototype ); + SphereGeometry.prototype.constructor = SphereGeometry; - } + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - // increase the radius for next row of vertices - radius += radiusStep; + function HemisphereLightHelper ( light, sphereSize ) { + this.isHemisphereLightHelper = this.isObject3D = true; - } + Object3D.call( this ); - // generate indices + this.light = light; + this.light.updateMatrixWorld(); - for ( j = 0; j < phiSegments; j ++ ) { + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - var thetaSegmentLevel = j * ( thetaSegments + 1 ); + this.colors = [ new Color(), new Color() ]; - for ( i = 0; i < thetaSegments; i ++ ) { + var geometry = new SphereGeometry( sphereSize, 4, 2 ); + geometry.rotateX( - Math.PI / 2 ); - segment = i + thetaSegmentLevel; + for ( var i = 0, il = 8; i < il; i ++ ) { - // indices - var a = segment; - var b = segment + thetaSegments + 1; - var c = segment + thetaSegments + 2; - var d = segment + 1; + geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; - // face one - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; + } - // face two - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } ); - } + this.lightSphere = new Mesh( geometry, material ); + this.add( this.lightSphere ); - } + this.update(); - // build geometry + }; - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); + HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; -}; + HemisphereLightHelper.prototype.dispose = function () { -THREE.RingBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.RingBufferGeometry.prototype.constructor = THREE.RingBufferGeometry; + this.lightSphere.geometry.dispose(); + this.lightSphere.material.dispose(); -// File:src/extras/geometries/RingGeometry.js + }; -/** - * @author Kaleb Murphy - */ + HemisphereLightHelper.prototype.update = function () { -THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + var vector = new Vector3(); - THREE.Geometry.call( this ); + return function update() { - this.type = 'RingGeometry'; + this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); + this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + this.lightSphere.geometry.colorsNeedUpdate = true; - this.fromBufferGeometry( new THREE.RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); + }; -}; + }(); -THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.RingGeometry.prototype.constructor = THREE.RingGeometry; + /** + * @author mrdoob / http://mrdoob.com/ + */ -// File:src/extras/geometries/SphereGeometry.js + function GridHelper ( size, divisions, color1, color2 ) { + this.isGridHelper = this.isLineSegments = true; -/** - * @author mrdoob / http://mrdoob.com/ - */ + divisions = divisions || 1; + color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); + color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); -THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + var center = divisions / 2; + var step = ( size * 2 ) / divisions; + var vertices = [], colors = []; - THREE.Geometry.call( this ); + for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) { - this.type = 'SphereGeometry'; + vertices.push( - size, 0, k, size, 0, k ); + vertices.push( k, 0, - size, k, 0, size ); - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + var color = i === center ? color1 : color2; - this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; -}; + } -THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry; + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) ); -// File:src/extras/geometries/SphereBufferGeometry.js + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); -/** - * @author benaadams / https://twitter.com/ben_a_adams - * based on THREE.SphereGeometry - */ + LineSegments.call( this, geometry, material ); -THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + }; - THREE.BufferGeometry.call( this ); + GridHelper.prototype = Object.create( LineSegments.prototype ); + GridHelper.prototype.constructor = GridHelper; - this.type = 'SphereBufferGeometry'; + GridHelper.prototype.setColors = function () { - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); - radius = radius || 50; + }; - widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); - heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - phiStart = phiStart !== undefined ? phiStart : 0; - phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; + function FaceNormalsHelper ( object, size, hex, linewidth ) { + this.isFaceNormalsHelper = this.isLineSegments = true; - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; + // FaceNormalsHelper only supports THREE.Geometry - var thetaEnd = thetaStart + thetaLength; + this.object = object; - var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) ); + this.size = ( size !== undefined ) ? size : 1; - var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var color = ( hex !== undefined ) ? hex : 0xffff00; - var index = 0, vertices = [], normal = new THREE.Vector3(); + var width = ( linewidth !== undefined ) ? linewidth : 1; - for ( var y = 0; y <= heightSegments; y ++ ) { + // - var verticesRow = []; + var nNormals = 0; - var v = y / heightSegments; + var objGeometry = this.object.geometry; - for ( var x = 0; x <= widthSegments; x ++ ) { + if ( (objGeometry && objGeometry.isGeometry) ) { - var u = x / widthSegments; + nNormals = objGeometry.faces.length; - var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - var py = radius * Math.cos( thetaStart + v * thetaLength ); - var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + } else { - normal.set( px, py, pz ).normalize(); + console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' ); - positions.setXYZ( index, px, py, pz ); - normals.setXYZ( index, normal.x, normal.y, normal.z ); - uvs.setXY( index, u, 1 - v ); + } - verticesRow.push( index ); + // - index ++; + var geometry = new BufferGeometry(); - } + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); - vertices.push( verticesRow ); + geometry.addAttribute( 'position', positions ); - } + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); - var indices = []; + // - for ( var y = 0; y < heightSegments; y ++ ) { + this.matrixAutoUpdate = false; + this.update(); - for ( var x = 0; x < widthSegments; x ++ ) { + }; - var v1 = vertices[ y ][ x + 1 ]; - var v2 = vertices[ y ][ x ]; - var v3 = vertices[ y + 1 ][ x ]; - var v4 = vertices[ y + 1 ][ x + 1 ]; + FaceNormalsHelper.prototype = Object.create( LineSegments.prototype ); + FaceNormalsHelper.prototype.constructor = FaceNormalsHelper; - if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 ); - if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 ); + FaceNormalsHelper.prototype.update = ( function () { - } + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); - } + return function update() { - this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) ); - this.addAttribute( 'position', positions ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + this.object.updateMatrixWorld( true ); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + normalMatrix.getNormalMatrix( this.object.matrixWorld ); -}; + var matrixWorld = this.object.matrixWorld; -THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry; + var position = this.geometry.attributes.position; -// File:src/extras/geometries/TextGeometry.js + // -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author alteredq / http://alteredqualia.com/ - * - * Text = 3D Text - * - * parameters = { - * font: , // font - * - * size: , // size of the text - * height: , // thickness to extrude text - * curveSegments: , // number of points on the curves - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into text bevel goes - * bevelSize: // how far from text outline is bevel - * } - */ + var objGeometry = this.object.geometry; -THREE.TextGeometry = function ( text, parameters ) { + var vertices = objGeometry.vertices; - parameters = parameters || {}; + var faces = objGeometry.faces; - var font = parameters.font; + var idx = 0; - if ( font instanceof THREE.Font === false ) { + for ( var i = 0, l = faces.length; i < l; i ++ ) { - console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); - return new THREE.Geometry(); + var face = faces[ i ]; - } + var normal = face.normal; - var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments ); + v1.copy( vertices[ face.a ] ) + .add( vertices[ face.b ] ) + .add( vertices[ face.c ] ) + .divideScalar( 3 ) + .applyMatrix4( matrixWorld ); - // translate parameters to ExtrudeGeometry API + v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); - parameters.amount = parameters.height !== undefined ? parameters.height : 50; + position.setXYZ( idx, v1.x, v1.y, v1.z ); - // defaults + idx = idx + 1; - if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; - if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; - if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; + position.setXYZ( idx, v2.x, v2.y, v2.z ); - THREE.ExtrudeGeometry.call( this, shapes, parameters ); + idx = idx + 1; - this.type = 'TextGeometry'; + } -}; + position.needsUpdate = true; -THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype ); -THREE.TextGeometry.prototype.constructor = THREE.TextGeometry; + return this; -// File:src/extras/geometries/TorusBufferGeometry.js + }; -/** - * @author Mugen87 / https://github.com/Mugen87 - */ + }() ); -THREE.TorusBufferGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) { + /** + * @author WestLangley / http://github.com/WestLangley + */ - THREE.BufferGeometry.call( this ); + function EdgesGeometry ( geometry, thresholdAngle ) { + this.isEdgesGeometry = this.isBufferGeometry = true; - this.type = 'TorusBufferGeometry'; + BufferGeometry.call( this ); - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; + thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; - radius = radius || 100; - tube = tube || 40; - radialSegments = Math.floor( radialSegments ) || 8; - tubularSegments = Math.floor( tubularSegments ) || 6; - arc = arc || Math.PI * 2; + var thresholdDot = Math.cos( exports.Math.DEG2RAD * thresholdAngle ); - // used to calculate buffer length - var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); - var indexCount = radialSegments * tubularSegments * 2 * 3; + var edge = [ 0, 0 ], hash = {}; - // buffers - var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); - var vertices = new Float32Array( vertexCount * 3 ); - var normals = new Float32Array( vertexCount * 3 ); - var uvs = new Float32Array( vertexCount * 2 ); + function sortFunction( a, b ) { - // offset variables - var vertexBufferOffset = 0; - var uvBufferOffset = 0; - var indexBufferOffset = 0; + return a - b; - // helper variables - var center = new THREE.Vector3(); - var vertex = new THREE.Vector3(); - var normal = new THREE.Vector3(); + } - var j, i; + var keys = [ 'a', 'b', 'c' ]; - // generate vertices, normals and uvs + var geometry2; - for ( j = 0; j <= radialSegments; j ++ ) { + if ( (geometry && geometry.isBufferGeometry) ) { - for ( i = 0; i <= tubularSegments; i ++ ) { + geometry2 = new Geometry(); + geometry2.fromBufferGeometry( geometry ); - var u = i / tubularSegments * arc; - var v = j / radialSegments * Math.PI * 2; + } else { - // vertex - vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); - vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); - vertex.z = tube * Math.sin( v ); + geometry2 = geometry.clone(); - vertices[ vertexBufferOffset ] = vertex.x; - vertices[ vertexBufferOffset + 1 ] = vertex.y; - vertices[ vertexBufferOffset + 2 ] = vertex.z; + } - // this vector is used to calculate the normal - center.x = radius * Math.cos( u ); - center.y = radius * Math.sin( u ); + geometry2.mergeVertices(); + geometry2.computeFaceNormals(); - // normal - normal.subVectors( vertex, center ).normalize(); + var vertices = geometry2.vertices; + var faces = geometry2.faces; - normals[ vertexBufferOffset ] = normal.x; - normals[ vertexBufferOffset + 1 ] = normal.y; - normals[ vertexBufferOffset + 2 ] = normal.z; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - // uv - uvs[ uvBufferOffset ] = i / tubularSegments; - uvs[ uvBufferOffset + 1 ] = j / radialSegments; + var face = faces[ i ]; - // update offsets - vertexBufferOffset += 3; - uvBufferOffset += 2; + for ( var j = 0; j < 3; j ++ ) { - } + edge[ 0 ] = face[ keys[ j ] ]; + edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; + edge.sort( sortFunction ); - } + var key = edge.toString(); - // generate indices + if ( hash[ key ] === undefined ) { - for ( j = 1; j <= radialSegments; j ++ ) { + hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; - for ( i = 1; i <= tubularSegments; i ++ ) { + } else { - // indices - var a = ( tubularSegments + 1 ) * j + i - 1; - var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; - var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; - var d = ( tubularSegments + 1 ) * j + i; + hash[ key ].face2 = i; - // face one - indices[ indexBufferOffset ] = a; - indices[ indexBufferOffset + 1 ] = b; - indices[ indexBufferOffset + 2 ] = d; + } - // face two - indices[ indexBufferOffset + 3 ] = b; - indices[ indexBufferOffset + 4 ] = c; - indices[ indexBufferOffset + 5 ] = d; + } - // update offset - indexBufferOffset += 6; + } - } + var coords = []; - } + for ( var key in hash ) { - // build geometry - this.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + var h = hash[ key ]; -}; + if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) { -THREE.TorusBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.TorusBufferGeometry.prototype.constructor = THREE.TorusBufferGeometry; + var vertex = vertices[ h.vert1 ]; + coords.push( vertex.x ); + coords.push( vertex.y ); + coords.push( vertex.z ); -// File:src/extras/geometries/TorusGeometry.js + vertex = vertices[ h.vert2 ]; + coords.push( vertex.x ); + coords.push( vertex.y ); + coords.push( vertex.z ); -/** - * @author oosmoxiecode - * @author mrdoob / http://mrdoob.com/ - * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888 - */ + } -THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) { + } - THREE.Geometry.call( this ); + this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) ); - this.type = 'TorusGeometry'; + }; - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; + EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); + EdgesGeometry.prototype.constructor = EdgesGeometry; - this.fromBufferGeometry( new THREE.TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); + /** + * @author WestLangley / http://github.com/WestLangley + * @param object THREE.Mesh whose geometry will be used + * @param hex line color + * @param thresholdAngle the minimum angle (in degrees), + * between the face normals of adjacent faces, + * that is required to render an edge. A value of 10 means + * an edge is only rendered if the angle is at least 10 degrees. + */ -}; + function EdgesHelper ( object, hex, thresholdAngle ) { + this.isEdgesHelper = this.isLineSegments = true; -THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry; + var color = ( hex !== undefined ) ? hex : 0xffffff; -// File:src/extras/geometries/TorusKnotBufferGeometry.js + LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) ); -/** - * @author Mugen87 / https://github.com/Mugen87 - * - * see: http://www.blackpawn.com/texts/pqtorus/ - */ -THREE.TorusKnotBufferGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q ) { + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - THREE.BufferGeometry.call( this ); + }; - this.type = 'TorusKnotBufferGeometry'; + EdgesHelper.prototype = Object.create( LineSegments.prototype ); + EdgesHelper.prototype.constructor = EdgesHelper; - this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q - }; + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - radius = radius || 100; - tube = tube || 40; - tubularSegments = Math.floor( tubularSegments ) || 64; - radialSegments = Math.floor( radialSegments ) || 8; - p = p || 2; - q = q || 3; + function DirectionalLightHelper ( light, size ) { + this.isDirectionalLightHelper = this.isObject3D = true; - // used to calculate buffer length - var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); - var indexCount = radialSegments * tubularSegments * 2 * 3; + Object3D.call( this ); - // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + this.light = light; + this.light.updateMatrixWorld(); - // helper variables - var i, j, index = 0, indexOffset = 0; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - var vertex = new THREE.Vector3(); - var normal = new THREE.Vector3(); - var uv = new THREE.Vector2(); + if ( size === undefined ) size = 1; - var P1 = new THREE.Vector3(); - var P2 = new THREE.Vector3(); + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ + - size, size, 0, + size, size, 0, + size, - size, 0, + - size, - size, 0, + - size, size, 0 + ], 3 ) ); - var B = new THREE.Vector3(); - var T = new THREE.Vector3(); - var N = new THREE.Vector3(); + var material = new LineBasicMaterial( { fog: false } ); - // generate vertices, normals and uvs + this.add( new Line( geometry, material ) ); - for ( i = 0; i <= tubularSegments; ++ i ) { + geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); - // the radian "u" is used to calculate the position on the torus curve of the current tubular segement + this.add( new Line( geometry, material )); - var u = i / tubularSegments * p * Math.PI * 2; + this.update(); - // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. - // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions + }; - calculatePositionOnCurve( u, p, q, radius, P1 ); - calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); + DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); + DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; - // calculate orthonormal basis + DirectionalLightHelper.prototype.dispose = function () { - T.subVectors( P2, P1 ); - N.addVectors( P2, P1 ); - B.crossVectors( T, N ); - N.crossVectors( B, T ); + var lightPlane = this.children[ 0 ]; + var targetLine = this.children[ 1 ]; - // normalize B, N. T can be ignored, we don't use it + lightPlane.geometry.dispose(); + lightPlane.material.dispose(); + targetLine.geometry.dispose(); + targetLine.material.dispose(); - B.normalize(); - N.normalize(); + }; - for ( j = 0; j <= radialSegments; ++ j ) { + DirectionalLightHelper.prototype.update = function () { - // now calculate the vertices. they are nothing more than an extrusion of the torus curve. - // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. + var v1 = new Vector3(); + var v2 = new Vector3(); + var v3 = new Vector3(); - var v = j / radialSegments * Math.PI * 2; - var cx = - tube * Math.cos( v ); - var cy = tube * Math.sin( v ); + return function update() { - // now calculate the final vertex position. - // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve + v1.setFromMatrixPosition( this.light.matrixWorld ); + v2.setFromMatrixPosition( this.light.target.matrixWorld ); + v3.subVectors( v2, v1 ); - vertex.x = P1.x + ( cx * N.x + cy * B.x ); - vertex.y = P1.y + ( cx * N.y + cy * B.y ); - vertex.z = P1.z + ( cx * N.z + cy * B.z ); + var lightPlane = this.children[ 0 ]; + var targetLine = this.children[ 1 ]; - // vertex - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + lightPlane.lookAt( v3 ); + lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) - normal.subVectors( vertex, P1 ).normalize(); - normals.setXYZ( index, normal.x, normal.y, normal.z ); + targetLine.lookAt( v3 ); + targetLine.scale.z = v3.length(); - // uv - uv.x = i / tubularSegments; - uv.y = j / radialSegments; - uvs.setXY( index, uv.x, uv.y ); + }; - // increase index - index ++; + }(); - } + /** + * @author alteredq / http://alteredqualia.com/ + * + * - shows frustum, line of sight and up of the camera + * - suitable for fast updates + * - based on frustum visualization in lightgl.js shadowmap example + * http://evanw.github.com/lightgl.js/tests/shadowmap.html + */ - } + function CameraHelper ( camera ) { + this.isCameraHelper = this.isLineSegments = true; - // generate indices + var geometry = new Geometry(); + var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } ); - for ( j = 1; j <= tubularSegments; j ++ ) { + var pointMap = {}; - for ( i = 1; i <= radialSegments; i ++ ) { + // colors - // indices - var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - var b = ( radialSegments + 1 ) * j + ( i - 1 ); - var c = ( radialSegments + 1 ) * j + i; - var d = ( radialSegments + 1 ) * ( j - 1 ) + i; + var hexFrustum = 0xffaa00; + var hexCone = 0xff0000; + var hexUp = 0x00aaff; + var hexTarget = 0xffffff; + var hexCross = 0x333333; - // face one - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + // near - // face two - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + addLine( "n1", "n2", hexFrustum ); + addLine( "n2", "n4", hexFrustum ); + addLine( "n4", "n3", hexFrustum ); + addLine( "n3", "n1", hexFrustum ); - } + // far - } + addLine( "f1", "f2", hexFrustum ); + addLine( "f2", "f4", hexFrustum ); + addLine( "f4", "f3", hexFrustum ); + addLine( "f3", "f1", hexFrustum ); - // build geometry + // sides - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + addLine( "n1", "f1", hexFrustum ); + addLine( "n2", "f2", hexFrustum ); + addLine( "n3", "f3", hexFrustum ); + addLine( "n4", "f4", hexFrustum ); - // this function calculates the current position on the torus curve + // cone - function calculatePositionOnCurve( u, p, q, radius, position ) { + addLine( "p", "n1", hexCone ); + addLine( "p", "n2", hexCone ); + addLine( "p", "n3", hexCone ); + addLine( "p", "n4", hexCone ); - var cu = Math.cos( u ); - var su = Math.sin( u ); - var quOverP = q / p * u; - var cs = Math.cos( quOverP ); + // up - position.x = radius * ( 2 + cs ) * 0.5 * cu; - position.y = radius * ( 2 + cs ) * su * 0.5; - position.z = radius * Math.sin( quOverP ) * 0.5; + addLine( "u1", "u2", hexUp ); + addLine( "u2", "u3", hexUp ); + addLine( "u3", "u1", hexUp ); - } + // target -}; + addLine( "c", "t", hexTarget ); + addLine( "p", "c", hexCross ); -THREE.TorusKnotBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.TorusKnotBufferGeometry.prototype.constructor = THREE.TorusKnotBufferGeometry; + // cross -// File:src/extras/geometries/TorusKnotGeometry.js + addLine( "cn1", "cn2", hexCross ); + addLine( "cn3", "cn4", hexCross ); -/** - * @author oosmoxiecode - */ + addLine( "cf1", "cf2", hexCross ); + addLine( "cf3", "cf4", hexCross ); -THREE.TorusKnotGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { + function addLine( a, b, hex ) { - THREE.Geometry.call( this ); + addPoint( a, hex ); + addPoint( b, hex ); - this.type = 'TorusKnotGeometry'; + } - this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q - }; + function addPoint( id, hex ) { - if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( hex ) ); - this.fromBufferGeometry( new THREE.TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); - this.mergeVertices(); + if ( pointMap[ id ] === undefined ) { -}; + pointMap[ id ] = []; -THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry; + } -// File:src/extras/geometries/TubeGeometry.js + pointMap[ id ].push( geometry.vertices.length - 1 ); -/** - * @author WestLangley / https://github.com/WestLangley - * @author zz85 / https://github.com/zz85 - * @author miningold / https://github.com/miningold - * @author jonobr1 / https://github.com/jonobr1 - * - * Modified from the TorusKnotGeometry by @oosmoxiecode - * - * Creates a tube which extrudes along a 3d spline - * - * Uses parallel transport frames as described in - * http://www.cs.indiana.edu/pub/techreports/TR425.pdf - */ + } -THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) { + LineSegments.call( this, geometry, material ); - THREE.Geometry.call( this ); + this.camera = camera; + if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); - this.type = 'TubeGeometry'; + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; - this.parameters = { - path: path, - segments: segments, - radius: radius, - radialSegments: radialSegments, - closed: closed, - taper: taper - }; + this.pointMap = pointMap; - segments = segments || 64; - radius = radius || 1; - radialSegments = radialSegments || 8; - closed = closed || false; - taper = taper || THREE.TubeGeometry.NoTaper; + this.update(); - var grid = []; + }; - var scope = this, + CameraHelper.prototype = Object.create( LineSegments.prototype ); + CameraHelper.prototype.constructor = CameraHelper; - tangent, - normal, - binormal, + CameraHelper.prototype.update = function () { - numpoints = segments + 1, + var geometry, pointMap; - u, v, r, + var vector = new Vector3(); + var camera = new Camera(); - cx, cy, - pos, pos2 = new THREE.Vector3(), - i, j, - ip, jp, - a, b, c, d, - uva, uvb, uvc, uvd; + function setPoint( point, x, y, z ) { - var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ), - tangents = frames.tangents, - normals = frames.normals, - binormals = frames.binormals; + vector.set( x, y, z ).unproject( camera ); - // proxy internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + var points = pointMap[ point ]; - function vert( x, y, z ) { + if ( points !== undefined ) { - return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1; + for ( var i = 0, il = points.length; i < il; i ++ ) { - } + geometry.vertices[ points[ i ] ].copy( vector ); - // construct the grid + } - for ( i = 0; i < numpoints; i ++ ) { + } - grid[ i ] = []; + } - u = i / ( numpoints - 1 ); + return function update() { - pos = path.getPointAt( u ); + geometry = this.geometry; + pointMap = this.pointMap; - tangent = tangents[ i ]; - normal = normals[ i ]; - binormal = binormals[ i ]; + var w = 1, h = 1; - r = radius * taper( u ); + // we need just camera projection matrix + // world matrix must be identity - for ( j = 0; j < radialSegments; j ++ ) { + camera.projectionMatrix.copy( this.camera.projectionMatrix ); - v = j / radialSegments * 2 * Math.PI; + // center / target - cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. - cy = r * Math.sin( v ); + setPoint( "c", 0, 0, - 1 ); + setPoint( "t", 0, 0, 1 ); - pos2.copy( pos ); - pos2.x += cx * normal.x + cy * binormal.x; - pos2.y += cx * normal.y + cy * binormal.y; - pos2.z += cx * normal.z + cy * binormal.z; + // near - grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); + setPoint( "n1", - w, - h, - 1 ); + setPoint( "n2", w, - h, - 1 ); + setPoint( "n3", - w, h, - 1 ); + setPoint( "n4", w, h, - 1 ); - } + // far - } + setPoint( "f1", - w, - h, 1 ); + setPoint( "f2", w, - h, 1 ); + setPoint( "f3", - w, h, 1 ); + setPoint( "f4", w, h, 1 ); + // up - // construct the mesh + setPoint( "u1", w * 0.7, h * 1.1, - 1 ); + setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); + setPoint( "u3", 0, h * 2, - 1 ); - for ( i = 0; i < segments; i ++ ) { + // cross - for ( j = 0; j < radialSegments; j ++ ) { + setPoint( "cf1", - w, 0, 1 ); + setPoint( "cf2", w, 0, 1 ); + setPoint( "cf3", 0, - h, 1 ); + setPoint( "cf4", 0, h, 1 ); - ip = ( closed ) ? ( i + 1 ) % segments : i + 1; - jp = ( j + 1 ) % radialSegments; + setPoint( "cn1", - w, 0, - 1 ); + setPoint( "cn2", w, 0, - 1 ); + setPoint( "cn3", 0, - h, - 1 ); + setPoint( "cn4", 0, h, - 1 ); - a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** - b = grid[ ip ][ j ]; - c = grid[ ip ][ jp ]; - d = grid[ i ][ jp ]; + geometry.verticesNeedUpdate = true; - uva = new THREE.Vector2( i / segments, j / radialSegments ); - uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments ); - uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments ); - uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments ); + }; - this.faces.push( new THREE.Face3( a, b, d ) ); - this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); + }(); - this.faces.push( new THREE.Face3( b, c, d ) ); - this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as + */ - } + function BoxGeometry ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + this.isBoxGeometry = this.isGeometry = true; - } + Geometry.call( this ); - this.computeFaceNormals(); - this.computeVertexNormals(); + this.type = 'BoxGeometry'; -}; + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; -THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry; + this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); + this.mergeVertices(); -THREE.TubeGeometry.NoTaper = function ( u ) { + }; - return 1; + BoxGeometry.prototype = Object.create( Geometry.prototype ); + BoxGeometry.prototype.constructor = BoxGeometry; -}; + exports.CubeGeometry = BoxGeometry; -THREE.TubeGeometry.SinusoidalTaper = function ( u ) { + /** + * @author WestLangley / http://github.com/WestLangley + */ - return Math.sin( Math.PI * u ); + // a helper to show the world-axis-aligned bounding box for an object -}; + function BoundingBoxHelper ( object, hex ) { + this.isBoundingBoxHelper = this.isMesh = true; -// For computing of Frenet frames, exposing the tangents, normals and binormals the spline -THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { + var color = ( hex !== undefined ) ? hex : 0x888888; - var normal = new THREE.Vector3(), + this.object = object; - tangents = [], - normals = [], - binormals = [], + this.box = new Box3(); - vec = new THREE.Vector3(), - mat = new THREE.Matrix4(), + Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) ); - numpoints = segments + 1, - theta, - smallest, + }; - tx, ty, tz, - i, u; + BoundingBoxHelper.prototype = Object.create( Mesh.prototype ); + BoundingBoxHelper.prototype.constructor = BoundingBoxHelper; + BoundingBoxHelper.prototype.update = function () { - // expose internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + this.box.setFromObject( this.object ); - // compute the tangent vectors for each segment on the path + this.box.size( this.scale ); - for ( i = 0; i < numpoints; i ++ ) { + this.box.center( this.position ); - u = i / ( numpoints - 1 ); + }; - tangents[ i ] = path.getTangentAt( u ); - tangents[ i ].normalize(); + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function BoxHelper ( object, color ) { + this.isBoxHelper = this.isLineSegments = true; - initialNormal3(); + if ( color === undefined ) color = 0xffff00; - /* - function initialNormal1(lastBinormal) { - // fixed start binormal. Has dangers of 0 vectors - normals[ 0 ] = new THREE.Vector3(); - binormals[ 0 ] = new THREE.Vector3(); - if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 ); - normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize(); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); - } + var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); + var positions = new Float32Array( 8 * 3 ); - function initialNormal2() { + var geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); - // This uses the Frenet-Serret formula for deriving binormal - var t2 = path.getTangentAt( epsilon ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); - normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); - binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); + if ( object !== undefined ) { - normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); + this.update( object ); - } - */ + } - function initialNormal3() { + }; - // select an initial normal vector perpendicular to the first tangent vector, - // and in the direction of the smallest tangent xyz component + BoxHelper.prototype = Object.create( LineSegments.prototype ); + BoxHelper.prototype.constructor = BoxHelper; - normals[ 0 ] = new THREE.Vector3(); - binormals[ 0 ] = new THREE.Vector3(); - smallest = Number.MAX_VALUE; - tx = Math.abs( tangents[ 0 ].x ); - ty = Math.abs( tangents[ 0 ].y ); - tz = Math.abs( tangents[ 0 ].z ); + BoxHelper.prototype.update = ( function () { - if ( tx <= smallest ) { + var box = new Box3(); - smallest = tx; - normal.set( 1, 0, 0 ); + return function update( object ) { - } + if ( (object && object.isBox3) ) { - if ( ty <= smallest ) { + box.copy( object ); - smallest = ty; - normal.set( 0, 1, 0 ); + } else { - } + box.setFromObject( object ); - if ( tz <= smallest ) { + } - normal.set( 0, 0, 1 ); + if ( box.isEmpty() ) return; - } + var min = box.min; + var max = box.max; - vec.crossVectors( tangents[ 0 ], normal ).normalize(); + /* + 5____4 + 1/___0/| + | 6__|_7 + 2/___3/ - normals[ 0 ].crossVectors( tangents[ 0 ], vec ); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + 0: max.x, max.y, max.z + 1: min.x, max.y, max.z + 2: min.x, min.y, max.z + 3: max.x, min.y, max.z + 4: max.x, max.y, min.z + 5: min.x, max.y, min.z + 6: min.x, min.y, min.z + 7: max.x, min.y, min.z + */ - } + var position = this.geometry.attributes.position; + var array = position.array; + array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; + array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; + array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; + array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; + array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; + array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; + array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; + array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z; - // compute the slowly-varying normal and binormal vectors for each segment on the path + position.needsUpdate = true; - for ( i = 1; i < numpoints; i ++ ) { + this.geometry.computeBoundingSphere(); - normals[ i ] = normals[ i - 1 ].clone(); + }; - binormals[ i ] = binormals[ i - 1 ].clone(); + } )(); - vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - if ( vec.length() > Number.EPSILON ) { + function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isCylinderBufferGeometry = this.isBufferGeometry = true; - vec.normalize(); + BufferGeometry.call( this ); - theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + this.type = 'CylinderBufferGeometry'; - normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - } + var scope = this; - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + radiusTop = radiusTop !== undefined ? radiusTop : 20; + radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; + height = height !== undefined ? height : 100; - } + radialSegments = Math.floor( radialSegments ) || 8; + heightSegments = Math.floor( heightSegments ) || 1; + openEnded = openEnded !== undefined ? openEnded : false; + thetaStart = thetaStart !== undefined ? thetaStart : 0.0; + thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI; - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + // used to calculate buffer length - if ( closed ) { + var nbCap = 0; - theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); - theta /= ( numpoints - 1 ); + if ( openEnded === false ) { - if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { + if ( radiusTop > 0 ) nbCap ++; + if ( radiusBottom > 0 ) nbCap ++; - theta = - theta; + } - } + var vertexCount = calculateVertexCount(); + var indexCount = calculateIndexCount(); - for ( i = 1; i < numpoints; i ++ ) { + // buffers - // twist a little... - normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - } + // helper variables - } + var index = 0, + indexOffset = 0, + indexArray = [], + halfHeight = height / 2; -}; + // group variables + var groupStart = 0; -// File:src/extras/geometries/PolyhedronGeometry.js + // generate geometry -/** - * @author clockworkgeek / https://github.com/clockworkgeek - * @author timothypratley / https://github.com/timothypratley - * @author WestLangley / http://github.com/WestLangley -*/ + generateTorso(); -THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { + if ( openEnded === false ) { - THREE.Geometry.call( this ); + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); - this.type = 'PolyhedronGeometry'; + } - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + // build geometry - radius = radius || 1; - detail = detail || 0; + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - var that = this; + // helper functions - for ( var i = 0, l = vertices.length; i < l; i += 3 ) { + function calculateVertexCount() { - prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); + var count = ( radialSegments + 1 ) * ( heightSegments + 1 ); - } + if ( openEnded === false ) { - var p = this.vertices; + count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap ); - var faces = []; + } - for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) { + return count; - var v1 = p[ indices[ i ] ]; - var v2 = p[ indices[ i + 1 ] ]; - var v3 = p[ indices[ i + 2 ] ]; + } - faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); + function calculateIndexCount() { - } + var count = radialSegments * heightSegments * 2 * 3; - var centroid = new THREE.Vector3(); + if ( openEnded === false ) { - for ( var i = 0, l = faces.length; i < l; i ++ ) { + count += radialSegments * nbCap * 3; - subdivide( faces[ i ], detail ); + } - } + return count; + } - // Handle case when face straddles the seam + function generateTorso() { - for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { + var x, y; + var normal = new Vector3(); + var vertex = new Vector3(); - var uvs = this.faceVertexUvs[ 0 ][ i ]; + var groupCount = 0; - var x0 = uvs[ 0 ].x; - var x1 = uvs[ 1 ].x; - var x2 = uvs[ 2 ].x; + // this will be used to calculate the normal + var tanTheta = ( radiusBottom - radiusTop ) / height; - var max = Math.max( x0, x1, x2 ); - var min = Math.min( x0, x1, x2 ); + // generate vertices, normals and uvs - if ( max > 0.9 && min < 0.1 ) { + for ( y = 0; y <= heightSegments; y ++ ) { - // 0.9 is somewhat arbitrary + var indexRow = []; - if ( x0 < 0.2 ) uvs[ 0 ].x += 1; - if ( x1 < 0.2 ) uvs[ 1 ].x += 1; - if ( x2 < 0.2 ) uvs[ 2 ].x += 1; + var v = y / heightSegments; - } + // calculate the radius of the current row + var radius = v * ( radiusBottom - radiusTop ) + radiusTop; - } + for ( x = 0; x <= radialSegments; x ++ ) { + var u = x / radialSegments; - // Apply radius + // vertex + vertex.x = radius * Math.sin( u * thetaLength + thetaStart ); + vertex.y = - v * height + halfHeight; + vertex.z = radius * Math.cos( u * thetaLength + thetaStart ); + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { + // normal + normal.copy( vertex ); - this.vertices[ i ].multiplyScalar( radius ); + // handle special case if radiusTop/radiusBottom is zero - } + if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) { + normal.x = Math.sin( u * thetaLength + thetaStart ); + normal.z = Math.cos( u * thetaLength + thetaStart ); - // Merge vertices + } - this.mergeVertices(); + normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize(); + normals.setXYZ( index, normal.x, normal.y, normal.z ); - this.computeFaceNormals(); + // uv + uvs.setXY( index, u, 1 - v ); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + // save index of vertex in respective row + indexRow.push( index ); + // increase index + index ++; - // Project vector onto sphere's surface + } - function prepare( vector ) { + // now save vertices of the row in our index array + indexArray.push( indexRow ); - var vertex = vector.normalize().clone(); - vertex.index = that.vertices.push( vertex ) - 1; + } - // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. + // generate indices - var u = azimuth( vector ) / 2 / Math.PI + 0.5; - var v = inclination( vector ) / Math.PI + 0.5; - vertex.uv = new THREE.Vector2( u, 1 - v ); + for ( x = 0; x < radialSegments; x ++ ) { - return vertex; + for ( y = 0; y < heightSegments; y ++ ) { - } + // we use the index array to access the correct indices + var i1 = indexArray[ y ][ x ]; + var i2 = indexArray[ y + 1 ][ x ]; + var i3 = indexArray[ y + 1 ][ x + 1 ]; + var i4 = indexArray[ y ][ x + 1 ]; + // face one + indices.setX( indexOffset, i1 ); indexOffset ++; + indices.setX( indexOffset, i2 ); indexOffset ++; + indices.setX( indexOffset, i4 ); indexOffset ++; - // Approximate a curved face with recursively sub-divided triangles. + // face two + indices.setX( indexOffset, i2 ); indexOffset ++; + indices.setX( indexOffset, i3 ); indexOffset ++; + indices.setX( indexOffset, i4 ); indexOffset ++; - function make( v1, v2, v3 ) { + // update counters + groupCount += 6; - var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - that.faces.push( face ); + } - centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); + } - var azi = azimuth( centroid ); + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, 0 ); - that.faceVertexUvs[ 0 ].push( [ - correctUV( v1.uv, v1, azi ), - correctUV( v2.uv, v2, azi ), - correctUV( v3.uv, v3, azi ) - ] ); + // calculate new start value for groups + groupStart += groupCount; - } + } + function generateCap( top ) { - // Analytically subdivide a face to the required detail level. + var x, centerIndexStart, centerIndexEnd; - function subdivide( face, detail ) { + var uv = new Vector2(); + var vertex = new Vector3(); - var cols = Math.pow( 2, detail ); - var a = prepare( that.vertices[ face.a ] ); - var b = prepare( that.vertices[ face.b ] ); - var c = prepare( that.vertices[ face.c ] ); - var v = []; + var groupCount = 0; - // Construct all of the vertices for this subdivision. + var radius = ( top === true ) ? radiusTop : radiusBottom; + var sign = ( top === true ) ? 1 : - 1; - for ( var i = 0 ; i <= cols; i ++ ) { + // save the index of the first center vertex + centerIndexStart = index; - v[ i ] = []; + // first we generate the center vertex data of the cap. + // because the geometry needs one set of uvs per face, + // we must generate a center vertex per face/segment - var aj = prepare( a.clone().lerp( c, i / cols ) ); - var bj = prepare( b.clone().lerp( c, i / cols ) ); - var rows = cols - i; + for ( x = 1; x <= radialSegments; x ++ ) { - for ( var j = 0; j <= rows; j ++ ) { + // vertex + vertices.setXYZ( index, 0, halfHeight * sign, 0 ); - if ( j === 0 && i === cols ) { + // normal + normals.setXYZ( index, 0, sign, 0 ); - v[ i ][ j ] = aj; + // uv + uv.x = 0.5; + uv.y = 0.5; - } else { + uvs.setXY( index, uv.x, uv.y ); - v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); + // increase index + index ++; - } + } - } + // save the index of the last center vertex + centerIndexEnd = index; - } + // now we generate the surrounding vertices, normals and uvs - // Construct all of the faces. + for ( x = 0; x <= radialSegments; x ++ ) { - for ( var i = 0; i < cols ; i ++ ) { + var u = x / radialSegments; + var theta = u * thetaLength + thetaStart; - for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + var cosTheta = Math.cos( theta ); + var sinTheta = Math.sin( theta ); - var k = Math.floor( j / 2 ); + // vertex + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - if ( j % 2 === 0 ) { + // normal + normals.setXYZ( index, 0, sign, 0 ); - make( - v[ i ][ k + 1 ], - v[ i + 1 ][ k ], - v[ i ][ k ] - ); + // uv + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.setXY( index, uv.x, uv.y ); - } else { + // increase index + index ++; - make( - v[ i ][ k + 1 ], - v[ i + 1 ][ k + 1 ], - v[ i + 1 ][ k ] - ); + } - } + // generate indices - } + for ( x = 0; x < radialSegments; x ++ ) { - } + var c = centerIndexStart + x; + var i = centerIndexEnd + x; - } + if ( top === true ) { + // face top + indices.setX( indexOffset, i ); indexOffset ++; + indices.setX( indexOffset, i + 1 ); indexOffset ++; + indices.setX( indexOffset, c ); indexOffset ++; - // Angle around the Y axis, counter-clockwise when looking from above. + } else { - function azimuth( vector ) { + // face bottom + indices.setX( indexOffset, i + 1 ); indexOffset ++; + indices.setX( indexOffset, i ); indexOffset ++; + indices.setX( indexOffset, c ); indexOffset ++; - return Math.atan2( vector.z, - vector.x ); + } - } + // update counters + groupCount += 3; + } - // Angle above the XZ plane. + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); - function inclination( vector ) { + // calculate new start value for groups + groupStart += groupCount; - return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + } - } + }; + CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; - // Texture fixing helper. Spheres have some odd behaviours. + /** + * @author WestLangley / http://github.com/WestLangley + * @author zz85 / http://github.com/zz85 + * @author bhouston / http://clara.io + * + * Creates an arrow for visualizing directions + * + * Parameters: + * dir - Vector3 + * origin - Vector3 + * length - Number + * color - color in hex value + * headLength - Number + * headWidth - Number + */ - function correctUV( uv, vector, azimuth ) { + exports.ArrowHelper = ( function () { - if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y ); - if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y ); - return uv.clone(); + var lineGeometry = new BufferGeometry(); + lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); - } + var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); + coneGeometry.translate( 0, - 0.5, 0 ); + return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { -}; + // dir is assumed to be normalized -THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry; + Object3D.call( this ); -// File:src/extras/geometries/DodecahedronGeometry.js + if ( color === undefined ) color = 0xffff00; + if ( length === undefined ) length = 1; + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; -/** - * @author Abe Pazos / https://hamoid.com - */ + this.position.copy( origin ); -THREE.DodecahedronGeometry = function ( radius, detail ) { - - var t = ( 1 + Math.sqrt( 5 ) ) / 2; - var r = 1 / t; - - var vertices = [ - - // (±1, ±1, ±1) - - 1, - 1, - 1, - 1, - 1, 1, - - 1, 1, - 1, - 1, 1, 1, - 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, 1, 1, 1, - - // (0, ±1/φ, ±φ) - 0, - r, - t, 0, - r, t, - 0, r, - t, 0, r, t, - - // (±1/φ, ±φ, 0) - - r, - t, 0, - r, t, 0, - r, - t, 0, r, t, 0, - - // (±φ, 0, ±1/φ) - - t, 0, - r, t, 0, - r, - - t, 0, r, t, 0, r - ]; - - var indices = [ - 3, 11, 7, 3, 7, 15, 3, 15, 13, - 7, 19, 17, 7, 17, 6, 7, 6, 15, - 17, 4, 8, 17, 8, 10, 17, 10, 6, - 8, 0, 16, 8, 16, 2, 8, 2, 10, - 0, 12, 1, 0, 1, 18, 0, 18, 16, - 6, 10, 2, 6, 2, 13, 6, 13, 15, - 2, 16, 18, 2, 18, 3, 2, 3, 13, - 18, 1, 9, 18, 9, 11, 18, 11, 3, - 4, 14, 12, 4, 12, 0, 4, 0, 8, - 11, 9, 5, 11, 5, 19, 11, 19, 7, - 19, 5, 14, 19, 14, 4, 19, 4, 17, - 1, 12, 14, 1, 14, 5, 1, 5, 9 - ]; - - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - - this.type = 'DodecahedronGeometry'; - - this.parameters = { - radius: radius, - detail: detail - }; + this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); -}; + this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); -THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry; + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); -// File:src/extras/geometries/IcosahedronGeometry.js + }; -/** - * @author timothypratley / https://github.com/timothypratley - */ + }() ); -THREE.IcosahedronGeometry = function ( radius, detail ) { + exports.ArrowHelper.prototype = Object.create( Object3D.prototype ); + exports.ArrowHelper.prototype.constructor = exports.ArrowHelper; - var t = ( 1 + Math.sqrt( 5 ) ) / 2; + exports.ArrowHelper.prototype.setDirection = ( function () { - var vertices = [ - - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, - 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, - t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 - ]; + var axis = new Vector3(); + var radians; - var indices = [ - 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, - 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, - 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, - 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 - ]; + return function setDirection( dir ) { - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + // dir is assumed to be normalized - this.type = 'IcosahedronGeometry'; + if ( dir.y > 0.99999 ) { - this.parameters = { - radius: radius, - detail: detail - }; + this.quaternion.set( 0, 0, 0, 1 ); -}; + } else if ( dir.y < - 0.99999 ) { -THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry; + this.quaternion.set( 1, 0, 0, 0 ); -// File:src/extras/geometries/OctahedronGeometry.js + } else { -/** - * @author timothypratley / https://github.com/timothypratley - */ + axis.set( dir.z, 0, - dir.x ).normalize(); -THREE.OctahedronGeometry = function ( radius, detail ) { + radians = Math.acos( dir.y ); - var vertices = [ - 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1 - ]; + this.quaternion.setFromAxisAngle( axis, radians ); - var indices = [ - 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 - ]; + } - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + }; - this.type = 'OctahedronGeometry'; + }() ); - this.parameters = { - radius: radius, - detail: detail - }; + exports.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { -}; + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; -THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry; + this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 ); + this.line.updateMatrix(); -// File:src/extras/geometries/TetrahedronGeometry.js + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); -/** - * @author timothypratley / https://github.com/timothypratley - */ + }; -THREE.TetrahedronGeometry = function ( radius, detail ) { + exports.ArrowHelper.prototype.setColor = function ( color ) { - var vertices = [ - 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 - ]; + this.line.material.color.copy( color ); + this.cone.material.color.copy( color ); - var indices = [ - 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 - ]; + }; - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + /** + * @author sroucheray / http://sroucheray.org/ + * @author mrdoob / http://mrdoob.com/ + */ - this.type = 'TetrahedronGeometry'; + function AxisHelper ( size ) { + this.isAxisHelper = this.isLineSegments = true; - this.parameters = { - radius: radius, - detail: detail - }; + size = size || 1; -}; + var vertices = new Float32Array( [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ] ); -THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry; + var colors = new Float32Array( [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ] ); -// File:src/extras/geometries/ParametricGeometry.js + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) ); -/** - * @author zz85 / https://github.com/zz85 - * Parametric Surfaces Geometry - * based on the brilliant article by @prideout http://prideout.net/blog/?p=44 - * - * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements ); - * - */ + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); -THREE.ParametricGeometry = function ( func, slices, stacks ) { + LineSegments.call( this, geometry, material ); - THREE.Geometry.call( this ); + }; - this.type = 'ParametricGeometry'; + AxisHelper.prototype = Object.create( LineSegments.prototype ); + AxisHelper.prototype.constructor = AxisHelper; - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; + /** + * @author zz85 / https://github.com/zz85 + * Parametric Surfaces Geometry + * based on the brilliant article by @prideout http://prideout.net/blog/?p=44 + * + * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements ); + * + */ - var verts = this.vertices; - var faces = this.faces; - var uvs = this.faceVertexUvs[ 0 ]; + function ParametricGeometry ( func, slices, stacks ) { + this.isParametricGeometry = this.isGeometry = true; - var i, j, p; - var u, v; + Geometry.call( this ); - var sliceCount = slices + 1; + this.type = 'ParametricGeometry'; - for ( i = 0; i <= stacks; i ++ ) { + this.parameters = { + func: func, + slices: slices, + stacks: stacks + }; - v = i / stacks; + var verts = this.vertices; + var faces = this.faces; + var uvs = this.faceVertexUvs[ 0 ]; - for ( j = 0; j <= slices; j ++ ) { + var i, j, p; + var u, v; - u = j / slices; + var sliceCount = slices + 1; - p = func( u, v ); - verts.push( p ); + for ( i = 0; i <= stacks; i ++ ) { - } + v = i / stacks; - } + for ( j = 0; j <= slices; j ++ ) { - var a, b, c, d; - var uva, uvb, uvc, uvd; + u = j / slices; - for ( i = 0; i < stacks; i ++ ) { + p = func( u, v ); + verts.push( p ); - for ( j = 0; j < slices; j ++ ) { + } - a = i * sliceCount + j; - b = i * sliceCount + j + 1; - c = ( i + 1 ) * sliceCount + j + 1; - d = ( i + 1 ) * sliceCount + j; + } - uva = new THREE.Vector2( j / slices, i / stacks ); - uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks ); - uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); - uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks ); + var a, b, c, d; + var uva, uvb, uvc, uvd; - faces.push( new THREE.Face3( a, b, d ) ); - uvs.push( [ uva, uvb, uvd ] ); + for ( i = 0; i < stacks; i ++ ) { - faces.push( new THREE.Face3( b, c, d ) ); - uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); + for ( j = 0; j < slices; j ++ ) { - } + a = i * sliceCount + j; + b = i * sliceCount + j + 1; + c = ( i + 1 ) * sliceCount + j + 1; + d = ( i + 1 ) * sliceCount + j; - } + uva = new Vector2( j / slices, i / stacks ); + uvb = new Vector2( ( j + 1 ) / slices, i / stacks ); + uvc = new Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); + uvd = new Vector2( j / slices, ( i + 1 ) / stacks ); - // console.log(this); + faces.push( new Face3( a, b, d ) ); + uvs.push( [ uva, uvb, uvd ] ); - // magic bullet - // var diff = this.mergeVertices(); - // console.log('removed ', diff, ' vertices by merging'); + faces.push( new Face3( b, c, d ) ); + uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); - this.computeFaceNormals(); - this.computeVertexNormals(); + } -}; + } -THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry; + // console.log(this); -// File:src/extras/geometries/WireframeGeometry.js + // magic bullet + // var diff = this.mergeVertices(); + // console.log('removed ', diff, ' vertices by merging'); -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.computeFaceNormals(); + this.computeVertexNormals(); -THREE.WireframeGeometry = function ( geometry ) { + }; - THREE.BufferGeometry.call( this ); + ParametricGeometry.prototype = Object.create( Geometry.prototype ); + ParametricGeometry.prototype.constructor = ParametricGeometry; - var edge = [ 0, 0 ], hash = {}; + /** + * @author clockworkgeek / https://github.com/clockworkgeek + * @author timothypratley / https://github.com/timothypratley + * @author WestLangley / http://github.com/WestLangley + */ - function sortFunction( a, b ) { + function PolyhedronGeometry ( vertices, indices, radius, detail ) { + this.isPolyhedronGeometry = this.isGeometry = true; - return a - b; + Geometry.call( this ); - } + this.type = 'PolyhedronGeometry'; - var keys = [ 'a', 'b', 'c' ]; + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; - if ( geometry instanceof THREE.Geometry ) { + radius = radius || 1; + detail = detail || 0; - var vertices = geometry.vertices; - var faces = geometry.faces; - var numEdges = 0; + var that = this; - // allocate maximal size - var edges = new Uint32Array( 6 * faces.length ); + for ( var i = 0, l = vertices.length; i < l; i += 3 ) { - for ( var i = 0, l = faces.length; i < l; i ++ ) { + prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); - var face = faces[ i ]; + } - for ( var j = 0; j < 3; j ++ ) { + var p = this.vertices; - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); + var faces = []; - var key = edge.toString(); + for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) { - if ( hash[ key ] === undefined ) { + var v1 = p[ indices[ i ] ]; + var v2 = p[ indices[ i + 1 ] ]; + var v3 = p[ indices[ i + 2 ] ]; - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - } + } - } + var centroid = new Vector3(); - } + for ( var i = 0, l = faces.length; i < l; i ++ ) { - var coords = new Float32Array( numEdges * 2 * 3 ); + subdivide( faces[ i ], detail ); - for ( var i = 0, l = numEdges; i < l; i ++ ) { + } - for ( var j = 0; j < 2; j ++ ) { - var vertex = vertices[ edges [ 2 * i + j ] ]; + // Handle case when face straddles the seam - var index = 6 * i + 3 * j; - coords[ index + 0 ] = vertex.x; - coords[ index + 1 ] = vertex.y; - coords[ index + 2 ] = vertex.z; + for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { - } + var uvs = this.faceVertexUvs[ 0 ][ i ]; - } + var x0 = uvs[ 0 ].x; + var x1 = uvs[ 1 ].x; + var x2 = uvs[ 2 ].x; - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + var max = Math.max( x0, x1, x2 ); + var min = Math.min( x0, x1, x2 ); - } else if ( geometry instanceof THREE.BufferGeometry ) { + if ( max > 0.9 && min < 0.1 ) { - if ( geometry.index !== null ) { + // 0.9 is somewhat arbitrary - // Indexed BufferGeometry + if ( x0 < 0.2 ) uvs[ 0 ].x += 1; + if ( x1 < 0.2 ) uvs[ 1 ].x += 1; + if ( x2 < 0.2 ) uvs[ 2 ].x += 1; - var indices = geometry.index.array; - var vertices = geometry.attributes.position; - var groups = geometry.groups; - var numEdges = 0; + } - if ( groups.length === 0 ) { + } - geometry.addGroup( 0, indices.length ); - } + // Apply radius - // allocate maximal size - var edges = new Uint32Array( 2 * indices.length ); + for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { - for ( var o = 0, ol = groups.length; o < ol; ++ o ) { + this.vertices[ i ].multiplyScalar( radius ); - var group = groups[ o ]; + } - var start = group.start; - var count = group.count; - for ( var i = start, il = start + count; i < il; i += 3 ) { + // Merge vertices - for ( var j = 0; j < 3; j ++ ) { + this.mergeVertices(); - edge[ 0 ] = indices[ i + j ]; - edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ]; - edge.sort( sortFunction ); + this.computeFaceNormals(); - var key = edge.toString(); + this.boundingSphere = new Sphere( new Vector3(), radius ); - if ( hash[ key ] === undefined ) { - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + // Project vector onto sphere's surface - } + function prepare( vector ) { - } + var vertex = vector.normalize().clone(); + vertex.index = that.vertices.push( vertex ) - 1; - } + // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. - } + var u = azimuth( vector ) / 2 / Math.PI + 0.5; + var v = inclination( vector ) / Math.PI + 0.5; + vertex.uv = new Vector2( u, 1 - v ); - var coords = new Float32Array( numEdges * 2 * 3 ); + return vertex; - for ( var i = 0, l = numEdges; i < l; i ++ ) { + } - for ( var j = 0; j < 2; j ++ ) { - var index = 6 * i + 3 * j; - var index2 = edges[ 2 * i + j ]; + // Approximate a curved face with recursively sub-divided triangles. - coords[ index + 0 ] = vertices.getX( index2 ); - coords[ index + 1 ] = vertices.getY( index2 ); - coords[ index + 2 ] = vertices.getZ( index2 ); + function make( v1, v2, v3 ) { - } + var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); + that.faces.push( face ); - } + centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + var azi = azimuth( centroid ); - } else { + that.faceVertexUvs[ 0 ].push( [ + correctUV( v1.uv, v1, azi ), + correctUV( v2.uv, v2, azi ), + correctUV( v3.uv, v3, azi ) + ] ); - // non-indexed BufferGeometry + } - var vertices = geometry.attributes.position.array; - var numEdges = vertices.length / 3; - var numTris = numEdges / 3; - var coords = new Float32Array( numEdges * 2 * 3 ); + // Analytically subdivide a face to the required detail level. - for ( var i = 0, l = numTris; i < l; i ++ ) { + function subdivide( face, detail ) { - for ( var j = 0; j < 3; j ++ ) { + var cols = Math.pow( 2, detail ); + var a = prepare( that.vertices[ face.a ] ); + var b = prepare( that.vertices[ face.b ] ); + var c = prepare( that.vertices[ face.c ] ); + var v = []; - var index = 18 * i + 6 * j; + // Construct all of the vertices for this subdivision. - var index1 = 9 * i + 3 * j; - coords[ index + 0 ] = vertices[ index1 ]; - coords[ index + 1 ] = vertices[ index1 + 1 ]; - coords[ index + 2 ] = vertices[ index1 + 2 ]; + for ( var i = 0 ; i <= cols; i ++ ) { - var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 ); - coords[ index + 3 ] = vertices[ index2 ]; - coords[ index + 4 ] = vertices[ index2 + 1 ]; - coords[ index + 5 ] = vertices[ index2 + 2 ]; + v[ i ] = []; - } + var aj = prepare( a.clone().lerp( c, i / cols ) ); + var bj = prepare( b.clone().lerp( c, i / cols ) ); + var rows = cols - i; - } + for ( var j = 0; j <= rows; j ++ ) { - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + if ( j === 0 && i === cols ) { - } + v[ i ][ j ] = aj; - } + } else { -}; + v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); -THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry; + } -// File:src/extras/helpers/AxisHelper.js + } -/** - * @author sroucheray / http://sroucheray.org/ - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.AxisHelper = function ( size ) { + // Construct all of the faces. - size = size || 1; + for ( var i = 0; i < cols ; i ++ ) { - var vertices = new Float32Array( [ - 0, 0, 0, size, 0, 0, - 0, 0, 0, 0, size, 0, - 0, 0, 0, 0, 0, size - ] ); + for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { - var colors = new Float32Array( [ - 1, 0, 0, 1, 0.6, 0, - 0, 1, 0, 0.6, 1, 0, - 0, 0, 1, 0, 0.6, 1 - ] ); + var k = Math.floor( j / 2 ); - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); + if ( j % 2 === 0 ) { - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); + make( + v[ i ][ k + 1 ], + v[ i + 1 ][ k ], + v[ i ][ k ] + ); - THREE.LineSegments.call( this, geometry, material ); + } else { -}; + make( + v[ i ][ k + 1 ], + v[ i + 1 ][ k + 1 ], + v[ i + 1 ][ k ] + ); -THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.AxisHelper.prototype.constructor = THREE.AxisHelper; + } -// File:src/extras/helpers/ArrowHelper.js + } -/** - * @author WestLangley / http://github.com/WestLangley - * @author zz85 / http://github.com/zz85 - * @author bhouston / http://clara.io - * - * Creates an arrow for visualizing directions - * - * Parameters: - * dir - Vector3 - * origin - Vector3 - * length - Number - * color - color in hex value - * headLength - Number - * headWidth - Number - */ + } -THREE.ArrowHelper = ( function () { + } - var lineGeometry = new THREE.BufferGeometry(); - lineGeometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); - var coneGeometry = new THREE.CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); - coneGeometry.translate( 0, - 0.5, 0 ); + // Angle around the Y axis, counter-clockwise when looking from above. - return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { + function azimuth( vector ) { - // dir is assumed to be normalized + return Math.atan2( vector.z, - vector.x ); - THREE.Object3D.call( this ); + } - if ( color === undefined ) color = 0xffff00; - if ( length === undefined ) length = 1; - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; - this.position.copy( origin ); + // Angle above the XZ plane. - this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) ); - this.line.matrixAutoUpdate = false; - this.add( this.line ); + function inclination( vector ) { - this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) ); - this.cone.matrixAutoUpdate = false; - this.add( this.cone ); + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); - this.setDirection( dir ); - this.setLength( length, headLength, headWidth ); + } - }; -}() ); + // Texture fixing helper. Spheres have some odd behaviours. -THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper; + function correctUV( uv, vector, azimuth ) { -THREE.ArrowHelper.prototype.setDirection = ( function () { + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new Vector2( uv.x - 1, uv.y ); + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new Vector2( azimuth / 2 / Math.PI + 0.5, uv.y ); + return uv.clone(); - var axis = new THREE.Vector3(); - var radians; + } - return function setDirection( dir ) { - // dir is assumed to be normalized + }; - if ( dir.y > 0.99999 ) { + PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); + PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; - this.quaternion.set( 0, 0, 0, 1 ); + /** + * @author timothypratley / https://github.com/timothypratley + */ - } else if ( dir.y < - 0.99999 ) { + function TetrahedronGeometry ( radius, detail ) { + this.isTetrahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; - this.quaternion.set( 1, 0, 0, 0 ); + var vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; - } else { + var indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; - axis.set( dir.z, 0, - dir.x ).normalize(); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - radians = Math.acos( dir.y ); + this.type = 'TetrahedronGeometry'; - this.quaternion.setFromAxisAngle( axis, radians ); + this.parameters = { + radius: radius, + detail: detail + }; - } + }; - }; + TetrahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; -}() ); + /** + * @author timothypratley / https://github.com/timothypratley + */ -THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { + function OctahedronGeometry ( radius, detail ) { + this.isOctahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; + var vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1 + ]; - this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 ); - this.line.updateMatrix(); + var indices = [ + 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 + ]; - this.cone.scale.set( headWidth, headLength, headWidth ); - this.cone.position.y = length; - this.cone.updateMatrix(); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); -}; + this.type = 'OctahedronGeometry'; -THREE.ArrowHelper.prototype.setColor = function ( color ) { + this.parameters = { + radius: radius, + detail: detail + }; - this.line.material.color.copy( color ); - this.cone.material.color.copy( color ); + }; -}; + OctahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + OctahedronGeometry.prototype.constructor = OctahedronGeometry; -// File:src/extras/helpers/BoxHelper.js + /** + * @author timothypratley / https://github.com/timothypratley + */ -/** - * @author mrdoob / http://mrdoob.com/ - */ + function IcosahedronGeometry ( radius, detail ) { + this.isIcosahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; -THREE.BoxHelper = function ( object, color ) { + var t = ( 1 + Math.sqrt( 5 ) ) / 2; - if ( color === undefined ) color = 0xffff00; + var vertices = [ + - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, + 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, + t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 + ]; - var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); - var positions = new Float32Array( 8 * 3 ); + var indices = [ + 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, + 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, + 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, + 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 + ]; - var geometry = new THREE.BufferGeometry(); - geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ) ); + this.type = 'IcosahedronGeometry'; - if ( object !== undefined ) { + this.parameters = { + radius: radius, + detail: detail + }; - this.update( object ); + }; - } + IcosahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; -}; + /** + * @author Abe Pazos / https://hamoid.com + */ -THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.BoxHelper.prototype.constructor = THREE.BoxHelper; + function DodecahedronGeometry ( radius, detail ) { + this.isDodecahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; -THREE.BoxHelper.prototype.update = ( function () { + var t = ( 1 + Math.sqrt( 5 ) ) / 2; + var r = 1 / t; - var box = new THREE.Box3(); + var vertices = [ - return function update( object ) { + // (±1, ±1, ±1) + - 1, - 1, - 1, - 1, - 1, 1, + - 1, 1, - 1, - 1, 1, 1, + 1, - 1, - 1, 1, - 1, 1, + 1, 1, - 1, 1, 1, 1, - if ( object instanceof THREE.Box3 ) { + // (0, ±1/φ, ±φ) + 0, - r, - t, 0, - r, t, + 0, r, - t, 0, r, t, - box.copy( object ); + // (±1/φ, ±φ, 0) + - r, - t, 0, - r, t, 0, + r, - t, 0, r, t, 0, - } else { + // (±φ, 0, ±1/φ) + - t, 0, - r, t, 0, - r, + - t, 0, r, t, 0, r + ]; - box.setFromObject( object ); + var indices = [ + 3, 11, 7, 3, 7, 15, 3, 15, 13, + 7, 19, 17, 7, 17, 6, 7, 6, 15, + 17, 4, 8, 17, 8, 10, 17, 10, 6, + 8, 0, 16, 8, 16, 2, 8, 2, 10, + 0, 12, 1, 0, 1, 18, 0, 18, 16, + 6, 10, 2, 6, 2, 13, 6, 13, 15, + 2, 16, 18, 2, 18, 3, 2, 3, 13, + 18, 1, 9, 18, 9, 11, 18, 11, 3, + 4, 14, 12, 4, 12, 0, 4, 0, 8, + 11, 9, 5, 11, 5, 19, 11, 19, 7, + 19, 5, 14, 19, 14, 4, 19, 4, 17, + 1, 12, 14, 1, 14, 5, 1, 5, 9 + ]; - } + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - if ( box.isEmpty() ) return; + this.type = 'DodecahedronGeometry'; - var min = box.min; - var max = box.max; + this.parameters = { + radius: radius, + detail: detail + }; - /* - 5____4 - 1/___0/| - | 6__|_7 - 2/___3/ + }; - 0: max.x, max.y, max.z - 1: min.x, max.y, max.z - 2: min.x, min.y, max.z - 3: max.x, min.y, max.z - 4: max.x, max.y, min.z - 5: min.x, max.y, min.z - 6: min.x, min.y, min.z - 7: max.x, min.y, min.z - */ + DodecahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; - var position = this.geometry.attributes.position; - var array = position.array; + /** + * @author Mugen87 / https://github.com/Mugen87 + * + * see: http://www.blackpawn.com/texts/pqtorus/ + */ + function TorusKnotBufferGeometry ( radius, tube, tubularSegments, radialSegments, p, q ) { + this.isTorusKnotBufferGeometry = this.isBufferGeometry = true; - array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; - array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; - array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; - array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; - array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; - array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; - array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; - array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z; + BufferGeometry.call( this ); - position.needsUpdate = true; + this.type = 'TorusKnotBufferGeometry'; - this.geometry.computeBoundingSphere(); + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - }; + radius = radius || 100; + tube = tube || 40; + tubularSegments = Math.floor( tubularSegments ) || 64; + radialSegments = Math.floor( radialSegments ) || 8; + p = p || 2; + q = q || 3; -} )(); + // used to calculate buffer length + var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); + var indexCount = radialSegments * tubularSegments * 2 * 3; -// File:src/extras/helpers/BoundingBoxHelper.js + // buffers + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); -/** - * @author WestLangley / http://github.com/WestLangley - */ + // helper variables + var i, j, index = 0, indexOffset = 0; -// a helper to show the world-axis-aligned bounding box for an object + var vertex = new Vector3(); + var normal = new Vector3(); + var uv = new Vector2(); -THREE.BoundingBoxHelper = function ( object, hex ) { + var P1 = new Vector3(); + var P2 = new Vector3(); - var color = ( hex !== undefined ) ? hex : 0x888888; + var B = new Vector3(); + var T = new Vector3(); + var N = new Vector3(); - this.object = object; + // generate vertices, normals and uvs - this.box = new THREE.Box3(); + for ( i = 0; i <= tubularSegments; ++ i ) { - THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) ); + // the radian "u" is used to calculate the position on the torus curve of the current tubular segement -}; + var u = i / tubularSegments * p * Math.PI * 2; -THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype ); -THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper; + // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. + // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions -THREE.BoundingBoxHelper.prototype.update = function () { + calculatePositionOnCurve( u, p, q, radius, P1 ); + calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); - this.box.setFromObject( this.object ); + // calculate orthonormal basis - this.box.size( this.scale ); + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); - this.box.center( this.position ); + // normalize B, N. T can be ignored, we don't use it -}; + B.normalize(); + N.normalize(); -// File:src/extras/helpers/CameraHelper.js + for ( j = 0; j <= radialSegments; ++ j ) { -/** - * @author alteredq / http://alteredqualia.com/ - * - * - shows frustum, line of sight and up of the camera - * - suitable for fast updates - * - based on frustum visualization in lightgl.js shadowmap example - * http://evanw.github.com/lightgl.js/tests/shadowmap.html - */ + // now calculate the vertices. they are nothing more than an extrusion of the torus curve. + // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. -THREE.CameraHelper = function ( camera ) { + var v = j / radialSegments * Math.PI * 2; + var cx = - tube * Math.cos( v ); + var cy = tube * Math.sin( v ); - var geometry = new THREE.Geometry(); - var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } ); + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve - var pointMap = {}; + vertex.x = P1.x + ( cx * N.x + cy * B.x ); + vertex.y = P1.y + ( cx * N.y + cy * B.y ); + vertex.z = P1.z + ( cx * N.z + cy * B.z ); - // colors + // vertex + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - var hexFrustum = 0xffaa00; - var hexCone = 0xff0000; - var hexUp = 0x00aaff; - var hexTarget = 0xffffff; - var hexCross = 0x333333; + // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) + normal.subVectors( vertex, P1 ).normalize(); + normals.setXYZ( index, normal.x, normal.y, normal.z ); - // near + // uv + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + uvs.setXY( index, uv.x, uv.y ); - addLine( "n1", "n2", hexFrustum ); - addLine( "n2", "n4", hexFrustum ); - addLine( "n4", "n3", hexFrustum ); - addLine( "n3", "n1", hexFrustum ); + // increase index + index ++; - // far + } - addLine( "f1", "f2", hexFrustum ); - addLine( "f2", "f4", hexFrustum ); - addLine( "f4", "f3", hexFrustum ); - addLine( "f3", "f1", hexFrustum ); + } - // sides + // generate indices - addLine( "n1", "f1", hexFrustum ); - addLine( "n2", "f2", hexFrustum ); - addLine( "n3", "f3", hexFrustum ); - addLine( "n4", "f4", hexFrustum ); + for ( j = 1; j <= tubularSegments; j ++ ) { - // cone + for ( i = 1; i <= radialSegments; i ++ ) { - addLine( "p", "n1", hexCone ); - addLine( "p", "n2", hexCone ); - addLine( "p", "n3", hexCone ); - addLine( "p", "n4", hexCone ); + // indices + var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + var b = ( radialSegments + 1 ) * j + ( i - 1 ); + var c = ( radialSegments + 1 ) * j + i; + var d = ( radialSegments + 1 ) * ( j - 1 ) + i; - // up + // face one + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - addLine( "u1", "u2", hexUp ); - addLine( "u2", "u3", hexUp ); - addLine( "u3", "u1", hexUp ); + // face two + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - // target + } - addLine( "c", "t", hexTarget ); - addLine( "p", "c", hexCross ); + } - // cross + // build geometry - addLine( "cn1", "cn2", hexCross ); - addLine( "cn3", "cn4", hexCross ); + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - addLine( "cf1", "cf2", hexCross ); - addLine( "cf3", "cf4", hexCross ); + // this function calculates the current position on the torus curve - function addLine( a, b, hex ) { + function calculatePositionOnCurve( u, p, q, radius, position ) { - addPoint( a, hex ); - addPoint( b, hex ); + var cu = Math.cos( u ); + var su = Math.sin( u ); + var quOverP = q / p * u; + var cs = Math.cos( quOverP ); - } + position.x = radius * ( 2 + cs ) * 0.5 * cu; + position.y = radius * ( 2 + cs ) * su * 0.5; + position.z = radius * Math.sin( quOverP ) * 0.5; - function addPoint( id, hex ) { + } - geometry.vertices.push( new THREE.Vector3() ); - geometry.colors.push( new THREE.Color( hex ) ); + }; - if ( pointMap[ id ] === undefined ) { + TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; - pointMap[ id ] = []; + /** + * @author oosmoxiecode + */ - } + function TorusKnotGeometry ( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { + this.isTorusKnotGeometry = this.isGeometry = true; - pointMap[ id ].push( geometry.vertices.length - 1 ); + Geometry.call( this ); - } + this.type = 'TorusKnotGeometry'; - THREE.LineSegments.call( this, geometry, material ); + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - this.camera = camera; - if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); + if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); - this.matrix = camera.matrixWorld; - this.matrixAutoUpdate = false; + this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); + this.mergeVertices(); - this.pointMap = pointMap; + }; - this.update(); + TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); + TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; -}; + /** + * @author Mugen87 / https://github.com/Mugen87 + */ -THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.CameraHelper.prototype.constructor = THREE.CameraHelper; + function TorusBufferGeometry ( radius, tube, radialSegments, tubularSegments, arc ) { + this.isTorusBufferGeometry = this.isBufferGeometry = true; -THREE.CameraHelper.prototype.update = function () { + BufferGeometry.call( this ); - var geometry, pointMap; + this.type = 'TorusBufferGeometry'; - var vector = new THREE.Vector3(); - var camera = new THREE.Camera(); + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - function setPoint( point, x, y, z ) { + radius = radius || 100; + tube = tube || 40; + radialSegments = Math.floor( radialSegments ) || 8; + tubularSegments = Math.floor( tubularSegments ) || 6; + arc = arc || Math.PI * 2; - vector.set( x, y, z ).unproject( camera ); + // used to calculate buffer length + var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); + var indexCount = radialSegments * tubularSegments * 2 * 3; - var points = pointMap[ point ]; + // buffers + var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); + var vertices = new Float32Array( vertexCount * 3 ); + var normals = new Float32Array( vertexCount * 3 ); + var uvs = new Float32Array( vertexCount * 2 ); - if ( points !== undefined ) { + // offset variables + var vertexBufferOffset = 0; + var uvBufferOffset = 0; + var indexBufferOffset = 0; - for ( var i = 0, il = points.length; i < il; i ++ ) { + // helper variables + var center = new Vector3(); + var vertex = new Vector3(); + var normal = new Vector3(); - geometry.vertices[ points[ i ] ].copy( vector ); + var j, i; - } + // generate vertices, normals and uvs - } + for ( j = 0; j <= radialSegments; j ++ ) { - } + for ( i = 0; i <= tubularSegments; i ++ ) { - return function update() { + var u = i / tubularSegments * arc; + var v = j / radialSegments * Math.PI * 2; - geometry = this.geometry; - pointMap = this.pointMap; + // vertex + vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); + vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); + vertex.z = tube * Math.sin( v ); - var w = 1, h = 1; + vertices[ vertexBufferOffset ] = vertex.x; + vertices[ vertexBufferOffset + 1 ] = vertex.y; + vertices[ vertexBufferOffset + 2 ] = vertex.z; - // we need just camera projection matrix - // world matrix must be identity + // this vector is used to calculate the normal + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); - camera.projectionMatrix.copy( this.camera.projectionMatrix ); + // normal + normal.subVectors( vertex, center ).normalize(); - // center / target + normals[ vertexBufferOffset ] = normal.x; + normals[ vertexBufferOffset + 1 ] = normal.y; + normals[ vertexBufferOffset + 2 ] = normal.z; - setPoint( "c", 0, 0, - 1 ); - setPoint( "t", 0, 0, 1 ); + // uv + uvs[ uvBufferOffset ] = i / tubularSegments; + uvs[ uvBufferOffset + 1 ] = j / radialSegments; - // near + // update offsets + vertexBufferOffset += 3; + uvBufferOffset += 2; - setPoint( "n1", - w, - h, - 1 ); - setPoint( "n2", w, - h, - 1 ); - setPoint( "n3", - w, h, - 1 ); - setPoint( "n4", w, h, - 1 ); + } - // far + } - setPoint( "f1", - w, - h, 1 ); - setPoint( "f2", w, - h, 1 ); - setPoint( "f3", - w, h, 1 ); - setPoint( "f4", w, h, 1 ); + // generate indices - // up + for ( j = 1; j <= radialSegments; j ++ ) { - setPoint( "u1", w * 0.7, h * 1.1, - 1 ); - setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); - setPoint( "u3", 0, h * 2, - 1 ); + for ( i = 1; i <= tubularSegments; i ++ ) { - // cross + // indices + var a = ( tubularSegments + 1 ) * j + i - 1; + var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + var d = ( tubularSegments + 1 ) * j + i; - setPoint( "cf1", - w, 0, 1 ); - setPoint( "cf2", w, 0, 1 ); - setPoint( "cf3", 0, - h, 1 ); - setPoint( "cf4", 0, h, 1 ); + // face one + indices[ indexBufferOffset ] = a; + indices[ indexBufferOffset + 1 ] = b; + indices[ indexBufferOffset + 2 ] = d; - setPoint( "cn1", - w, 0, - 1 ); - setPoint( "cn2", w, 0, - 1 ); - setPoint( "cn3", 0, - h, - 1 ); - setPoint( "cn4", 0, h, - 1 ); + // face two + indices[ indexBufferOffset + 3 ] = b; + indices[ indexBufferOffset + 4 ] = c; + indices[ indexBufferOffset + 5 ] = d; - geometry.verticesNeedUpdate = true; + // update offset + indexBufferOffset += 6; - }; + } -}(); + } -// File:src/extras/helpers/DirectionalLightHelper.js + // build geometry + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + }; -THREE.DirectionalLightHelper = function ( light, size ) { + TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; - THREE.Object3D.call( this ); + /** + * @author oosmoxiecode + * @author mrdoob / http://mrdoob.com/ + * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888 + */ - this.light = light; - this.light.updateMatrixWorld(); + function TorusGeometry ( radius, tube, radialSegments, tubularSegments, arc ) { + this.isTorusGeometry = this.isGeometry = true; - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + Geometry.call( this ); - if ( size === undefined ) size = 1; + this.type = 'TorusGeometry'; - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( [ - - size, size, 0, - size, size, 0, - size, - size, 0, - - size, - size, 0, - - size, size, 0 - ], 3 ) ); + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - var material = new THREE.LineBasicMaterial( { fog: false } ); + this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); - this.add( new THREE.Line( geometry, material ) ); + }; - geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + TorusGeometry.prototype = Object.create( Geometry.prototype ); + TorusGeometry.prototype.constructor = TorusGeometry; - this.add( new THREE.Line( geometry, material )); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author alteredq / http://alteredqualia.com/ + * + * Text = 3D Text + * + * parameters = { + * font: , // font + * + * size: , // size of the text + * height: , // thickness to extrude text + * curveSegments: , // number of points on the curves + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into text bevel goes + * bevelSize: // how far from text outline is bevel + * } + */ - this.update(); + function TextGeometry ( text, parameters ) { + this.isTextGeometry = this.isExtrudeGeometry = this.isGeometry = true; -}; + parameters = parameters || {}; -THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper; + var font = parameters.font; -THREE.DirectionalLightHelper.prototype.dispose = function () { + if ( (font && font.isFont) === false ) { - var lightPlane = this.children[ 0 ]; - var targetLine = this.children[ 1 ]; + console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); + return new Geometry(); - lightPlane.geometry.dispose(); - lightPlane.material.dispose(); - targetLine.geometry.dispose(); - targetLine.material.dispose(); + } -}; + var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments ); -THREE.DirectionalLightHelper.prototype.update = function () { + // translate parameters to ExtrudeGeometry API - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var v3 = new THREE.Vector3(); + parameters.amount = parameters.height !== undefined ? parameters.height : 50; - return function update() { + // defaults - v1.setFromMatrixPosition( this.light.matrixWorld ); - v2.setFromMatrixPosition( this.light.target.matrixWorld ); - v3.subVectors( v2, v1 ); + if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; + if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; + if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; - var lightPlane = this.children[ 0 ]; - var targetLine = this.children[ 1 ]; + ExtrudeGeometry.call( this, shapes, parameters ); - lightPlane.lookAt( v3 ); - lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + this.type = 'TextGeometry'; - targetLine.lookAt( v3 ); - targetLine.scale.z = v3.length(); + }; - }; + TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype ); + TextGeometry.prototype.constructor = TextGeometry; -}(); + /** + * @author Mugen87 / https://github.com/Mugen87 + */ -// File:src/extras/helpers/EdgesHelper.js + function RingBufferGeometry ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + this.isRingBufferGeometry = this.isBufferGeometry = true; -/** - * @author WestLangley / http://github.com/WestLangley - * @param object THREE.Mesh whose geometry will be used - * @param hex line color - * @param thresholdAngle the minimum angle (in degrees), - * between the face normals of adjacent faces, - * that is required to render an edge. A value of 10 means - * an edge is only rendered if the angle is at least 10 degrees. - */ + BufferGeometry.call( this ); -THREE.EdgesHelper = function ( object, hex, thresholdAngle ) { + this.type = 'RingBufferGeometry'; - var color = ( hex !== undefined ) ? hex : 0xffffff; + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) ); + innerRadius = innerRadius || 20; + outerRadius = outerRadius || 50; - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; -}; + thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; + phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; -THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper; + // these are used to calculate buffer length + var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 ); + var indexCount = thetaSegments * phiSegments * 2 * 3; -// File:src/extras/helpers/FaceNormalsHelper.js + // buffers + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ + // some helper variables + var index = 0, indexOffset = 0, segment; + var radius = innerRadius; + var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + var vertex = new Vector3(); + var uv = new Vector2(); + var j, i; -THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { + // generate vertices, normals and uvs - // FaceNormalsHelper only supports THREE.Geometry + // values are generate from the inside of the ring to the outside - this.object = object; + for ( j = 0; j <= phiSegments; j ++ ) { - this.size = ( size !== undefined ) ? size : 1; + for ( i = 0; i <= thetaSegments; i ++ ) { - var color = ( hex !== undefined ) ? hex : 0xffff00; + segment = thetaStart + i / thetaSegments * thetaLength; - var width = ( linewidth !== undefined ) ? linewidth : 1; + // vertex + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - // + // normal + normals.setXYZ( index, 0, 0, 1 ); - var nNormals = 0; + // uv + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; + uvs.setXY( index, uv.x, uv.y ); - var objGeometry = this.object.geometry; + // increase index + index++; - if ( objGeometry instanceof THREE.Geometry ) { + } - nNormals = objGeometry.faces.length; + // increase the radius for next row of vertices + radius += radiusStep; - } else { + } - console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' ); + // generate indices - } + for ( j = 0; j < phiSegments; j ++ ) { - // + var thetaSegmentLevel = j * ( thetaSegments + 1 ); - var geometry = new THREE.BufferGeometry(); + for ( i = 0; i < thetaSegments; i ++ ) { - var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 ); + segment = i + thetaSegmentLevel; - geometry.addAttribute( 'position', positions ); + // indices + var a = segment; + var b = segment + thetaSegments + 1; + var c = segment + thetaSegments + 2; + var d = segment + 1; - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) ); + // face one + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; - // + // face two + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - this.matrixAutoUpdate = false; - this.update(); + } -}; + } -THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper; + // build geometry -THREE.FaceNormalsHelper.prototype.update = ( function () { + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var normalMatrix = new THREE.Matrix3(); + }; - return function update() { + RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + RingBufferGeometry.prototype.constructor = RingBufferGeometry; - this.object.updateMatrixWorld( true ); + /** + * @author Kaleb Murphy + */ - normalMatrix.getNormalMatrix( this.object.matrixWorld ); + function RingGeometry ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + this.isRingGeometry = this.isGeometry = true; - var matrixWorld = this.object.matrixWorld; + Geometry.call( this ); - var position = this.geometry.attributes.position; + this.type = 'RingGeometry'; - // + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - var objGeometry = this.object.geometry; + this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); - var vertices = objGeometry.vertices; + }; - var faces = objGeometry.faces; + RingGeometry.prototype = Object.create( Geometry.prototype ); + RingGeometry.prototype.constructor = RingGeometry; - var idx = 0; + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as + */ - for ( var i = 0, l = faces.length; i < l; i ++ ) { + function PlaneGeometry ( width, height, widthSegments, heightSegments ) { + this.isPlaneGeometry = this.isGeometry = true; - var face = faces[ i ]; + Geometry.call( this ); - var normal = face.normal; + this.type = 'PlaneGeometry'; - v1.copy( vertices[ face.a ] ) - .add( vertices[ face.b ] ) - .add( vertices[ face.c ] ) - .divideScalar( 3 ) - .applyMatrix4( matrixWorld ); + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); - position.setXYZ( idx, v1.x, v1.y, v1.z ); + }; - idx = idx + 1; + PlaneGeometry.prototype = Object.create( Geometry.prototype ); + PlaneGeometry.prototype.constructor = PlaneGeometry; - position.setXYZ( idx, v2.x, v2.y, v2.z ); + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - idx = idx + 1; + // points - to create a closed torus, one must use a set of points + // like so: [ a, b, c, d, a ], see first is the same as last. + // segments - the number of circumference segments to create + // phiStart - the starting radian + // phiLength - the radian (0 to 2PI) range of the lathed section + // 2PI is a closed lathe, less than 2PI is a portion. - } + function LatheBufferGeometry ( points, segments, phiStart, phiLength ) { + this.isLatheBufferGeometry = this.isBufferGeometry = true; - position.needsUpdate = true; + BufferGeometry.call( this ); - return this; + this.type = 'LatheBufferGeometry'; - }; + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; -}() ); + segments = Math.floor( segments ) || 12; + phiStart = phiStart || 0; + phiLength = phiLength || Math.PI * 2; -// File:src/extras/helpers/GridHelper.js + // clamp phiLength so it's in range of [ 0, 2PI ] + phiLength = exports.Math.clamp( phiLength, 0, Math.PI * 2 ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + // these are used to calculate buffer length + var vertexCount = ( segments + 1 ) * points.length; + var indexCount = segments * points.length * 2 * 3; -THREE.GridHelper = function ( size, divisions, color1, color2 ) { + // buffers + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - divisions = divisions || 1; - color1 = new THREE.Color( color1 !== undefined ? color1 : 0x444444 ); - color2 = new THREE.Color( color2 !== undefined ? color2 : 0x888888 ); + // helper variables + var index = 0, indexOffset = 0, base; + var inversePointLength = 1.0 / ( points.length - 1 ); + var inverseSegments = 1.0 / segments; + var vertex = new Vector3(); + var uv = new Vector2(); + var i, j; - var center = divisions / 2; - var step = ( size * 2 ) / divisions; - var vertices = [], colors = []; + // generate vertices and uvs - for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) { + for ( i = 0; i <= segments; i ++ ) { - vertices.push( - size, 0, k, size, 0, k ); - vertices.push( k, 0, - size, k, 0, size ); + var phi = phiStart + i * inverseSegments * phiLength; - var color = i === center ? color1 : color2; + var sin = Math.sin( phi ); + var cos = Math.cos( phi ); - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; + for ( j = 0; j <= ( points.length - 1 ); j ++ ) { - } + // vertex + vertex.x = points[ j ].x * sin; + vertex.y = points[ j ].y; + vertex.z = points[ j ].x * cos; + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new THREE.Float32Attribute( colors, 3 ) ); + // uv + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); + uvs.setXY( index, uv.x, uv.y ); - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); + // increase index + index ++; - THREE.LineSegments.call( this, geometry, material ); + } -}; + } -THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.GridHelper.prototype.constructor = THREE.GridHelper; + // generate indices -THREE.GridHelper.prototype.setColors = function () { + for ( i = 0; i < segments; i ++ ) { - console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); + for ( j = 0; j < ( points.length - 1 ); j ++ ) { -}; + base = j + i * points.length; -// File:src/extras/helpers/HemisphereLightHelper.js + // indices + var a = base; + var b = base + points.length; + var c = base + points.length + 1; + var d = base + 1; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + // face one + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; -THREE.HemisphereLightHelper = function ( light, sphereSize ) { + // face two + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - THREE.Object3D.call( this ); + } - this.light = light; - this.light.updateMatrixWorld(); + } - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + // build geometry - this.colors = [ new THREE.Color(), new THREE.Color() ]; + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'uv', uvs ); - var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 ); - geometry.rotateX( - Math.PI / 2 ); + // generate normals - for ( var i = 0, il = 8; i < il; i ++ ) { + this.computeVertexNormals(); - geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; + // if the geometry is closed, we need to average the normals along the seam. + // because the corresponding vertices are identical (but still have different UVs). - } + if( phiLength === Math.PI * 2 ) { - var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } ); + var normals = this.attributes.normal.array; + var n1 = new Vector3(); + var n2 = new Vector3(); + var n = new Vector3(); - this.lightSphere = new THREE.Mesh( geometry, material ); - this.add( this.lightSphere ); + // this is the buffer offset for the last line of vertices + base = segments * points.length * 3; - this.update(); + for( i = 0, j = 0; i < points.length; i ++, j += 3 ) { -}; + // select the normal of the vertex in the first line + n1.x = normals[ j + 0 ]; + n1.y = normals[ j + 1 ]; + n1.z = normals[ j + 2 ]; -THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper; + // select the normal of the vertex in the last line + n2.x = normals[ base + j + 0 ]; + n2.y = normals[ base + j + 1 ]; + n2.z = normals[ base + j + 2 ]; -THREE.HemisphereLightHelper.prototype.dispose = function () { + // average normals + n.addVectors( n1, n2 ).normalize(); - this.lightSphere.geometry.dispose(); - this.lightSphere.material.dispose(); + // assign the new values to both normals + normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; + normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; + normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; -}; + } // next row -THREE.HemisphereLightHelper.prototype.update = function () { + } - var vector = new THREE.Vector3(); + }; - return function update() { + LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; - this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); - this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); + /** + * @author astrodud / http://astrodud.isgreat.org/ + * @author zz85 / https://github.com/zz85 + * @author bhouston / http://clara.io + */ - this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); - this.lightSphere.geometry.colorsNeedUpdate = true; + // points - to create a closed torus, one must use a set of points + // like so: [ a, b, c, d, a ], see first is the same as last. + // segments - the number of circumference segments to create + // phiStart - the starting radian + // phiLength - the radian (0 to 2PI) range of the lathed section + // 2PI is a closed lathe, less than 2PI is a portion. - }; + function LatheGeometry ( points, segments, phiStart, phiLength ) { + this.isLatheGeometry = this.isGeometry = true; -}(); + Geometry.call( this ); -// File:src/extras/helpers/PointLightHelper.js + this.type = 'LatheGeometry'; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; -THREE.PointLightHelper = function ( light, sphereSize ) { + this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); + this.mergeVertices(); - this.light = light; - this.light.updateMatrixWorld(); + }; - var geometry = new THREE.SphereBufferGeometry( sphereSize, 4, 2 ); - var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); - material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + LatheGeometry.prototype = Object.create( Geometry.prototype ); + LatheGeometry.prototype.constructor = LatheGeometry; - THREE.Mesh.call( this, geometry, material ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.matrix = this.light.matrixWorld; - this.matrixAutoUpdate = false; + function CylinderGeometry ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isCylinderGeometry = this.isGeometry = true; - /* - var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); - var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); + Geometry.call( this ); - this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); - this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); + this.type = 'CylinderGeometry'; - var d = light.distance; + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - if ( d === 0.0 ) { + this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); + this.mergeVertices(); - this.lightDistance.visible = false; + }; - } else { + CylinderGeometry.prototype = Object.create( Geometry.prototype ); + CylinderGeometry.prototype.constructor = CylinderGeometry; - this.lightDistance.scale.set( d, d, d ); + /** + * @author abelnation / http://github.com/abelnation + */ - } + function ConeGeometry ( + radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ) { + this.isConeGeometry = this.isCylinderGeometry = this.isGeometry = true; - this.add( this.lightDistance ); - */ + CylinderGeometry.call( this, + 0, radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ); -}; + this.type = 'ConeGeometry'; -THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype ); -THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper; + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; -THREE.PointLightHelper.prototype.dispose = function () { + }; - this.geometry.dispose(); - this.material.dispose(); + ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); + ConeGeometry.prototype.constructor = ConeGeometry; -}; + /* + * @author: abelnation / http://github.com/abelnation + */ -THREE.PointLightHelper.prototype.update = function () { + function ConeBufferGeometry ( + radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ) { + this.isConeBufferGeometry = this.isBufferGeometry = true; - this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + CylinderBufferGeometry.call( this, + 0, radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ); - /* - var d = this.light.distance; + this.type = 'ConeBufferGeometry'; - if ( d === 0.0 ) { + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - this.lightDistance.visible = false; + }; - } else { + ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; - this.lightDistance.visible = true; - this.lightDistance.scale.set( d, d, d ); + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - } - */ + function CircleBufferGeometry ( radius, segments, thetaStart, thetaLength ) { + this.isCircleBufferGeometry = this.isBufferGeometry = true; -}; + BufferGeometry.call( this ); -// File:src/extras/helpers/SkeletonHelper.js + this.type = 'CircleBufferGeometry'; -/** - * @author Sean Griffin / http://twitter.com/sgrif - * @author Michael Guerrero / http://realitymeltdown.com - * @author mrdoob / http://mrdoob.com/ - * @author ikerr / http://verold.com - */ + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; -THREE.SkeletonHelper = function ( object ) { + radius = radius || 50; + segments = segments !== undefined ? Math.max( 3, segments ) : 8; - this.bones = this.getBoneList( object ); + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - var geometry = new THREE.Geometry(); + var vertices = segments + 2; - for ( var i = 0; i < this.bones.length; i ++ ) { + var positions = new Float32Array( vertices * 3 ); + var normals = new Float32Array( vertices * 3 ); + var uvs = new Float32Array( vertices * 2 ); - var bone = this.bones[ i ]; + // center data is already zero, but need to set a few extras + normals[ 2 ] = 1.0; + uvs[ 0 ] = 0.5; + uvs[ 1 ] = 0.5; - if ( bone.parent instanceof THREE.Bone ) { + for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) { - geometry.vertices.push( new THREE.Vector3() ); - geometry.vertices.push( new THREE.Vector3() ); - geometry.colors.push( new THREE.Color( 0, 0, 1 ) ); - geometry.colors.push( new THREE.Color( 0, 1, 0 ) ); + var segment = thetaStart + s / segments * thetaLength; - } + positions[ i ] = radius * Math.cos( segment ); + positions[ i + 1 ] = radius * Math.sin( segment ); - } + normals[ i + 2 ] = 1; // normal z - geometry.dynamic = true; + uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2; + uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2; - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } ); + } - THREE.LineSegments.call( this, geometry, material ); + var indices = []; - this.root = object; + for ( var i = 1; i <= segments; i ++ ) { - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + indices.push( i, i + 1, 0 ); - this.update(); + } -}; + this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); + this.boundingSphere = new Sphere( new Vector3(), radius ); -THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper; + }; -THREE.SkeletonHelper.prototype.getBoneList = function( object ) { + CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; - var boneList = []; + /** + * @author hughes + */ - if ( object instanceof THREE.Bone ) { + function CircleGeometry ( radius, segments, thetaStart, thetaLength ) { + this.isCircleGeometry = this.isGeometry = true; - boneList.push( object ); + Geometry.call( this ); - } + this.type = 'CircleGeometry'; - for ( var i = 0; i < object.children.length; i ++ ) { + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); + this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); - } + }; - return boneList; + CircleGeometry.prototype = Object.create( Geometry.prototype ); + CircleGeometry.prototype.constructor = CircleGeometry; -}; + /** + * @author zz85 https://github.com/zz85 + * + * Centripetal CatmullRom Curve - which is useful for avoiding + * cusps and self-intersections in non-uniform catmull rom curves. + * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf + * + * curve.type accepts centripetal(default), chordal and catmullrom + * curve.tension is used for catmullrom which defaults to 0.5 + */ -THREE.SkeletonHelper.prototype.update = function () { + exports.CatmullRomCurve3 = ( function() { - var geometry = this.geometry; + var + tmp = new Vector3(), + px = new CubicPoly(), + py = new CubicPoly(), + pz = new CubicPoly(); - var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld ); + /* + Based on an optimized c++ solution in + - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ + - http://ideone.com/NoEbVM - var boneMatrix = new THREE.Matrix4(); + This CubicPoly class could be used for reusing some variables and calculations, + but for three.js curve use, it could be possible inlined and flatten into a single function call + which can be placed in CurveUtils. + */ - var j = 0; + function CubicPoly() { - for ( var i = 0; i < this.bones.length; i ++ ) { + } - var bone = this.bones[ i ]; + /* + * Compute coefficients for a cubic polynomial + * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 + * such that + * p(0) = x0, p(1) = x1 + * and + * p'(0) = t0, p'(1) = t1. + */ + CubicPoly.prototype.init = function( x0, x1, t0, t1 ) { - if ( bone.parent instanceof THREE.Bone ) { + this.c0 = x0; + this.c1 = t0; + this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + this.c3 = 2 * x0 - 2 * x1 + t0 + t1; - boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); - geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); + }; - boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); - geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); + CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) { - j += 2; + // compute tangents when parameterized in [t1,t2] + var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; - } + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; - } + // initCubicPoly + this.init( x1, x2, t1, t2 ); - geometry.verticesNeedUpdate = true; + }; - geometry.computeBoundingSphere(); + // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4 + CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) { -}; + this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); -// File:src/extras/helpers/SpotLightHelper.js + }; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ + CubicPoly.prototype.calc = function( t ) { -THREE.SpotLightHelper = function ( light ) { + var t2 = t * t; + var t3 = t2 * t; + return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3; - THREE.Object3D.call( this ); + }; - this.light = light; - this.light.updateMatrixWorld(); + // Subclass Three.js curve + return Curve.create( - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + function ( p /* array of Vector3 */ ) { - var geometry = new THREE.BufferGeometry(); + this.points = p || []; + this.closed = false; - var positions = [ - 0, 0, 0, 0, 0, 1, - 0, 0, 0, 1, 0, 1, - 0, 0, 0, - 1, 0, 1, - 0, 0, 0, 0, 1, 1, - 0, 0, 0, 0, - 1, 1 - ]; + }, - for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + function ( t ) { - var p1 = ( i / l ) * Math.PI * 2; - var p2 = ( j / l ) * Math.PI * 2; + var points = this.points, + point, intPoint, weight, l; - positions.push( - Math.cos( p1 ), Math.sin( p1 ), 1, - Math.cos( p2 ), Math.sin( p2 ), 1 - ); + l = points.length; - } + if ( l < 2 ) console.log( 'duh, you need at least 2 points' ); - geometry.addAttribute( 'position', new THREE.Float32Attribute( positions, 3 ) ); + point = ( l - ( this.closed ? 0 : 1 ) ) * t; + intPoint = Math.floor( point ); + weight = point - intPoint; - var material = new THREE.LineBasicMaterial( { fog: false } ); + if ( this.closed ) { - this.cone = new THREE.LineSegments( geometry, material ); - this.add( this.cone ); + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; - this.update(); + } else if ( weight === 0 && intPoint === l - 1 ) { -}; + intPoint = l - 2; + weight = 1; -THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper; + } -THREE.SpotLightHelper.prototype.dispose = function () { + var p0, p1, p2, p3; // 4 points - this.cone.geometry.dispose(); - this.cone.material.dispose(); + if ( this.closed || intPoint > 0 ) { -}; + p0 = points[ ( intPoint - 1 ) % l ]; -THREE.SpotLightHelper.prototype.update = function () { + } else { - var vector = new THREE.Vector3(); - var vector2 = new THREE.Vector3(); + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; - return function update() { + } - var coneLength = this.light.distance ? this.light.distance : 1000; - var coneWidth = coneLength * Math.tan( this.light.angle ); + p1 = points[ intPoint % l ]; + p2 = points[ ( intPoint + 1 ) % l ]; - this.cone.scale.set( coneWidth, coneWidth, coneLength ); + if ( this.closed || intPoint + 2 < l ) { - vector.setFromMatrixPosition( this.light.matrixWorld ); - vector2.setFromMatrixPosition( this.light.target.matrixWorld ); + p3 = points[ ( intPoint + 2 ) % l ]; - this.cone.lookAt( vector2.sub( vector ) ); + } else { - this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; - }; + } -}(); + if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) { -// File:src/extras/helpers/VertexNormalsHelper.js + // init Centripetal / Chordal Catmull-Rom + var pow = this.type === 'chordal' ? 0.5 : 0.25; + var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; -THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { + px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); + py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); + pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); - this.object = object; + } else if ( this.type === 'catmullrom' ) { - this.size = ( size !== undefined ) ? size : 1; + var tension = this.tension !== undefined ? this.tension : 0.5; + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension ); - var color = ( hex !== undefined ) ? hex : 0xff0000; + } - var width = ( linewidth !== undefined ) ? linewidth : 1; + var v = new Vector3( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); - // + return v; - var nNormals = 0; + } - var objGeometry = this.object.geometry; + ); - if ( objGeometry instanceof THREE.Geometry ) { + } )(); - nNormals = objGeometry.faces.length * 3; + /************************************************************** + * Closed Spline 3D curve + **************************************************************/ - } else if ( objGeometry instanceof THREE.BufferGeometry ) { - nNormals = objGeometry.attributes.normal.count; + function ClosedSplineCurve3 ( points ) { + this.isClosedSplineCurve3 = this.isCatmullRomCurve3 = true; - } + console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' ); - // + exports.CatmullRomCurve3.call( this, points ); + this.type = 'catmullrom'; + this.closed = true; - var geometry = new THREE.BufferGeometry(); + }; - var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 ); + ClosedSplineCurve3.prototype = Object.create( exports.CatmullRomCurve3.prototype ); - geometry.addAttribute( 'position', positions ); + /************************************************************** + * Spline 3D curve + **************************************************************/ - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) ); - // + exports.SplineCurve3 = Curve.create( - this.matrixAutoUpdate = false; + function ( points /* array of Vector3 */ ) { - this.update(); + console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' ); + this.points = ( points == undefined ) ? [] : points; -}; + }, -THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper; + function ( t ) { -THREE.VertexNormalsHelper.prototype.update = ( function () { + var points = this.points; + var point = ( points.length - 1 ) * t; - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var normalMatrix = new THREE.Matrix3(); + var intPoint = Math.floor( point ); + var weight = point - intPoint; - return function update() { + var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ]; + var point1 = points[ intPoint ]; + var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; - var keys = [ 'a', 'b', 'c' ]; + var interpolate = exports.CurveUtils.interpolate; - this.object.updateMatrixWorld( true ); + return new Vector3( + interpolate( point0.x, point1.x, point2.x, point3.x, weight ), + interpolate( point0.y, point1.y, point2.y, point3.y, weight ), + interpolate( point0.z, point1.z, point2.z, point3.z, weight ) + ); - normalMatrix.getNormalMatrix( this.object.matrixWorld ); + } - var matrixWorld = this.object.matrixWorld; + ); - var position = this.geometry.attributes.position; + /************************************************************** + * Cubic Bezier 3D curve + **************************************************************/ - // + exports.CubicBezierCurve3 = Curve.create( - var objGeometry = this.object.geometry; + function ( v0, v1, v2, v3 ) { - if ( objGeometry instanceof THREE.Geometry ) { + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - var vertices = objGeometry.vertices; + }, - var faces = objGeometry.faces; + function ( t ) { - var idx = 0; + var b3 = exports.ShapeUtils.b3; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + return new Vector3( + b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), + b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ), + b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ) + ); - var face = faces[ i ]; + } - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + ); - var vertex = vertices[ face[ keys[ j ] ] ]; + /************************************************************** + * Quadratic Bezier 3D curve + **************************************************************/ - var normal = face.vertexNormals[ j ]; + exports.QuadraticBezierCurve3 = Curve.create( - v1.copy( vertex ).applyMatrix4( matrixWorld ); + function ( v0, v1, v2 ) { - v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - position.setXYZ( idx, v1.x, v1.y, v1.z ); + }, - idx = idx + 1; + function ( t ) { - position.setXYZ( idx, v2.x, v2.y, v2.z ); + var b2 = exports.ShapeUtils.b2; - idx = idx + 1; + return new Vector3( + b2( t, this.v0.x, this.v1.x, this.v2.x ), + b2( t, this.v0.y, this.v1.y, this.v2.y ), + b2( t, this.v0.z, this.v1.z, this.v2.z ) + ); - } + } - } + ); - } else if ( objGeometry instanceof THREE.BufferGeometry ) { + /************************************************************** + * Line3D + **************************************************************/ - var objPos = objGeometry.attributes.position; + exports.LineCurve3 = Curve.create( - var objNorm = objGeometry.attributes.normal; + function ( v1, v2 ) { - var idx = 0; + this.v1 = v1; + this.v2 = v2; - // for simplicity, ignore index and drawcalls, and render every normal + }, - for ( var j = 0, jl = objPos.count; j < jl; j ++ ) { + function ( t ) { - v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld ); + if ( t === 1 ) { - v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) ); + return this.v2.clone(); - v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + } - position.setXYZ( idx, v1.x, v1.y, v1.z ); + var vector = new Vector3(); - idx = idx + 1; + vector.subVectors( this.v2, this.v1 ); // diff + vector.multiplyScalar( t ); + vector.add( this.v1 ); - position.setXYZ( idx, v2.x, v2.y, v2.z ); + return vector; - idx = idx + 1; + } - } + ); - } + /************************************************************** + * Arc curve + **************************************************************/ - position.needsUpdate = true; + function ArcCurve ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + this.isArcCurve = this.isEllipseCurve = this.isCurve = true; - return this; + EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - }; + }; -}() ); + ArcCurve.prototype = Object.create( EllipseCurve.prototype ); + ArcCurve.prototype.constructor = ArcCurve; -// File:src/extras/helpers/WireframeHelper.js + /** + * @author alteredq / http://alteredqualia.com/ + */ -/** - * @author mrdoob / http://mrdoob.com/ - */ + exports.SceneUtils = { -THREE.WireframeHelper = function ( object, hex ) { + createMultiMaterialObject: function ( geometry, materials ) { - var color = ( hex !== undefined ) ? hex : 0xffffff; + var group = new Group(); - THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) ); + for ( var i = 0, l = materials.length; i < l; i ++ ) { - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + group.add( new Mesh( geometry, materials[ i ] ) ); -}; + } -THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper; + return group; -// File:src/extras/objects/ImmediateRenderObject.js + }, + detach: function ( child, parent, scene ) { + + child.applyMatrix( parent.matrixWorld ); + parent.remove( child ); + scene.add( child ); + + }, + + attach: function ( child, scene, parent ) { + + var matrixWorldInverse = new Matrix4(); + matrixWorldInverse.getInverse( parent.matrixWorld ); + child.applyMatrix( matrixWorldInverse ); + + scene.remove( child ); + parent.add( child ); + + } + + }; + + Object.defineProperty( exports, 'AudioContext', { + get: function () { + return exports.getAudioContext(); + } + }); + + exports.SpritePlugin = SpritePlugin; + exports.LensFlarePlugin = LensFlarePlugin; + exports.WebGLTextures = WebGLTextures; + exports.WebGLStencilBuffer = WebGLStencilBuffer; + exports.WebGLDepthBuffer = WebGLDepthBuffer; + exports.WebGLColorBuffer = WebGLColorBuffer; + exports.WebGLState = WebGLState; + exports.WebGLShadowMap = WebGLShadowMap; + exports.WebGLProperties = WebGLProperties; + exports.WebGLPrograms = WebGLPrograms; + exports.WebGLObjects = WebGLObjects; + exports.WebGLLights = WebGLLights; + exports.WebGLGeometries = WebGLGeometries; + exports.WebGLCapabilities = WebGLCapabilities; + exports.WebGLExtensions = WebGLExtensions; + exports.WebGLIndexedBufferRenderer = WebGLIndexedBufferRenderer; + exports.WebGLClipping = WebGLClipping; + exports.WebGLBufferRenderer = WebGLBufferRenderer; + exports.WebGLRenderTargetCube = WebGLRenderTargetCube; + exports.WebGLRenderTarget = WebGLRenderTarget; + exports.WebGLRenderer = WebGLRenderer; + exports.FogExp2 = FogExp2; + exports.Fog = Fog; + exports.Scene = Scene; + exports.LensFlare = LensFlare; + exports.Sprite = Sprite; + exports.LOD = LOD; + exports.SkinnedMesh = SkinnedMesh; + exports.Skeleton = Skeleton; + exports.Bone = Bone; + exports.Mesh = Mesh; + exports.LineSegments = LineSegments; + exports.Line = Line; + exports.Points = Points; + exports.Group = Group; + exports.VideoTexture = VideoTexture; + exports.DataTexture = DataTexture; + exports.CompressedTexture = CompressedTexture; + exports.CubeTexture = CubeTexture; + exports.CanvasTexture = CanvasTexture; + exports.DepthTexture = DepthTexture; + exports.TextureIdCount = TextureIdCount; + exports.Texture = Texture; + exports.ShadowMaterial = ShadowMaterial; + exports.SpriteMaterial = SpriteMaterial; + exports.RawShaderMaterial = RawShaderMaterial; + exports.ShaderMaterial = ShaderMaterial; + exports.PointsMaterial = PointsMaterial; + exports.MultiMaterial = MultiMaterial; + exports.MeshPhysicalMaterial = MeshPhysicalMaterial; + exports.MeshStandardMaterial = MeshStandardMaterial; + exports.MeshPhongMaterial = MeshPhongMaterial; + exports.MeshNormalMaterial = MeshNormalMaterial; + exports.MeshLambertMaterial = MeshLambertMaterial; + exports.MeshDepthMaterial = MeshDepthMaterial; + exports.MeshBasicMaterial = MeshBasicMaterial; + exports.LineDashedMaterial = LineDashedMaterial; + exports.LineBasicMaterial = LineBasicMaterial; + exports.MaterialIdCount = MaterialIdCount; + exports.Material = Material; + exports.CompressedTextureLoader = CompressedTextureLoader; + exports.BinaryTextureLoader = BinaryTextureLoader; + exports.DataTextureLoader = DataTextureLoader; + exports.CubeTextureLoader = CubeTextureLoader; + exports.TextureLoader = TextureLoader; + exports.ObjectLoader = ObjectLoader; + exports.MaterialLoader = MaterialLoader; + exports.BufferGeometryLoader = BufferGeometryLoader; + exports.LoadingManager = LoadingManager; + exports.JSONLoader = JSONLoader; + exports.ImageLoader = ImageLoader; + exports.FontLoader = FontLoader; + exports.XHRLoader = XHRLoader; + exports.Loader = Loader; + exports.AudioLoader = AudioLoader; + exports.SpotLightShadow = SpotLightShadow; + exports.SpotLight = SpotLight; + exports.PointLight = PointLight; + exports.HemisphereLight = HemisphereLight; + exports.DirectionalLightShadow = DirectionalLightShadow; + exports.DirectionalLight = DirectionalLight; + exports.AmbientLight = AmbientLight; + exports.LightShadow = LightShadow; + exports.Light = Light; + exports.StereoCamera = StereoCamera; + exports.PerspectiveCamera = PerspectiveCamera; + exports.OrthographicCamera = OrthographicCamera; + exports.CubeCamera = CubeCamera; + exports.Camera = Camera; + exports.AudioListener = AudioListener; + exports.PositionalAudio = PositionalAudio; + exports.getAudioContext = getAudioContext; + exports.AudioAnalyser = AudioAnalyser; + exports.Audio = Audio; + exports.VectorKeyframeTrack = VectorKeyframeTrack; + exports.StringKeyframeTrack = StringKeyframeTrack; + exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack; + exports.NumberKeyframeTrack = NumberKeyframeTrack; + exports.ColorKeyframeTrack = ColorKeyframeTrack; + exports.BooleanKeyframeTrack = BooleanKeyframeTrack; + exports.PropertyMixer = PropertyMixer; + exports.PropertyBinding = PropertyBinding; + exports.KeyframeTrack = KeyframeTrack; + exports.AnimationObjectGroup = AnimationObjectGroup; + exports.AnimationMixer = AnimationMixer; + exports.AnimationClip = AnimationClip; + exports.AnimationAction = AnimationAction; + exports.Uniform = Uniform; + exports.InstancedBufferGeometry = InstancedBufferGeometry; + exports.BufferGeometry = BufferGeometry; + exports.DirectGeometry = DirectGeometry; + exports.GeometryIdCount = GeometryIdCount; + exports.Geometry = Geometry; + exports.InterleavedBufferAttribute = InterleavedBufferAttribute; + exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer; + exports.InterleavedBuffer = InterleavedBuffer; + exports.InstancedBufferAttribute = InstancedBufferAttribute; + exports.DynamicBufferAttribute = DynamicBufferAttribute; + exports.Float64Attribute = Float64Attribute; + exports.Float32Attribute = Float32Attribute; + exports.Uint32Attribute = Uint32Attribute; + exports.Int32Attribute = Int32Attribute; + exports.Uint16Attribute = Uint16Attribute; + exports.Int16Attribute = Int16Attribute; + exports.Uint8ClampedAttribute = Uint8ClampedAttribute; + exports.Uint8Attribute = Uint8Attribute; + exports.Int8Attribute = Int8Attribute; + exports.BufferAttribute = BufferAttribute; + exports.Face3 = Face3; + exports.Object3DIdCount = Object3DIdCount; + exports.Object3D = Object3D; + exports.Raycaster = Raycaster; + exports.Layers = Layers; + exports.EventDispatcher = EventDispatcher; + exports.Clock = Clock; + exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant; + exports.LinearInterpolant = LinearInterpolant; + exports.DiscreteInterpolant = DiscreteInterpolant; + exports.CubicInterpolant = CubicInterpolant; + exports.Interpolant = Interpolant; + exports.Triangle = Triangle; + exports.Spline = Spline; + exports.Spherical = Spherical; + exports.Plane = Plane; + exports.Frustum = Frustum; + exports.Sphere = Sphere; + exports.Ray = Ray; + exports.Matrix4 = Matrix4; + exports.Matrix3 = Matrix3; + exports.Box3 = Box3; + exports.Box2 = Box2; + exports.Line3 = Line3; + exports.Euler = Euler; + exports.Vector4 = Vector4; + exports.Vector3 = Vector3; + exports.Vector2 = Vector2; + exports.Quaternion = Quaternion; + exports.Color = Color; + exports.MorphBlendMesh = MorphBlendMesh; + exports.ImmediateRenderObject = ImmediateRenderObject; + exports.WireframeHelper = WireframeHelper; + exports.VertexNormalsHelper = VertexNormalsHelper; + exports.SpotLightHelper = SpotLightHelper; + exports.SkeletonHelper = SkeletonHelper; + exports.PointLightHelper = PointLightHelper; + exports.HemisphereLightHelper = HemisphereLightHelper; + exports.GridHelper = GridHelper; + exports.FaceNormalsHelper = FaceNormalsHelper; + exports.EdgesHelper = EdgesHelper; + exports.DirectionalLightHelper = DirectionalLightHelper; + exports.CameraHelper = CameraHelper; + exports.BoundingBoxHelper = BoundingBoxHelper; + exports.BoxHelper = BoxHelper; + exports.AxisHelper = AxisHelper; + exports.WireframeGeometry = WireframeGeometry; + exports.ParametricGeometry = ParametricGeometry; + exports.TetrahedronGeometry = TetrahedronGeometry; + exports.OctahedronGeometry = OctahedronGeometry; + exports.IcosahedronGeometry = IcosahedronGeometry; + exports.DodecahedronGeometry = DodecahedronGeometry; + exports.PolyhedronGeometry = PolyhedronGeometry; + exports.TubeGeometry = TubeGeometry; + exports.TorusKnotGeometry = TorusKnotGeometry; + exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry; + exports.TorusGeometry = TorusGeometry; + exports.TorusBufferGeometry = TorusBufferGeometry; + exports.TextGeometry = TextGeometry; + exports.SphereBufferGeometry = SphereBufferGeometry; + exports.SphereGeometry = SphereGeometry; + exports.RingGeometry = RingGeometry; + exports.RingBufferGeometry = RingBufferGeometry; + exports.PlaneBufferGeometry = PlaneBufferGeometry; + exports.PlaneGeometry = PlaneGeometry; + exports.LatheGeometry = LatheGeometry; + exports.LatheBufferGeometry = LatheBufferGeometry; + exports.ShapeGeometry = ShapeGeometry; + exports.ExtrudeGeometry = ExtrudeGeometry; + exports.EdgesGeometry = EdgesGeometry; + exports.ConeGeometry = ConeGeometry; + exports.ConeBufferGeometry = ConeBufferGeometry; + exports.CylinderGeometry = CylinderGeometry; + exports.CylinderBufferGeometry = CylinderBufferGeometry; + exports.CircleBufferGeometry = CircleBufferGeometry; + exports.CircleGeometry = CircleGeometry; + exports.BoxBufferGeometry = BoxBufferGeometry; + exports.BoxGeometry = BoxGeometry; + exports.ClosedSplineCurve3 = ClosedSplineCurve3; + exports.ArcCurve = ArcCurve; + exports.EllipseCurve = EllipseCurve; + exports.SplineCurve = SplineCurve; + exports.CubicBezierCurve = CubicBezierCurve; + exports.QuadraticBezierCurve = QuadraticBezierCurve; + exports.LineCurve = LineCurve; + exports.Shape = Shape; + exports.ShapePath = ShapePath; + exports.Path = Path; + exports.Font = Font; + exports.CurvePath = CurvePath; + exports.Curve = Curve; + exports.MOUSE = MOUSE; + exports.CullFaceNone = CullFaceNone; + exports.CullFaceBack = CullFaceBack; + exports.CullFaceFront = CullFaceFront; + exports.CullFaceFrontBack = CullFaceFrontBack; + exports.FrontFaceDirectionCW = FrontFaceDirectionCW; + exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW; + exports.BasicShadowMap = BasicShadowMap; + exports.PCFShadowMap = PCFShadowMap; + exports.PCFSoftShadowMap = PCFSoftShadowMap; + exports.FrontSide = FrontSide; + exports.BackSide = BackSide; + exports.DoubleSide = DoubleSide; + exports.FlatShading = FlatShading; + exports.SmoothShading = SmoothShading; + exports.NoColors = NoColors; + exports.FaceColors = FaceColors; + exports.VertexColors = VertexColors; + exports.NoBlending = NoBlending; + exports.NormalBlending = NormalBlending; + exports.AdditiveBlending = AdditiveBlending; + exports.SubtractiveBlending = SubtractiveBlending; + exports.MultiplyBlending = MultiplyBlending; + exports.CustomBlending = CustomBlending; + exports.AddEquation = AddEquation; + exports.SubtractEquation = SubtractEquation; + exports.ReverseSubtractEquation = ReverseSubtractEquation; + exports.MinEquation = MinEquation; + exports.MaxEquation = MaxEquation; + exports.ZeroFactor = ZeroFactor; + exports.OneFactor = OneFactor; + exports.SrcColorFactor = SrcColorFactor; + exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor; + exports.SrcAlphaFactor = SrcAlphaFactor; + exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor; + exports.DstAlphaFactor = DstAlphaFactor; + exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor; + exports.DstColorFactor = DstColorFactor; + exports.OneMinusDstColorFactor = OneMinusDstColorFactor; + exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor; + exports.NeverDepth = NeverDepth; + exports.AlwaysDepth = AlwaysDepth; + exports.LessDepth = LessDepth; + exports.LessEqualDepth = LessEqualDepth; + exports.EqualDepth = EqualDepth; + exports.GreaterEqualDepth = GreaterEqualDepth; + exports.GreaterDepth = GreaterDepth; + exports.NotEqualDepth = NotEqualDepth; + exports.MultiplyOperation = MultiplyOperation; + exports.MixOperation = MixOperation; + exports.AddOperation = AddOperation; + exports.NoToneMapping = NoToneMapping; + exports.LinearToneMapping = LinearToneMapping; + exports.ReinhardToneMapping = ReinhardToneMapping; + exports.Uncharted2ToneMapping = Uncharted2ToneMapping; + exports.CineonToneMapping = CineonToneMapping; + exports.UVMapping = UVMapping; + exports.CubeReflectionMapping = CubeReflectionMapping; + exports.CubeRefractionMapping = CubeRefractionMapping; + exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping; + exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping; + exports.SphericalReflectionMapping = SphericalReflectionMapping; + exports.CubeUVReflectionMapping = CubeUVReflectionMapping; + exports.CubeUVRefractionMapping = CubeUVRefractionMapping; + exports.RepeatWrapping = RepeatWrapping; + exports.ClampToEdgeWrapping = ClampToEdgeWrapping; + exports.MirroredRepeatWrapping = MirroredRepeatWrapping; + exports.NearestFilter = NearestFilter; + exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter; + exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter; + exports.LinearFilter = LinearFilter; + exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter; + exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter; + exports.UnsignedByteType = UnsignedByteType; + exports.ByteType = ByteType; + exports.ShortType = ShortType; + exports.UnsignedShortType = UnsignedShortType; + exports.IntType = IntType; + exports.UnsignedIntType = UnsignedIntType; + exports.FloatType = FloatType; + exports.HalfFloatType = HalfFloatType; + exports.UnsignedShort4444Type = UnsignedShort4444Type; + exports.UnsignedShort5551Type = UnsignedShort5551Type; + exports.UnsignedShort565Type = UnsignedShort565Type; + exports.AlphaFormat = AlphaFormat; + exports.RGBFormat = RGBFormat; + exports.RGBAFormat = RGBAFormat; + exports.LuminanceFormat = LuminanceFormat; + exports.LuminanceAlphaFormat = LuminanceAlphaFormat; + exports.RGBEFormat = RGBEFormat; + exports.DepthFormat = DepthFormat; + exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format; + exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format; + exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format; + exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format; + exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format; + exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format; + exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format; + exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format; + exports.RGB_ETC1_Format = RGB_ETC1_Format; + exports.LoopOnce = LoopOnce; + exports.LoopRepeat = LoopRepeat; + exports.LoopPingPong = LoopPingPong; + exports.InterpolateDiscrete = InterpolateDiscrete; + exports.InterpolateLinear = InterpolateLinear; + exports.InterpolateSmooth = InterpolateSmooth; + exports.ZeroCurvatureEnding = ZeroCurvatureEnding; + exports.ZeroSlopeEnding = ZeroSlopeEnding; + exports.WrapAroundEnding = WrapAroundEnding; + exports.TrianglesDrawMode = TrianglesDrawMode; + exports.TriangleStripDrawMode = TriangleStripDrawMode; + exports.TriangleFanDrawMode = TriangleFanDrawMode; + exports.LinearEncoding = LinearEncoding; + exports.sRGBEncoding = sRGBEncoding; + exports.GammaEncoding = GammaEncoding; + exports.RGBEEncoding = RGBEEncoding; + exports.LogLuvEncoding = LogLuvEncoding; + exports.RGBM7Encoding = RGBM7Encoding; + exports.RGBM16Encoding = RGBM16Encoding; + exports.RGBDEncoding = RGBDEncoding; + exports.BasicDepthPacking = BasicDepthPacking; + exports.RGBADepthPacking = RGBADepthPacking; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); /** - * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ */ -THREE.ImmediateRenderObject = function ( material ) { - - THREE.Object3D.call( this ); - - this.material = material; - this.render = function ( renderCallback ) {}; +Object.assign( THREE, { + Face4: function ( a, b, c, d, normal, color, materialIndex ) { + console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ); + return new THREE.Face3( a, b, c, normal, color, materialIndex ); + }, + LineStrip: 0, + LinePieces: 1, + MeshFaceMaterial: THREE.MultiMaterial, + PointCloud: function ( geometry, material ) { + console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); + return new THREE.Points( geometry, material ); + }, + Particle: THREE.Sprite, + ParticleSystem: function ( geometry, material ) { + console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); + return new THREE.Points( geometry, material ); + }, + PointCloudMaterial: function ( parameters ) { + console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); + return new THREE.PointsMaterial( parameters ); + }, + ParticleBasicMaterial: function ( parameters ) { + console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); + return new THREE.PointsMaterial( parameters ); + }, + ParticleSystemMaterial: function ( parameters ) { + console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); + return new THREE.PointsMaterial( parameters ); + }, + Vertex: function ( x, y, z ) { + console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); + return new THREE.Vector3( x, y, z ); + } +} ); -}; +// -THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject; +Object.assign( THREE.Box2.prototype, { + empty: function () { + console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); + return this.isEmpty(); + }, + isIntersectionBox: function ( box ) { + console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); + return this.intersectsBox( box ); + } +} ); -// File:src/extras/objects/MorphBlendMesh.js +Object.assign( THREE.Box3.prototype, { + empty: function () { + console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); + return this.isEmpty(); + }, + isIntersectionBox: function ( box ) { + console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); + return this.intersectsBox( box ); + }, + isIntersectionSphere: function ( sphere ) { + console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); + return this.intersectsSphere( sphere ); + } +} ); -/** - * @author alteredq / http://alteredqualia.com/ - */ +Object.assign( THREE.Matrix3.prototype, { + multiplyVector3: function ( vector ) { + console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); + return vector.applyMatrix3( this ); + }, + multiplyVector3Array: function ( a ) { + console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); + return this.applyToVector3Array( a ); + } +} ); -THREE.MorphBlendMesh = function( geometry, material ) { +Object.assign( THREE.Matrix4.prototype, { + extractPosition: function ( m ) { + console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); + return this.copyPosition( m ); + }, + setRotationFromQuaternion: function ( q ) { + console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); + return this.makeRotationFromQuaternion( q ); + }, + multiplyVector3: function ( vector ) { + console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); + return vector.applyProjection( this ); + }, + multiplyVector4: function ( vector ) { + console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + return vector.applyMatrix4( this ); + }, + multiplyVector3Array: function ( a ) { + console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); + return this.applyToVector3Array( a ); + }, + rotateAxis: function ( v ) { + console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); + v.transformDirection( this ); + }, + crossVector: function ( vector ) { + console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + return vector.applyMatrix4( this ); + }, + translate: function ( v ) { + console.error( 'THREE.Matrix4: .translate() has been removed.' ); + }, + rotateX: function ( angle ) { + console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); + }, + rotateY: function ( angle ) { + console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); + }, + rotateZ: function ( angle ) { + console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); + }, + rotateByAxis: function ( axis, angle ) { + console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); + } +} ); - THREE.Mesh.call( this, geometry, material ); +Object.assign( THREE.Plane.prototype, { + isIntersectionLine: function ( line ) { + console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); + return this.intersectsLine( line ); + } +} ); - this.animationsMap = {}; - this.animationsList = []; +Object.assign( THREE.Quaternion.prototype, { + multiplyVector3: function ( vector ) { + console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); + return vector.applyQuaternion( this ); + } +} ); - // prepare default animation - // (all frames played together in 1 second) +Object.assign( THREE.Ray.prototype, { + isIntersectionBox: function ( box ) { + console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); + return this.intersectsBox( box ); + }, + isIntersectionPlane: function ( plane ) { + console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); + return this.intersectsPlane( plane ); + }, + isIntersectionSphere: function ( sphere ) { + console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); + return this.intersectsSphere( sphere ); + } +} ); - var numFrames = this.geometry.morphTargets.length; +Object.assign( THREE.Vector3.prototype, { + setEulerFromRotationMatrix: function () { + console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); + }, + setEulerFromQuaternion: function () { + console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); + }, + getPositionFromMatrix: function ( m ) { + console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); + return this.setFromMatrixPosition( m ); + }, + getScaleFromMatrix: function ( m ) { + console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); + return this.setFromMatrixScale( m ); + }, + getColumnFromMatrix: function ( index, matrix ) { + console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); + return this.setFromMatrixColumn( matrix, index ); + } +} ); - var name = "__default"; +// - var startFrame = 0; - var endFrame = numFrames - 1; +Object.assign( THREE.Object3D.prototype, { + getChildByName: function ( name ) { + console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); + return this.getObjectByName( name ); + }, + renderDepth: function ( value ) { + console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); + }, + translate: function ( distance, axis ) { + console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); + return this.translateOnAxis( axis, distance ); + } +} ); - var fps = numFrames / 1; +Object.defineProperties( THREE.Object3D.prototype, { + eulerOrder: { + get: function () { + console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); + return this.rotation.order; + }, + set: function ( value ) { + console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); + this.rotation.order = value; + } + }, + useQuaternion: { + get: function () { + console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + }, + set: function ( value ) { + console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + } + } +} ); - this.createAnimation( name, startFrame, endFrame, fps ); - this.setAnimationWeight( name, 1 ); +Object.defineProperties( THREE.LOD.prototype, { + objects: { + get: function () { + console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); + return this.levels; + } + } +} ); -}; +// -THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype ); -THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh; +THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { -THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { + console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " + + "Use .setFocalLength and .filmGauge for a photographic setup." ); - var animation = { + if ( filmGauge !== undefined ) this.filmGauge = filmGauge; + this.setFocalLength( focalLength ); - start: start, - end: end, +}; - length: end - start + 1, +// - fps: fps, - duration: ( end - start ) / fps, +Object.defineProperties( THREE.Light.prototype, { + onlyShadow: { + set: function ( value ) { + console.warn( 'THREE.Light: .onlyShadow has been removed.' ); + } + }, + shadowCameraFov: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); + this.shadow.camera.fov = value; + } + }, + shadowCameraLeft: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' ); + this.shadow.camera.left = value; + } + }, + shadowCameraRight: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' ); + this.shadow.camera.right = value; + } + }, + shadowCameraTop: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); + this.shadow.camera.top = value; + } + }, + shadowCameraBottom: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); + this.shadow.camera.bottom = value; + } + }, + shadowCameraNear: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); + this.shadow.camera.near = value; + } + }, + shadowCameraFar: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); + this.shadow.camera.far = value; + } + }, + shadowCameraVisible: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); + } + }, + shadowBias: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); + this.shadow.bias = value; + } + }, + shadowDarkness: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); + } + }, + shadowMapWidth: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); + this.shadow.mapSize.width = value; + } + }, + shadowMapHeight: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); + this.shadow.mapSize.height = value; + } + } +} ); - lastFrame: 0, - currentFrame: 0, +// - active: false, +Object.defineProperties( THREE.BufferAttribute.prototype, { + length: { + get: function () { + console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); + return this.array.length; + } + } +} ); - time: 0, - direction: 1, - weight: 1, +Object.assign( THREE.BufferGeometry.prototype, { + addIndex: function ( index ) { + console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); + this.setIndex( index ); + }, + addDrawCall: function ( start, count, indexOffset ) { + if ( indexOffset !== undefined ) { + console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); + } + console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); + this.addGroup( start, count ); + }, + clearDrawCalls: function () { + console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); + this.clearGroups(); + }, + computeTangents: function () { + console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' ); + }, + computeOffsets: function () { + console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); + } +} ); - directionBackwards: false, - mirroredLoop: false +Object.defineProperties( THREE.BufferGeometry.prototype, { + drawcalls: { + get: function () { + console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); + return this.groups; + } + }, + offsets: { + get: function () { + console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); + return this.groups; + } + } +} ); - }; +// - this.animationsMap[ name ] = animation; - this.animationsList.push( animation ); +Object.defineProperties( THREE.Material.prototype, { + wrapAround: { + get: function () { + console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' ); + }, + set: function ( value ) { + console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' ); + } + }, + wrapRGB: { + get: function () { + console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' ); + return new THREE.Color(); + } + } +} ); -}; +Object.defineProperties( THREE.MeshPhongMaterial.prototype, { + metal: { + get: function () { + console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' ); + return false; + }, + set: function ( value ) { + console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' ); + } + } +} ); -THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { +Object.defineProperties( THREE.ShaderMaterial.prototype, { + derivatives: { + get: function () { + console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); + return this.extensions.derivatives; + }, + set: function ( value ) { + console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); + this.extensions.derivatives = value; + } + } +} ); - var pattern = /([a-z]+)_?(\d+)/i; +// - var firstAnimation, frameRanges = {}; +THREE.EventDispatcher.prototype = Object.assign( Object.create( { - var geometry = this.geometry; + // Note: Extra base ensures these properties are not 'assign'ed. - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + constructor: THREE.EventDispatcher, - var morph = geometry.morphTargets[ i ]; - var chunks = morph.name.match( pattern ); + apply: function ( target ) { - if ( chunks && chunks.length > 1 ) { + console.warn( "THREE.EventDispatcher: .apply is deprecated, " + + "just inherit or Object.assign the prototype to mix-in." ); - var name = chunks[ 1 ]; + Object.assign( target, this ); - if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity }; + } - var range = frameRanges[ name ]; +} ), THREE.EventDispatcher.prototype ); - if ( i < range.start ) range.start = i; - if ( i > range.end ) range.end = i; +// - if ( ! firstAnimation ) firstAnimation = name; +Object.assign( THREE.WebGLRenderer.prototype, { + supportsFloatTextures: function () { + console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); + return this.extensions.get( 'OES_texture_float' ); + }, + supportsHalfFloatTextures: function () { + console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); + return this.extensions.get( 'OES_texture_half_float' ); + }, + supportsStandardDerivatives: function () { + console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); + return this.extensions.get( 'OES_standard_derivatives' ); + }, + supportsCompressedTextureS3TC: function () { + console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); + return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); + }, + supportsCompressedTexturePVRTC: function () { + console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); + return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + }, + supportsBlendMinMax: function () { + console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); + return this.extensions.get( 'EXT_blend_minmax' ); + }, + supportsVertexTextures: function () { + return this.capabilities.vertexTextures; + }, + supportsInstancedArrays: function () { + console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); + return this.extensions.get( 'ANGLE_instanced_arrays' ); + }, + enableScissorTest: function ( boolean ) { + console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); + this.setScissorTest( boolean ); + }, + initMaterial: function () { + console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); + }, + addPrePlugin: function () { + console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); + }, + addPostPlugin: function () { + console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); + }, + updateShadowMap: function () { + console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); + } +} ); +Object.defineProperties( THREE.WebGLRenderer.prototype, { + shadowMapEnabled: { + get: function () { + return this.shadowMap.enabled; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); + this.shadowMap.enabled = value; + } + }, + shadowMapType: { + get: function () { + return this.shadowMap.type; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); + this.shadowMap.type = value; + } + }, + shadowMapCullFace: { + get: function () { + return this.shadowMap.cullFace; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' ); + this.shadowMap.cullFace = value; } - } +} ); - for ( var name in frameRanges ) { - - var range = frameRanges[ name ]; - this.createAnimation( name, range.start, range.end, fps ); - +Object.defineProperties( THREE.WebGLShadowMap.prototype, { + cullFace: { + get: function () { + return this.renderReverseSided ? THREE.CullFaceFront : THREE.CullFaceBack; + }, + set: function ( cullFace ) { + var value = ( cullFace !== THREE.CullFaceBack ); + console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." ); + this.renderReverseSided = value; + } } +} ); - this.firstAnimation = firstAnimation; - -}; - -THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.direction = 1; - animation.directionBackwards = false; +// +Object.defineProperties( THREE.WebGLRenderTarget.prototype, { + wrapS: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); + return this.texture.wrapS; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); + this.texture.wrapS = value; + } + }, + wrapT: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); + return this.texture.wrapT; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); + this.texture.wrapT = value; + } + }, + magFilter: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); + return this.texture.magFilter; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); + this.texture.magFilter = value; + } + }, + minFilter: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); + return this.texture.minFilter; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); + this.texture.minFilter = value; + } + }, + anisotropy: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); + return this.texture.anisotropy; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); + this.texture.anisotropy = value; + } + }, + offset: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); + return this.texture.offset; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); + this.texture.offset = value; + } + }, + repeat: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); + return this.texture.repeat; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); + this.texture.repeat = value; + } + }, + format: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); + return this.texture.format; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); + this.texture.format = value; + } + }, + type: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); + return this.texture.type; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); + this.texture.type = value; + } + }, + generateMipmaps: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); + return this.texture.generateMipmaps; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); + this.texture.generateMipmaps = value; + } } +} ); -}; - -THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.direction = - 1; - animation.directionBackwards = true; +// +Object.assign( THREE.Audio.prototype, { + load: function ( file ) { + console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' ); + var scope = this; + var audioLoader = new THREE.AudioLoader(); + audioLoader.load( file, function ( buffer ) { + scope.setBuffer( buffer ); + } ); + return this; } +} ); -}; - -THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.fps = fps; - animation.duration = ( animation.end - animation.start ) / animation.fps; - +Object.assign( THREE.AudioAnalyser.prototype, { + getData: function ( file ) { + console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); + return this.getFrequencyData(); } +} ); -}; - -THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.duration = duration; - animation.fps = ( animation.end - animation.start ) / animation.duration; +// - } +THREE.GeometryUtils = { -}; + merge: function ( geometry1, geometry2, materialIndexOffset ) { -THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { + console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); - var animation = this.animationsMap[ name ]; + var matrix; - if ( animation ) { + if ( geometry2 instanceof THREE.Mesh ) { - animation.weight = weight; + geometry2.matrixAutoUpdate && geometry2.updateMatrix(); - } + matrix = geometry2.matrix; + geometry2 = geometry2.geometry; -}; + } -THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { + geometry1.merge( geometry2, matrix, materialIndexOffset ); - var animation = this.animationsMap[ name ]; + }, - if ( animation ) { + center: function ( geometry ) { - animation.time = time; + console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); + return geometry.center(); } }; -THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { - - var time = 0; - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - time = animation.time; - - } - - return time; - -}; +THREE.ImageUtils = { -THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { + crossOrigin: undefined, - var duration = - 1; + loadTexture: function ( url, mapping, onLoad, onError ) { - var animation = this.animationsMap[ name ]; + console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); - if ( animation ) { + var loader = new THREE.TextureLoader(); + loader.setCrossOrigin( this.crossOrigin ); - duration = animation.duration; + var texture = loader.load( url, onLoad, undefined, onError ); - } + if ( mapping ) texture.mapping = mapping; - return duration; + return texture; -}; + }, -THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { + loadTextureCube: function ( urls, mapping, onLoad, onError ) { - var animation = this.animationsMap[ name ]; + console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); - if ( animation ) { + var loader = new THREE.CubeTextureLoader(); + loader.setCrossOrigin( this.crossOrigin ); - animation.time = 0; - animation.active = true; + var texture = loader.load( urls, onLoad, undefined, onError ); - } else { + if ( mapping ) texture.mapping = mapping; - console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" ); + return texture; - } + }, -}; + loadCompressedTexture: function () { -THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { + console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); - var animation = this.animationsMap[ name ]; + }, - if ( animation ) { + loadCompressedTextureCube: function () { - animation.active = false; + console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); } }; -THREE.MorphBlendMesh.prototype.update = function ( delta ) { - - for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { - - var animation = this.animationsList[ i ]; - - if ( ! animation.active ) continue; - - var frameTime = animation.duration / animation.length; - - animation.time += animation.direction * delta; - - if ( animation.mirroredLoop ) { - - if ( animation.time > animation.duration || animation.time < 0 ) { - - animation.direction *= - 1; - - if ( animation.time > animation.duration ) { - - animation.time = animation.duration; - animation.directionBackwards = true; - - } - - if ( animation.time < 0 ) { - - animation.time = 0; - animation.directionBackwards = false; - - } - - } - - } else { - - animation.time = animation.time % animation.duration; +// - if ( animation.time < 0 ) animation.time += animation.duration; +THREE.Projector = function () { - } + console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' ); - var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); - var weight = animation.weight; + this.projectVector = function ( vector, camera ) { - if ( keyframe !== animation.currentFrame ) { + console.warn( 'THREE.Projector: .projectVector() is now vector.project().' ); + vector.project( camera ); - this.morphTargetInfluences[ animation.lastFrame ] = 0; - this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; + }; - this.morphTargetInfluences[ keyframe ] = 0; + this.unprojectVector = function ( vector, camera ) { - animation.lastFrame = animation.currentFrame; - animation.currentFrame = keyframe; + console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' ); + vector.unproject( camera ); - } + }; - var mix = ( animation.time % frameTime ) / frameTime; + this.pickingRay = function ( vector, camera ) { - if ( animation.directionBackwards ) mix = 1 - mix; + console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' ); - if ( animation.currentFrame !== animation.lastFrame ) { + }; - this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; - this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; +}; - } else { +// - this.morphTargetInfluences[ animation.currentFrame ] = weight; +THREE.CanvasRenderer = function () { - } + console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' ); - } + this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + this.clear = function () {}; + this.render = function () {}; + this.setClearColor = function () {}; + this.setSize = function () {}; }; - diff --git a/build/three.min.js b/build/three.min.js index 64cad2e875ee10..18a48b5d4fcf64 100644 --- a/build/three.min.js +++ b/build/three.min.js @@ -1,993 +1,16 @@ -// threejs.org/license -'use strict';var THREE={REVISION:"79dev"};"function"===typeof define&&define.amd?define("three",THREE):"undefined"!==typeof exports&&"undefined"!==typeof module&&(module.exports=THREE);void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52));void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b,c,d){b=THREE.Math.euclideanModulo(b,1);c=THREE.Math.clamp(c,0,1);d=THREE.Math.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c= -/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(255,parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){var d= -parseFloat(c[1])/360,e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0=h?k/(e+f):k/(2-e-f);switch(e){case b:g=(c-d)/k+(cf&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y= -.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a,b;return function(c,d){void 0===a&&(a=new THREE.Vector3);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*= --1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this}, -multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y,k=b._z,l=b._w;this._x=c*l+f*g+d*k-e*h;this._y=d*l+f*h+e*g-c*k;this._z=e*l+f*k+c*h-d*g;this._w=f*l-c*g-d*h-e*k;this.onChangeCallback(); -return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.sqrt(1-g*g);if(.001>Math.abs(h))return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var k=Math.atan2(h,g),g=Math.sin((1-b)*k)/h,h=Math.sin(b* -k)/h;this._w=f*g+this._w*h;this._x=c*g+this._x*h;this._y=d*g+this._y*h;this._z=e*g+this._z*h;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback= -a;return this},onChangeCallback:function(){}}; -Object.assign(THREE.Quaternion,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],l=c[d+2];c=c[d+3];d=e[f+0];var m=e[f+1],p=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==m||l!==p){f=1-g;var n=h*d+k*m+l*p+c*e,q=0<=n?1:-1,r=1-n*n;r>Number.EPSILON&&(r=Math.sqrt(r),n=Math.atan2(r,n*q),f=Math.sin(f*n)/r,g=Math.sin(g*n)/r);q*=g;h=h*f+d*q;k=k*f+m*q;l=l*f+p*q;c=c*f+e*q;f===1-g&&(g=1/Math.sqrt(h*h+k*k+l*l+c*c),h*=g,k*=g,l*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=l; -a[b+3]=c}});THREE.Vector2=function(a,b){this.x=a||0;this.y=b||0}; -THREE.Vector2.prototype={constructor:THREE.Vector2,get width(){return this.x},set width(a){this.x=a},get height(){return this.y},set height(a){this.y=a},set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+a);}},getComponent:function(a){switch(a){case 0:return this.x; -case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this}, -addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a, -this.y*=a):this.y=this.x=0;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a,b;return function(c,d){void 0=== -a&&(a=new THREE.Vector2,b=new THREE.Vector2);a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x); -this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a}, -distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y}, -fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromAttribute:function(a,b,c){void 0===c&&(c=0);b=b*a.itemSize+c;this.x=a.array[b];this.y=a.array[b+1];return this},rotateAround:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=this.x-a.x,f=this.y-a.y;this.x=e*c-f*d+a.x;this.y=e*d+f*c+a.y;return this}};THREE.Vector3=function(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}; -THREE.Vector3.prototype={constructor:THREE.Vector3,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y; -case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},addVectors:function(a, -b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this}, -multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a,this.y*=a,this.z*=a):this.z=this.y=this.x=0;return this},multiplyVectors:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a;return function(b){!1===b instanceof THREE.Euler&& -console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");void 0===a&&(a=new THREE.Quaternion);return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a;return function(b,c){void 0===a&&(a=new THREE.Quaternion);return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this}, -applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12];this.y=a[1]*b+a[5]*c+a[9]*d+a[13];this.z=a[2]*b+a[6]*c+a[10]*d+a[14];return this},applyProjection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a= -a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,l=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-l*-f;this.y=k*a+b*-f+l*-e-h*-g;this.z=l*a+b*-g+h*-f-k*-e;return this},project:function(){var a;return function(b){void 0===a&&(a=new THREE.Matrix4);a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyProjection(a)}}(),unproject:function(){var a;return function(b){void 0===a&&(a=new THREE.Matrix4);a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyProjection(a)}}(), -transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z= -Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new THREE.Vector3,b=new THREE.Vector3);a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);this.y= -Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y= --this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+= -(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b);var c=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-c*a.z;this.z=c*a.y-d*a.x;return this},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;this.x=d*h-e*g;this.y=e*f-c*h; -this.z=c*g-d*f;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a;return function(b){void 0===a&&(a=new THREE.Vector3);a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a;return function(b){void 0===a&&(a=new THREE.Vector3);return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(THREE.Math.clamp(a, --1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){return this.setFromMatrixColumn(a,3)}, -setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){if("number"===typeof a){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var c=a;a=b;b=c}return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0); -this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromAttribute:function(a,b,c){void 0===c&&(c=0);b=b*a.itemSize+c;this.x=a.array[b];this.y=a.array[b+1];this.z=a.array[b+2];return this}};THREE.Vector4=function(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}; -THREE.Vector4.prototype={constructor:THREE.Vector4,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+ -a);}},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b); -this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-= -a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a,this.y*=a,this.z*=a,this.w*=a):this.w=this.z=this.y=this.x=0;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z= -a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/b);return this},setAxisAngleFromRotationMatrix:function(a){var b,c,d;a=a.elements;var e=a[0];d=a[4];var f=a[8],g=a[1],h=a[5],k=a[9];c=a[2];b=a[6];var l=a[10];if(.01>Math.abs(d-g)&&.01>Math.abs(f-c)&&.01> -Math.abs(k-b)){if(.1>Math.abs(d+g)&&.1>Math.abs(f+c)&&.1>Math.abs(k+b)&&.1>Math.abs(e+h+l-3))return this.set(1,0,0,0),this;a=Math.PI;e=(e+1)/2;h=(h+1)/2;l=(l+1)/2;d=(d+g)/4;f=(f+c)/4;k=(k+b)/4;e>h&&e>l?.01>e?(b=0,d=c=.707106781):(b=Math.sqrt(e),c=d/b,d=f/b):h>l?.01>h?(b=.707106781,c=0,d=.707106781):(c=Math.sqrt(h),b=d/c,d=k/c):.01>l?(c=b=.707106781,d=0):(d=Math.sqrt(l),b=f/d,c=k/d);this.set(b,c,d,a);return this}a=Math.sqrt((b-k)*(b-k)+(f-c)*(f-c)+(g-d)*(g-d));.001>Math.abs(a)&&(a=1);this.x=(b-k)/ -a;this.y=(f-c)/a;this.z=(g-d)/a;this.w=Math.acos((e+h+l-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z)); -this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new THREE.Vector4,b=new THREE.Vector4);a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);this.w=Math.ceil(this.w);return this},round:function(){this.x= -Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z* -a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z- -this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromAttribute:function(a,b,c){void 0===c&&(c=0);b=b*a.itemSize+ -c;this.x=a.array[b];this.y=a.array[b+1];this.z=a.array[b+2];this.w=a.array[b+3];return this}};THREE.Euler=function(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||THREE.Euler.DefaultOrder};THREE.Euler.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");THREE.Euler.DefaultOrder="XYZ"; -THREE.Euler.prototype={constructor:THREE.Euler,get x(){return this._x},set x(a){this._x=a;this.onChangeCallback()},get y(){return this._y},set y(a){this._y=a;this.onChangeCallback()},get z(){return this._z},set z(a){this._z=a;this.onChangeCallback()},get order(){return this._order},set order(a){this._order=a;this.onChangeCallback()},set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x, -this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=THREE.Math.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],l=e[9],m=e[2],p=e[6],e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-l,e),this._z=Math.atan2(-f,a)):(this._x=Math.atan2(p,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(l,-1,1)),.99999>Math.abs(l)? -(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-m,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(p,-1,1)),.99999>Math.abs(p)?(this._y=Math.atan2(-m,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._x=Math.atan2(p,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-l,k),this._y=Math.atan2(-m,a)):(this._x= -0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(p,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-l,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a;return function(b,c,d){void 0===a&&(a=new THREE.Matrix4);a.makeRotationFromQuaternion(b);return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a, -b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new THREE.Quaternion;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=a[0];this._y=a[1];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z; -a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new THREE.Vector3(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}};THREE.Line3=function(a,b){this.start=void 0!==a?a:new THREE.Vector3;this.end=void 0!==b?b:new THREE.Vector3}; -THREE.Line3.prototype={constructor:THREE.Line3,set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start);this.end.copy(a.end);return this},center:function(a){return(a||new THREE.Vector3).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new THREE.Vector3).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)}, -at:function(a,b){var c=b||new THREE.Vector3;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new THREE.Vector3,b=new THREE.Vector3;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);var e=b.dot(b),e=b.dot(a)/e;d&&(e=THREE.Math.clamp(e,0,1));return e}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);c=c||new THREE.Vector3;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a); -this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}};THREE.Box2=function(a,b){this.min=void 0!==a?a:new THREE.Vector2(Infinity,Infinity);this.max=void 0!==b?b:new THREE.Vector2(-Infinity,-Infinity)}; -THREE.Box2.prototype={constructor:THREE.Box2,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;bthis.max.x||a.ythis.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y?!0:!1},getParameter:function(a,b){return(b||new THREE.Vector2).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.xthis.max.x||a.max.y -this.max.y?!1:!0},clampPoint:function(a,b){return(b||new THREE.Vector2).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new THREE.Vector2;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&& -a.max.equals(this.max)}};THREE.Box3=function(a,b){this.min=void 0!==a?a:new THREE.Vector3(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new THREE.Vector3(-Infinity,-Infinity,-Infinity)}; -THREE.Box3.prototype={constructor:THREE.Box3,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.length;he&&(e=l);m>f&&(f=m);p>g&&(g=p)}this.min.set(b,c,d);this.max.set(e,f,g)},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;bthis.max.x||a.ythis.max.y||a.zthis.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z?!0:!1},getParameter:function(a,b){return(b||new THREE.Vector3).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.xthis.max.x|| -a.max.ythis.max.y||a.max.zthis.max.z?!1:!0},intersectsSphere:function(){var a;return function(b){void 0===a&&(a=new THREE.Vector3);this.clampPoint(b.center,a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){var b,c;0=a.constant},clampPoint:function(a,b){return(b||new THREE.Vector3).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new THREE.Vector3;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=new THREE.Vector3;return function(b){b=b||new THREE.Sphere;b.center= -this.center();b.radius=.5*this.size(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=[new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b); -a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a); -return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}};THREE.Matrix3=function(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1]);0this.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.elements.set(this.elements);c=1/g;var f=1/h,l=1/k;b.elements[0]*=c;b.elements[1]*=c; -b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=l;b.elements[9]*=l;b.elements[10]*=l;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makeFrustum:function(a,b,c,d,e,f){var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(d-c);g[9]=(d+c)/(d-c);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makePerspective:function(a,b,c,d){a=c*Math.tan(THREE.Math.DEG2RAD*a*.5);var e= --a;return this.makeFrustum(e*b,a*b,e,a,c,d)},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),l=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*l;g[14]=-((f+e)*l);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a){this.elements.set(a);return this},toArray:function(a,b){void 0===a&&(a=[]); -void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}};THREE.Ray=function(a,b){this.origin=void 0!==a?a:new THREE.Vector3;this.direction=void 0!==b?b:new THREE.Vector3}; -THREE.Ray.prototype={constructor:THREE.Ray,set:function(a,b){this.origin.copy(a);this.direction.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.origin.copy(a.origin);this.direction.copy(a.direction);return this},at:function(a,b){return(b||new THREE.Vector3).copy(this.direction).multiplyScalar(a).add(this.origin)},lookAt:function(a){this.direction.copy(a).sub(this.origin).normalize();return this},recast:function(){var a=new THREE.Vector3;return function(b){this.origin.copy(this.at(b, -a));return this}}(),closestPointToPoint:function(a,b){var c=b||new THREE.Vector3;c.subVectors(a,this.origin);var d=c.dot(this.direction);return 0>d?c.copy(this.origin):c.copy(this.direction).multiplyScalar(d).add(this.origin)},distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new THREE.Vector3;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin); -return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=new THREE.Vector3,b=new THREE.Vector3,c=new THREE.Vector3;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a);var h=.5*d.distanceTo(e),k=-this.direction.dot(b),l=c.dot(this.direction),m=-c.dot(b),p=c.lengthSq(),n=Math.abs(1-k*k),q;0=-q?e<=q?(h=1/n,d*=h,e*=h,k=d*(d+k*e+2*l)+e*(k*d+e+2*m)+p):(e=h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2* -m)+p):(e=-h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*m)+p):e<=-q?(d=Math.max(0,-(-k*h+l)),e=0f)return null;f=Math.sqrt(f-e);e=d-f;d+=f;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){var c= -this.distanceToPlane(a);return null===c?null:this.at(c,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c,d,e,f,g;d=1/this.direction.x;f=1/this.direction.y;g=1/this.direction.z;var h=this.origin;0<=d?(c=(a.min.x-h.x)*d,d*=a.max.x-h.x):(c=(a.max.x-h.x)*d,d*=a.min.x-h.x);0<=f?(e=(a.min.y-h.y)*f,f*=a.max.y-h.y):(e=(a.max.y-h.y)*f,f*=a.min.y-h.y);if(c>f||e>d)return null;if(e>c||c!==c)c=e;if(fg||e>d)return null;if(e>c||c!==c)c=e;if(gd?null:this.at(0<=c?c:d,b)},intersectsBox:function(){var a=new THREE.Vector3;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=new THREE.Vector3,b=new THREE.Vector3,c=new THREE.Vector3,d=new THREE.Vector3;return function(e,f,g,h,k){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d); -if(0f)h=-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null;g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,k)}}(),applyMatrix4:function(a){this.direction.add(this.origin).applyMatrix4(a);this.origin.applyMatrix4(a);this.direction.sub(this.origin);this.direction.normalize();return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}}; -THREE.Sphere=function(a,b){this.center=void 0!==a?a:new THREE.Vector3;this.radius=void 0!==b?b:0}; -THREE.Sphere.prototype={constructor:THREE.Sphere,set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new THREE.Box3;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).center(d);for(var e=0,f=0,g=b.length;f=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(this.center.dot(a.normal)-a.constant)<=this.radius},clampPoint:function(a,b){var c= -this.center.distanceToSquared(a),d=b||new THREE.Vector3;d.copy(a);c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center));return d},getBoundingBox:function(a){a=a||new THREE.Box3;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&& -a.radius===this.radius}};THREE.Frustum=function(a,b,c,d,e,f){this.planes=[void 0!==a?a:new THREE.Plane,void 0!==b?b:new THREE.Plane,void 0!==c?c:new THREE.Plane,void 0!==d?d:new THREE.Plane,void 0!==e?e:new THREE.Plane,void 0!==f?f:new THREE.Plane]}; -THREE.Frustum.prototype={constructor:THREE.Frustum,set:function(a,b,c,d,e,f){var g=this.planes;g[0].copy(a);g[1].copy(b);g[2].copy(c);g[3].copy(d);g[4].copy(e);g[5].copy(f);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){for(var b=this.planes,c=0;6>c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],l=c[7],m=c[8],p=c[9],n=c[10],q=c[11],r=c[12],s=c[13],v=c[14], -c=c[15];b[0].setComponents(f-a,l-g,q-m,c-r).normalize();b[1].setComponents(f+a,l+g,q+m,c+r).normalize();b[2].setComponents(f+d,l+h,q+p,c+s).normalize();b[3].setComponents(f-d,l-h,q-p,c-s).normalize();b[4].setComponents(f-e,l-k,q-n,c-v).normalize();b[5].setComponents(f+e,l+k,q+n,c+v).normalize();return this},intersectsObject:function(){var a=new THREE.Sphere;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(), -intersectsSprite:function(){var a=new THREE.Sphere;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d=0;6>d;d++)if(b[d].distanceToPoint(c)e;e++){var f=d[e];a.x=0g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6>c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}};THREE.Plane=function(a,b){this.normal=void 0!==a?a:new THREE.Vector3(1,0,0);this.constant=void 0!==b?b:0}; -THREE.Plane.prototype={constructor:THREE.Plane,set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a=new THREE.Vector3,b=new THREE.Vector3;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d, -c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a, -b){return this.orthoPoint(a,b).sub(a).negate()},orthoPoint:function(a,b){var c=this.distanceToPoint(a);return(b||new THREE.Vector3).copy(this.normal).multiplyScalar(c)},intersectLine:function(){var a=new THREE.Vector3;return function(b,c){var d=c||new THREE.Vector3,e=b.delta(a),f=this.normal.dot(e);if(0===f){if(0===this.distanceToPoint(b.start))return d.copy(b.start)}else return f=-(b.start.dot(this.normal)+this.constant)/f,0>f||1b&&0a&&0e;e++)8===e||13===e||18===e||23===e?b[e]="-":14===e?b[e]="4":(2>=c&&(c=33554432+16777216*Math.random()|0),d=c&15,c>>=4,b[e]=a[19===e?d&3|8:d]);return b.join("")}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c, -d,e){return d+(a-b)*(e-d)/(c-b)},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},random16:function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a* -(.5-Math.random())},degToRad:function(a){return a*THREE.Math.DEG2RAD},radToDeg:function(a){return a*THREE.Math.RAD2DEG},isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},nearestPowerOfTwo:function(a){return Math.pow(2,Math.round(Math.log(a)/Math.LN2))},nextPowerOfTwo:function(a){a--;a|=a>>1;a|=a>>2;a|=a>>4;a|=a>>8;a|=a>>16;a++;return a}}; -THREE.Spline=function(a){function b(a,b,c,d,e,f,g){a=.5*(c-a);d=.5*(d-b);return(2*(b-c)+a+d)*g+(-3*(b-c)-2*a-d)*f+a*e+b}this.points=a;var c=[],d={x:0,y:0,z:0},e,f,g,h,k,l,m,p,n;this.initFromArray=function(a){this.points=[];for(var b=0;bthis.points.length-2?this.points.length-1:f+1;c[3]=f>this.points.length-3?this.points.length-1:f+ -2;l=this.points[c[0]];m=this.points[c[1]];p=this.points[c[2]];n=this.points[c[3]];h=g*g;k=g*h;d.x=b(l.x,m.x,p.x,n.x,g,h,k);d.y=b(l.y,m.y,p.y,n.y,g,h,k);d.z=b(l.z,m.z,p.z,n.z,g,h,k);return d};this.getControlPointsArray=function(){var a,b,c=this.points.length,d=[];for(a=0;a=b.x+b.y}}(); -THREE.Triangle.prototype={constructor:THREE.Triangle,set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},area:function(){var a=new THREE.Vector3,b=new THREE.Vector3;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a, -this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new THREE.Vector3).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return THREE.Triangle.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new THREE.Plane).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return THREE.Triangle.barycoordFromPoint(a,this.a,this.b,this.c,b)},containsPoint:function(a){return THREE.Triangle.containsPoint(a,this.a,this.b,this.c)}, -closestPointToPoint:function(){var a,b,c,d;return function(e,f){void 0===a&&(a=new THREE.Plane,b=[new THREE.Line3,new THREE.Line3,new THREE.Line3],c=new THREE.Vector3,d=new THREE.Vector3);var g=f||new THREE.Vector3,h=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))g.copy(c);else{b[0].set(this.a,this.b);b[1].set(this.b,this.c);b[2].set(this.c,this.a);for(var k=0;k=e)break a;else{f=b[1];a=e)break b}d= -c;c=0}}for(;c>>1,ad;d++)if(e[d]===e[(d+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(e=a[f],this.faces.splice(e, -1),c=0,g=this.faceVertexUvs.length;cb||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0c.parameterPositions[1]&&(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0: -this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(d===THREE.LoopOnce)a:{if(-1===e&&(this.loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=d===THREE.LoopPingPong;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions, -d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a, -b,c){var d=this._interpolantSettings;c?(d.endingStart=THREE.ZeroSlopeEnding,d.endingEnd=THREE.ZeroSlopeEnding):(d.endingStart=a?this.zeroSlopeAtStart?THREE.ZeroSlopeEnding:THREE.ZeroCurvatureEnding:THREE.WrapAroundEnding,d.endingEnd=b?this.zeroSlopeAtEnd?THREE.ZeroSlopeEnding:THREE.ZeroCurvatureEnding:THREE.WrapAroundEnding)},_scheduleFading:function(a,b,c){var d=this._mixer,e=d.time,f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions; -f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}};THREE.AnimationClip=function(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=THREE.Math.generateUUID();0>this.duration&&this.resetDuration();this.trim();this.optimize()}; -THREE.AnimationClip.prototype={constructor:THREE.AnimationClip,resetDuration:function(){for(var a=0,b=0,c=this.tracks.length;b!==c;++b)var d=this.tracks[b],a=Math.max(a,d.times[d.times.length-1]);this.duration=a},trim:function(){for(var a=0;a=c){var p=c++,n=b[p];d[n.uuid]= -m;b[m]=n;d[l]=p;b[p]=k;k=0;for(l=f;k!==l;++k){var n=e[k],q=n[m];n[m]=n[p];n[p]=q}}}this.nCachedObjects_=c},uncache:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._bindings,g=f.length,h=0,k=arguments.length;h!==k;++h){var l=arguments[h].uuid,m=e[l];if(void 0!==m)if(delete e[l],mb;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,1),e=f-1),d=this.getValueSize(),this.times=THREE.AnimationUtils.arraySlice(c,e,f),this.values=THREE.AnimationUtils.arraySlice(this.values,e*d,f*d);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("invalid value size in track", -this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("track is empty",this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("time is not a valid number",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("out of order keys",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&THREE.AnimationUtils.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("value is not a valid number",this,f,d);a=!1;break}return a},optimize:function(){for(var a= -this.times,b=this.values,c=this.getValueSize(),d=1,e=1,f=a.length-1;e<=f;++e){var g=!1,h=a[e];if(h!==a[e+1]&&(1!==e||h!==h[0]))for(var k=e*c,l=k-c,m=k+c,h=0;h!==c;++h){var p=b[k+h];if(p!==b[l+h]||p!==b[m+h]){g=!0;break}}if(g){if(e!==d)for(a[d]=a[e],g=e*c,k=d*c,h=0;h!==c;++h)b[k+h]=b[g+h];++d}}d!==a.length&&(this.times=THREE.AnimationUtils.arraySlice(a,0,d),this.values=THREE.AnimationUtils.arraySlice(b,0,d*c));return this}}; -Object.assign(THREE.KeyframeTrack,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");var b=THREE.KeyframeTrack._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];THREE.AnimationUtils.flattenJSON(a.keys,c,d,"value");a.times=c;a.values=d}return void 0!==b.parse?b.parse(a):new b(a.name,a.times,a.values,a.interpolation)},toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=b.toJSON(a);else{var b={name:a.name,times:THREE.AnimationUtils.convertArray(a.times, -Array),values:THREE.AnimationUtils.convertArray(a.values,Array)},c=a.getInterpolation();c!==a.DefaultInterpolation&&(b.interpolation=c)}b.type=a.ValueTypeName;return b},_getTrackTypeForValueTypeName:function(a){switch(a.toLowerCase()){case "scalar":case "double":case "float":case "number":case "integer":return THREE.NumberKeyframeTrack;case "vector":case "vector2":case "vector3":case "vector4":return THREE.VectorKeyframeTrack;case "color":return THREE.ColorKeyframeTrack;case "quaternion":return THREE.QuaternionKeyframeTrack; -case "bool":case "boolean":return THREE.BooleanKeyframeTrack;case "string":return THREE.StringKeyframeTrack}throw Error("Unsupported typeName: "+a);}});THREE.PropertyBinding=function(a,b,c){this.path=b;this.parsedPath=c||THREE.PropertyBinding.parseTrackName(b);this.node=THREE.PropertyBinding.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}; -THREE.PropertyBinding.prototype={constructor:THREE.PropertyBinding,getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=THREE.PropertyBinding.findNode(this.rootNode,b.nodeName)||this.rootNode);this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(a){if(c){var f=b.objectIndex;switch(c){case "materials":if(!a.material){console.error(" can not bind to material as node does not have a material", -this);return}if(!a.material.materials){console.error(" can not bind to material.materials as node.material does not have a materials array",this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error(" can not bind to bones as node does not have a skeleton",this);return}a=a.skeleton.bones;for(c=0;cd&&this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a); -break}},saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d,e){THREE.Quaternion.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}}; -THREE.BooleanKeyframeTrack=function(a,b,c){THREE.KeyframeTrack.call(this,a,b,c)};THREE.BooleanKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.BooleanKeyframeTrack,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:THREE.InterpolateDiscrete,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});THREE.ColorKeyframeTrack=function(a,b,c,d){THREE.KeyframeTrack.call(this,a,b,c,d)}; -THREE.ColorKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.ColorKeyframeTrack,ValueTypeName:"color"});THREE.NumberKeyframeTrack=function(a,b,c,d){THREE.KeyframeTrack.call(this,a,b,c,d)};THREE.NumberKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.NumberKeyframeTrack,ValueTypeName:"number"});THREE.QuaternionKeyframeTrack=function(a,b,c,d){THREE.KeyframeTrack.call(this,a,b,c,d)}; -THREE.QuaternionKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.QuaternionKeyframeTrack,ValueTypeName:"quaternion",DefaultInterpolation:THREE.InterpolateLinear,InterpolantFactoryMethodLinear:function(a){return new THREE.QuaternionLinearInterpolant(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});THREE.StringKeyframeTrack=function(a,b,c,d){THREE.KeyframeTrack.call(this,a,b,c,d)}; -THREE.StringKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.StringKeyframeTrack,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:THREE.InterpolateDiscrete,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});THREE.VectorKeyframeTrack=function(a,b,c,d){THREE.KeyframeTrack.call(this,a,b,c,d)}; -THREE.VectorKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.VectorKeyframeTrack,ValueTypeName:"vector"}); -THREE.Audio=function(a){THREE.Object3D.call(this);this.type="Audio";this.context=a.context;this.source=this.context.createBufferSource();this.source.onended=this.onEnded.bind(this);this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}; -THREE.Audio.prototype=Object.assign(Object.create(THREE.Object3D.prototype),{constructor:THREE.Audio,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setBuffer:function(a){this.source.buffer=a;this.sourceType="buffer";this.autoplay&&this.play();return this},play:function(){if(!0===this.isPlaying)console.warn("THREE.Audio: Audio is already playing.");else if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control."); -else{var a=this.context.createBufferSource();a.buffer=this.source.buffer;a.loop=this.source.loop;a.onended=this.source.onended;a.start(0,this.startTime);a.playbackRate.value=this.playbackRate;this.isPlaying=!0;this.source=a;return this.connect()}},pause:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.source.stop(),this.startTime=this.context.currentTime,this.isPlaying=!1,this},stop:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control."); -else return this.source.stop(),this.startTime=0,this.isPlaying=!1,this},connect:function(){if(0k.opacity&&(k.transparent=!0);c.setTextures(h); -return c.parse(k)}}()};THREE.Loader.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;cg;g++)n=u[k++],t=v[2*n],n=v[2*n+1],t=new THREE.Vector2(t,n),2!==g&&c.faceVertexUvs[d][h].push(t), -0!==g&&c.faceVertexUvs[d][h+1].push(t);p&&(p=3*u[k++],q.normal.set(D[p++],D[p++],D[p]),s.normal.copy(q.normal));if(r)for(d=0;4>d;d++)p=3*u[k++],r=new THREE.Vector3(D[p++],D[p++],D[p]),2!==d&&q.vertexNormals.push(r),0!==d&&s.vertexNormals.push(r);m&&(m=u[k++],m=w[m],q.color.setHex(m),s.color.setHex(m));if(b)for(d=0;4>d;d++)m=u[k++],m=w[m],2!==d&&q.vertexColors.push(new THREE.Color(m)),0!==d&&s.vertexColors.push(new THREE.Color(m));c.faces.push(q);c.faces.push(s)}else{q=new THREE.Face3;q.a=u[k++];q.b= -u[k++];q.c=u[k++];h&&(h=u[k++],q.materialIndex=h);h=c.faces.length;if(d)for(d=0;dg;g++)n=u[k++],t=v[2*n],n=v[2*n+1],t=new THREE.Vector2(t,n),c.faceVertexUvs[d][h].push(t);p&&(p=3*u[k++],q.normal.set(D[p++],D[p++],D[p]));if(r)for(d=0;3>d;d++)p=3*u[k++],r=new THREE.Vector3(D[p++],D[p++],D[p]),q.vertexNormals.push(r);m&&(m=u[k++],q.color.setHex(w[m]));if(b)for(d=0;3>d;d++)m=u[k++],q.vertexColors.push(new THREE.Color(w[m]));c.faces.push(q)}})(d);(function(){var b= -void 0!==a.influencesPerVertex?a.influencesPerVertex:2;if(a.skinWeights)for(var d=0,g=a.skinWeights.length;dthis.opacity&&(d.opacity=this.opacity);!0===this.transparent&&(d.transparent=this.transparent);0a.x||1a.x?0:1;break;case THREE.MirroredRepeatWrapping:1===Math.abs(Math.floor(a.x)%2)?a.x=Math.ceil(a.x)-a.x:a.x-=Math.floor(a.x)}if(0>a.y||1a.y?0:1;break;case THREE.MirroredRepeatWrapping:1=== -Math.abs(Math.floor(a.y)%2)?a.y=Math.ceil(a.y)-a.y:a.y-=Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}};Object.assign(THREE.Texture.prototype,THREE.EventDispatcher.prototype);THREE.TextureIdCount=0; -THREE.DepthTexture=function(a,b,c,d,e,f,g,h,k){THREE.Texture.call(this,null,d,e,f,g,h,THREE.DepthFormat,c,k);this.image={width:a,height:b};this.type=void 0!==c?c:THREE.UnsignedShortType;this.magFilter=void 0!==g?g:THREE.NearestFilter;this.minFilter=void 0!==h?h:THREE.NearestFilter;this.generateMipmaps=this.flipY=!1};THREE.DepthTexture.prototype=Object.create(THREE.Texture.prototype);THREE.DepthTexture.prototype.constructor=THREE.DepthTexture; -THREE.CanvasTexture=function(a,b,c,d,e,f,g,h,k){THREE.Texture.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0};THREE.CanvasTexture.prototype=Object.create(THREE.Texture.prototype);THREE.CanvasTexture.prototype.constructor=THREE.CanvasTexture;THREE.CubeTexture=function(a,b,c,d,e,f,g,h,k,l){a=void 0!==a?a:[];b=void 0!==b?b:THREE.CubeReflectionMapping;THREE.Texture.call(this,a,b,c,d,e,f,g,h,k,l);this.flipY=!1};THREE.CubeTexture.prototype=Object.create(THREE.Texture.prototype); -THREE.CubeTexture.prototype.constructor=THREE.CubeTexture;Object.defineProperty(THREE.CubeTexture.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});THREE.CompressedTexture=function(a,b,c,d,e,f,g,h,k,l,m,p){THREE.Texture.call(this,null,f,g,h,k,l,d,e,m,p);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1};THREE.CompressedTexture.prototype=Object.create(THREE.Texture.prototype);THREE.CompressedTexture.prototype.constructor=THREE.CompressedTexture; -THREE.DataTexture=function(a,b,c,d,e,f,g,h,k,l,m,p){THREE.Texture.call(this,null,f,g,h,k,l,d,e,m,p);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:THREE.NearestFilter;this.minFilter=void 0!==l?l:THREE.NearestFilter;this.generateMipmaps=this.flipY=!1};THREE.DataTexture.prototype=Object.create(THREE.Texture.prototype);THREE.DataTexture.prototype.constructor=THREE.DataTexture; -THREE.VideoTexture=function(a,b,c,d,e,f,g,h,k){function l(){requestAnimationFrame(l);a.readyState>=a.HAVE_CURRENT_DATA&&(m.needsUpdate=!0)}THREE.Texture.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var m=this;l()};THREE.VideoTexture.prototype=Object.create(THREE.Texture.prototype);THREE.VideoTexture.prototype.constructor=THREE.VideoTexture;THREE.Group=function(){THREE.Object3D.call(this);this.type="Group"};THREE.Group.prototype=Object.assign(Object.create(THREE.Object3D.prototype),{constructor:THREE.Group}); -THREE.Points=function(a,b){THREE.Object3D.call(this);this.type="Points";this.geometry=void 0!==a?a:new THREE.BufferGeometry;this.material=void 0!==b?b:new THREE.PointsMaterial({color:16777215*Math.random()})}; -THREE.Points.prototype=Object.assign(Object.create(THREE.Object3D.prototype),{constructor:THREE.Points,raycast:function(){var a=new THREE.Matrix4,b=new THREE.Ray,c=new THREE.Sphere;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(fd.far||e.push({distance:l,distanceToRay:Math.sqrt(f),point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,l=d.params.Points.threshold; -null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var l=l/((this.scale.x+this.scale.y+this.scale.z)/3),m=l*l,l=new THREE.Vector3;if(h instanceof THREE.BufferGeometry){var p=h.index,h=h.attributes.position.array;if(null!==p)for(var n=p.array,p=0,q=n.length;pf||(m.applyMatrix4(this.matrixWorld),s=d.ray.origin.distanceTo(m),sd.far||e.push({distance:s,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,r= -q.length/3-1;gf||(m.applyMatrix4(this.matrixWorld),s=d.ray.origin.distanceTo(m),sd.far||e.push({distance:s,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g instanceof THREE.Geometry)for(k=g.vertices,l=k.length,g=0;gf||(m.applyMatrix4(this.matrixWorld),s=d.ray.origin.distanceTo(m),sd.far|| -e.push({distance:s,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});THREE.LineSegments=function(a,b){THREE.Line.call(this,a,b);this.type="LineSegments"};THREE.LineSegments.prototype=Object.assign(Object.create(THREE.Line.prototype),{constructor:THREE.LineSegments}); -THREE.Mesh=function(a,b){THREE.Object3D.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new THREE.BufferGeometry;this.material=void 0!==b?b:new THREE.MeshBasicMaterial({color:16777215*Math.random()});this.drawMode=THREE.TrianglesDrawMode;this.updateMorphTargets()}; -THREE.Mesh.prototype=Object.assign(Object.create(THREE.Object3D.prototype),{constructor:THREE.Mesh,setDrawMode:function(a){this.drawMode=a},copy:function(a){THREE.Object3D.prototype.copy.call(this,a);this.drawMode=a.drawMode;return this},updateMorphTargets:function(){if(void 0!==this.geometry.morphTargets&&0b.far?null:{distance:c,point:t.clone(),object:a}}function c(c,d,e,f,l,p,m,s){g.fromArray(f,3*p);h.fromArray(f,3*m);k.fromArray(f,3*s);if(c=b(c,d,e,g,h,k,v))l&&(n.fromArray(l,2*p),q.fromArray(l,2*m),r.fromArray(l,2*s),c.uv=a(v,g,h,k,n,q,r)),c.face=new THREE.Face3(p, -m,s,THREE.Triangle.normal(g,h,k)),c.faceIndex=p;return c}var d=new THREE.Matrix4,e=new THREE.Ray,f=new THREE.Sphere,g=new THREE.Vector3,h=new THREE.Vector3,k=new THREE.Vector3,l=new THREE.Vector3,m=new THREE.Vector3,p=new THREE.Vector3,n=new THREE.Vector2,q=new THREE.Vector2,r=new THREE.Vector2,s=new THREE.Vector3,v=new THREE.Vector3,t=new THREE.Vector3;return function(u,s){var w=this.geometry,t=this.material,z=this.matrixWorld;if(void 0!==t&&(null===w.boundingSphere&&w.computeBoundingSphere(),f.copy(w.boundingSphere), -f.applyMatrix4(z),!1!==u.ray.intersectsSphere(f)&&(d.getInverse(z),e.copy(u.ray).applyMatrix4(d),null===w.boundingBox||!1!==e.intersectsBox(w.boundingBox)))){var y,A;if(w instanceof THREE.BufferGeometry){var G,B,t=w.index,z=w.attributes,w=z.position.array;void 0!==z.uv&&(y=z.uv.array);if(null!==t)for(var z=t.array,F=0,J=z.length;F= -d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;for(;ethis.scale.x*this.scale.y/4||c.push({distance:Math.sqrt(d),point:this.position,face:null,object:this})}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}}); -THREE.LensFlare=function(a,b,c,d,e){THREE.Object3D.call(this);this.lensFlares=[];this.positionScreen=new THREE.Vector3;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}; -THREE.LensFlare.prototype=Object.assign(Object.create(THREE.Object3D.prototype),{constructor:THREE.LensFlare,copy:function(a){THREE.Object3D.prototype.copy.call(this,a);this.positionScreen.copy(a.positionScreen);this.customUpdateCallback=a.customUpdateCallback;for(var b=0,c=a.lensFlares.length;b=ca.maxTextures&&console.warn("WebGLRenderer: trying to use "+a+" texture units while this GPU supports only "+ca.maxTextures); -ga+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b instanceof THREE.WebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);la.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);la.setTexture2D(b,c)}}();this.setTextureCube=function(){var a= -!1;return function(b,c){b instanceof THREE.WebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b instanceof THREE.CubeTexture||Array.isArray(b.image)&&6===b.image.length?la.setTextureCube(b,c):la.setTextureCubeDynamic(b,c)}}();this.getCurrentRenderTarget=function(){return C};this.setRenderTarget=function(a){(C=a)&&void 0===Y.get(a).__webglFramebuffer&&la.setupRenderTarget(a); -var b=a instanceof THREE.WebGLRenderTargetCube,c;a?(c=Y.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,X.copy(a.scissor),ea=a.scissorTest,fa.copy(a.viewport)):(c=null,X.copy(ua).multiplyScalar(Z),ea=xa,fa.copy(na).multiplyScalar(Z));L!==c&&(x.bindFramebuffer(x.FRAMEBUFFER,c),L=c);R.scissor(X);R.setScissorTest(ea);R.viewport(fa);b&&(b=Y.get(a.texture),x.framebufferTexture2D(x.FRAMEBUFFER,x.COLOR_ATTACHMENT0,x.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,b.__webglTexture,a.activeMipMapLevel))}; -this.readRenderTargetPixels=function(a,b,c,d,e,g){if(!1===a instanceof THREE.WebGLRenderTarget)console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");else{var f=Y.get(a).__webglFramebuffer;if(f){var h=!1;f!==L&&(x.bindFramebuffer(x.FRAMEBUFFER,f),h=!0);try{var k=a.texture;k.format!==THREE.RGBAFormat&&t(k.format)!==x.getParameter(x.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."): -k.type===THREE.UnsignedByteType||t(k.type)===x.getParameter(x.IMPLEMENTATION_COLOR_READ_TYPE)||k.type===THREE.FloatType&&U.get("WEBGL_color_buffer_float")||k.type===THREE.HalfFloatType&&U.get("EXT_color_buffer_half_float")?x.checkFramebufferStatus(x.FRAMEBUFFER)===x.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&x.readPixels(b,c,d,e,t(k.format),t(k.type),g):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&& -x.bindFramebuffer(x.FRAMEBUFFER,L)}}}}}; -THREE.WebGLRenderTarget=function(a,b,c){this.uuid=THREE.Math.generateUUID();this.width=a;this.height=b;this.scissor=new THREE.Vector4(0,0,a,b);this.scissorTest=!1;this.viewport=new THREE.Vector4(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=THREE.LinearFilter);this.texture=new THREE.Texture(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer: -!0;this.depthTexture=null}; -Object.assign(THREE.WebGLRenderTarget.prototype,THREE.EventDispatcher.prototype,{setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture; -return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});THREE.WebGLRenderTargetCube=function(a,b,c){THREE.WebGLRenderTarget.call(this,a,b,c);this.activeMipMapLevel=this.activeCubeFace=0};THREE.WebGLRenderTargetCube.prototype=Object.create(THREE.WebGLRenderTarget.prototype);THREE.WebGLRenderTargetCube.prototype.constructor=THREE.WebGLRenderTargetCube; -THREE.WebGLBufferRenderer=function(a,b,c){var d;this.setMode=function(a){d=a};this.render=function(b,f){a.drawArrays(d,b,f);c.calls++;c.vertices+=f;d===a.TRIANGLES&&(c.faces+=f/3)};this.renderInstances=function(e){var f=b.get("ANGLE_instanced_arrays");if(null===f)console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{var g=e.attributes.position,h=0,h=g instanceof THREE.InterleavedBufferAttribute?g.data.count: -g.count;f.drawArraysInstancedANGLE(d,0,h,e.maxInstancedCount);c.calls++;c.vertices+=h*e.maxInstancedCount;d===a.TRIANGLES&&(c.faces+=e.maxInstancedCount*h/3)}}}; -THREE.WebGLClipping=function(){function a(){l.value!==d&&(l.value=d,l.needsUpdate=0c){var d=b;b=c;c=d}d=a[b];return void 0===d?(a[b]=[c],!0):-1===d.indexOf(c)?(d.push(c),!0):!1}var f=new THREE.WebGLGeometries(a,b,c);this.getAttributeBuffer=function(a){return a instanceof THREE.InterleavedBufferAttribute?b.get(a.data).__webglBuffer:b.get(a).__webglBuffer};this.getWireframeAttribute= -function(c){var f=b.get(c);if(void 0!==f.wireframe)return f.wireframe;var k=[],l=c.index,m=c.attributes;c=m.position;if(null!==l)for(var m={},l=l.array,p=0,n=l.length;p/g,function(a,b){var c=THREE.ShaderChunk[b];if(void 0===c)throw Error("Can not resolve #include <"+ -b+">");return k(c)})}function l(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,b,c,d){a="";for(b=parseInt(b);bb||a.height>b){var c=b/Math.max(a.width,a.height),d=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");d.width=Math.floor(a.width*c);d.height=Math.floor(a.height*c);d.getContext("2d").drawImage(a,0,0,a.width,a.height,0,0,d.width,d.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a}function k(a){return THREE.Math.isPowerOfTwo(a.width)&&THREE.Math.isPowerOfTwo(a.height)} -function l(b){return b===THREE.NearestFilter||b===THREE.NearestMipMapNearestFilter||b===THREE.NearestMipMapLinearFilter?a.NEAREST:a.LINEAR}function m(b){b=b.target;b.removeEventListener("dispose",m);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.delete(b)}v.textures--}function p(b){b=b.target;b.removeEventListener("dispose",p);var c=d.get(b),e=d.get(b.texture);if(b){void 0!== -e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b instanceof THREE.WebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.delete(b.texture);d.delete(b)}v.textures--}function n(b,g){var l=d.get(b);if(0s;s++)r[s]= -n||p?p?b.image[s].image:b.image[s]:h(b.image[s],e.maxCubemapSize);var t=k(r[0]),B=f(b.format),F=f(b.type);q(a.TEXTURE_CUBE_MAP,b,t);for(s=0;6>s;s++)if(n)for(var J,P=r[s].mipmaps,K=0,H=P.length;Kl;l++)e.__webglFramebuffer[l]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(g){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);q(a.TEXTURE_CUBE_MAP,b.texture,h);for(l= -0;6>l;l++)r(e.__webglFramebuffer[l],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+l);b.texture.generateMipmaps&&h&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),q(a.TEXTURE_2D,b.texture,h),r(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),b.texture.generateMipmaps&&h&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=b instanceof THREE.WebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets"); -if(b instanceof THREE.WebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported!");a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer);if(!(b.depthTexture instanceof THREE.DepthTexture))throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate= -!0);n(b.depthTexture,0);b=d.get(b.depthTexture).__webglTexture;a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.TEXTURE_2D,b,0)}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),s(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),s(e.__webglDepthbuffer,b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap= -function(b){var e=b.texture;e.generateMipmaps&&k(b)&&e.minFilter!==THREE.NearestFilter&&e.minFilter!==THREE.LinearFilter&&(b=b instanceof THREE.WebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}; -THREE.WebGLUniforms=function(){var a=new THREE.Texture,b=new THREE.CubeTexture,c=[],d=[],e=function(a,b,d){var e=a[0];if(0>=e||0 0 ) {\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\nfloat fogFactor = 0.0;\nif ( fogType == 1 ) {\nfogFactor = smoothstep( fogNear, fogFar, depth );\n} else {\nconst float LOG2 = 1.442695;\nfogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\nfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n}\ngl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n}\n}"].join("\n")); -w.compileShader(M);w.compileShader(O);w.attachShader(H,M);w.attachShader(H,O);w.linkProgram(H);A=H;t=w.getAttribLocation(A,"position");u=w.getAttribLocation(A,"uv");c=w.getUniformLocation(A,"uvOffset");d=w.getUniformLocation(A,"uvScale");e=w.getUniformLocation(A,"rotation");f=w.getUniformLocation(A,"scale");g=w.getUniformLocation(A,"color");h=w.getUniformLocation(A,"map");k=w.getUniformLocation(A,"opacity");l=w.getUniformLocation(A,"modelViewMatrix");m=w.getUniformLocation(A,"projectionMatrix");p= -w.getUniformLocation(A,"fogType");n=w.getUniformLocation(A,"fogDensity");q=w.getUniformLocation(A,"fogNear");r=w.getUniformLocation(A,"fogFar");s=w.getUniformLocation(A,"fogColor");v=w.getUniformLocation(A,"alphaTest");H=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");H.width=8;H.height=8;M=H.getContext("2d");M.fillStyle="white";M.fillRect(0,0,8,8);G=new THREE.Texture(H);G.needsUpdate=!0}w.useProgram(A);I.initAttributes();I.enableAttribute(t);I.enableAttribute(u);I.disableUnusedAttributes(); -I.disable(w.CULL_FACE);I.enable(w.BLEND);w.bindBuffer(w.ARRAY_BUFFER,z);w.vertexAttribPointer(t,2,w.FLOAT,!1,16,0);w.vertexAttribPointer(u,2,w.FLOAT,!1,16,8);w.bindBuffer(w.ELEMENT_ARRAY_BUFFER,y);w.uniformMatrix4fv(m,!1,K.projectionMatrix.elements);I.activeTexture(w.TEXTURE0);w.uniform1i(h,0);M=H=0;(O=P.fog)?(w.uniform3f(s,O.color.r,O.color.g,O.color.b),O instanceof THREE.Fog?(w.uniform1f(q,O.near),w.uniform1f(r,O.far),w.uniform1i(p,1),M=H=1):O instanceof THREE.FogExp2&&(w.uniform1f(n,O.density), -w.uniform1i(p,2),M=H=2)):(w.uniform1i(p,0),M=H=0);for(var O=0,N=b.length;Oc)return null;var d=[],e=[],f=[],g,h,k;if(0=l--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");break}g=h;c<=g&&(g=0);h=g+1;c<=h&&(h=0);k=h+1;c<=k&&(k=0);var m;a:{var p= -m=void 0,n=void 0,q=void 0,r=void 0,s=void 0,v=void 0,t=void 0,u=void 0,p=a[e[g]].x,n=a[e[g]].y,q=a[e[h]].x,r=a[e[h]].y,s=a[e[k]].x,v=a[e[k]].y;if(Number.EPSILON>(q-p)*(v-n)-(r-n)*(s-p))m=!1;else{var D=void 0,w=void 0,I=void 0,z=void 0,y=void 0,A=void 0,G=void 0,B=void 0,F=void 0,J=void 0,F=B=G=u=t=void 0,D=s-q,w=v-r,I=p-s,z=n-v,y=q-p,A=r-n;for(m=0;m=-Number.EPSILON&& -B>=-Number.EPSILON&&G>=-Number.EPSILON)){m=!1;break a}m=!0}}if(m){d.push([a[e[g]],a[e[h]],a[e[k]]]);f.push([e[g],e[h],e[k]]);g=h;for(k=h+1;kNumber.EPSILON){if(0G||G>p)return[];k=l*m-k*n;if(0>k||k>p)return[]}else{if(0c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,l]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0e&&(e=d);var g=a+1;g>d&&(g=0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-1;e=b-1;0>e&&(e=d);g=b+1;g>d&&(g=0);return(d=f(k[b],k[e],k[g],h[a]))?!0:!1}function d(a,b){var c,f;for(c=0;cH){console.log("Infinite Loop! Holes left:"+l.length+", Probably Hole outside Shape!");break}for(n=F;nk;k++)m=l[k].x+":"+l[k].y,m=p[m],void 0!==m&&(l[k]=m);return n.concat()},isClockWise:function(a){return 0>THREE.ShapeUtils.area(a)},b2:function(){return function(a,b,c,d){var e= -1-a;return e*e*b+2*(1-a)*a*c+a*a*d}}(),b3:function(){return function(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}}()};THREE.Curve=function(){}; -THREE.Curve.prototype={constructor:THREE.Curve,getPoint:function(a){console.warn("THREE.Curve: Warning, getPoint() not implemented!");return null},getPointAt:function(a){a=this.getUtoTmapping(a);return this.getPoint(a)},getPoints:function(a){a||(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));return b},getSpacedPoints:function(a){a||(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPointAt(c/a));return b},getLength:function(){var a=this.getLengths();return a[a.length-1]},getLengths:function(a){a|| -(a=this.__arcLengthDivisions?this.__arcLengthDivisions:200);if(this.cacheArcLengths&&this.cacheArcLengths.length===a+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var b=[],c,d=this.getPoint(0),e,f=0;b.push(0);for(e=1;e<=a;e++)c=this.getPoint(e/a),f+=c.distanceTo(d),b.push(f),d=c;return this.cacheArcLengths=b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,b){var c=this.getLengths(),d=0,e=c.length,f;f=b?b:a*c[e-1];for(var g=0,h=e- -1,k;g<=h;)if(d=Math.floor(g+(h-g)/2),k=c[d]-f,0>k)g=d+1;else if(0b&&(b=0);1=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},getLength:function(){var a= -this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=!0;this.cacheLengths=null;this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;cNumber.EPSILON){if(0>l&&(g=b[f],k=-k,h=b[e],l=-l),!(a.yh.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=l*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=THREE.ShapeUtils.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);var g, -h,k,l=[];if(1===f.length)return h=f[0],k=new THREE.Shape,k.curves=h.curves,l.push(k),l;var m=!e(f[0].getPoints()),m=a?!m:m;k=[];var p=[],n=[],q=0,r;p[q]=void 0;n[q]=[];for(var s=0,v=f.length;sb.length-2?b.length-1:c+1],b=b[c>b.length-3?b.length-1:c+2],c=THREE.CurveUtils.interpolate;return new THREE.Vector2(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a))}; -THREE.EllipseCurve=function(a,b,c,d,e,f,g,h){this.aX=a;this.aY=b;this.xRadius=c;this.yRadius=d;this.aStartAngle=e;this.aEndAngle=f;this.aClockwise=g;this.aRotation=h||0};THREE.EllipseCurve.prototype=Object.create(THREE.Curve.prototype);THREE.EllipseCurve.prototype.constructor=THREE.EllipseCurve; -THREE.EllipseCurve.prototype.getPoint=function(a){for(var b=2*Math.PI,c=this.aEndAngle-this.aStartAngle,d=Math.abs(c)c;)c+=b;for(;c>b;)c-=b;cb.length-2?b.length-1:c+1],b=b[c>b.length-3?b.length-1:c+2],c=THREE.CurveUtils.interpolate;return new THREE.Vector3(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a),c(d.z,e.z,f.z,b.z,a))}); -THREE.CatmullRomCurve3=function(){function a(){}var b=new THREE.Vector3,c=new a,d=new a,e=new a;a.prototype.init=function(a,b,c,d){this.c0=a;this.c1=c;this.c2=-3*a+3*b-2*c-d;this.c3=2*a-2*b+c+d};a.prototype.initNonuniformCatmullRom=function(a,b,c,d,e,m,p){a=((b-a)/e-(c-a)/(e+m)+(c-b)/m)*m;d=((c-b)/m-(d-b)/(m+p)+(d-c)/p)*m;this.init(b,c,a,d)};a.prototype.initCatmullRom=function(a,b,c,d,e){this.init(b,c,e*(c-a),e*(d-b))};a.prototype.calc=function(a){var b=a*a;return this.c0+this.c1*a+this.c2*b+this.c3* -b*a};return THREE.Curve.create(function(a){this.points=a||[];this.closed=!1},function(a){var g=this.points,h,k;k=g.length;2>k&&console.log("duh, you need at least 2 points");a*=k-(this.closed?0:1);h=Math.floor(a);a-=h;this.closed?h+=0h&&(h=1);1E-4>k&&(k=h);1E-4>n&&(n=h);c.initNonuniformCatmullRom(l.x,m.x,p.x,g.x,k,h,n);d.initNonuniformCatmullRom(l.y,m.y,p.y,g.y,k,h,n);e.initNonuniformCatmullRom(l.z,m.z,p.z,g.z,k,h,n)}else"catmullrom"===this.type&&(k=void 0!==this.tension?this.tension:.5,c.initCatmullRom(l.x,m.x,p.x,g.x, -k),d.initCatmullRom(l.y,m.y,p.y,g.y,k),e.initCatmullRom(l.z,m.z,p.z,g.z,k));return new THREE.Vector3(c.calc(a),d.calc(a),e.calc(a))})}();THREE.ClosedSplineCurve3=function(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.");THREE.CatmullRomCurve3.call(this,a);this.type="catmullrom";this.closed=!0};THREE.ClosedSplineCurve3.prototype=Object.create(THREE.CatmullRomCurve3.prototype); -THREE.BoxGeometry=function(a,b,c,d,e,f){THREE.Geometry.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new THREE.BoxBufferGeometry(a,b,c,d,e,f));this.mergeVertices()};THREE.BoxGeometry.prototype=Object.create(THREE.Geometry.prototype);THREE.BoxGeometry.prototype.constructor=THREE.BoxGeometry;THREE.CubeGeometry=THREE.BoxGeometry; -THREE.BoxBufferGeometry=function(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,k,l,J,P){var K=f/l,H=g/J,M=f/2,O=g/2,N=k/2;g=l+1;for(var Q=J+1,C=f=0,L=new THREE.Vector3,E=0;En;n++){e[0]=p[g[n]];e[1]=p[g[(n+1)%3]];e.sort(c);var q=e.toString();void 0===f[q]?f[q]={vert1:e[0],vert2:e[1],face1:l, -face2:void 0}:f[q].face2=l}e=[];for(q in f)if(g=f[q],void 0===g.face2||h[g.face1].normal.dot(h[g.face2].normal)<=d)l=k[g.vert1],e.push(l.x),e.push(l.y),e.push(l.z),l=k[g.vert2],e.push(l.x),e.push(l.y),e.push(l.z);this.addAttribute("position",new THREE.BufferAttribute(new Float32Array(e),3))};THREE.EdgesGeometry.prototype=Object.create(THREE.BufferGeometry.prototype);THREE.EdgesGeometry.prototype.constructor=THREE.EdgesGeometry; -THREE.ExtrudeGeometry=function(a,b){"undefined"!==typeof a&&(THREE.Geometry.call(this),this.type="ExtrudeGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeFaceNormals())};THREE.ExtrudeGeometry.prototype=Object.create(THREE.Geometry.prototype);THREE.ExtrudeGeometry.prototype.constructor=THREE.ExtrudeGeometry;THREE.ExtrudeGeometry.prototype.addShapeList=function(a,b){for(var c=a.length,d=0;dNumber.EPSILON){var k=Math.sqrt(h),l=Math.sqrt(f*f+g*g),h=b.x-e/k;b=b.y+d/k;f=((c.x-g/l-h)*g-(c.y+f/l-b)*f)/(d*g-e*f);c=h+d*f-a.x;a=b+e*f-a.y;d=c*c+a*a;if(2>=d)return new THREE.Vector2(c,a);d=Math.sqrt(d/2)}else a=!1,d>Number.EPSILON? -f>Number.EPSILON&&(a=!0):d<-Number.EPSILON?f<-Number.EPSILON&&(a=!0):Math.sign(e)===Math.sign(g)&&(a=!0),a?(c=-e,a=d,d=Math.sqrt(h)):(c=d,a=e,d=Math.sqrt(h/2));return new THREE.Vector2(c/d,a/d)}function e(a,b){var c,d;for(E=a.length;0<=--E;){c=E;d=E-1;0>d&&(d=a.length-1);for(var e=0,f=q+2*m,e=0;eMath.abs(b.y-c.y)?[new THREE.Vector2(b.x,1-b.z),new THREE.Vector2(c.x,1-c.z),new THREE.Vector2(d.x,1-d.z),new THREE.Vector2(e.x,1-e.z)]:[new THREE.Vector2(b.y,1-b.z),new THREE.Vector2(c.y,1-c.z),new THREE.Vector2(d.y, -1-d.z),new THREE.Vector2(e.y,1-e.z)]}};THREE.ShapeGeometry=function(a,b){THREE.Geometry.call(this);this.type="ShapeGeometry";!1===Array.isArray(a)&&(a=[a]);this.addShapeList(a,b);this.computeFaceNormals()};THREE.ShapeGeometry.prototype=Object.create(THREE.Geometry.prototype);THREE.ShapeGeometry.prototype.constructor=THREE.ShapeGeometry;THREE.ShapeGeometry.prototype.addShapeList=function(a,b){for(var c=0,d=a.length;cNumber.EPSILON&&(h.normalize(),d=Math.acos(THREE.Math.clamp(e[l-1].dot(e[l]),-1,1)),f[l].applyMatrix4(k.makeRotationAxis(h,d))),g[l].crossVectors(e[l],f[l]);if(c)for(d=Math.acos(THREE.Math.clamp(f[0].dot(f[b-1]),-1,1)),d/=b-1,0c&&1===a.x&&(a=new THREE.Vector2(a.x-1,a.y));0===b.x&&0===b.z&&(a=new THREE.Vector2(c/2/Math.PI+.5,a.y)); -return a.clone()}THREE.Geometry.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;d=d||0;for(var k=this,l=0,m=a.length;lq&&(.2>d&&(b[0].x+=1),.2>a&&(b[1].x+=1),.2>p&&(b[2].x+=1));l=0;for(m=this.vertices.length;lp;p++){c[0]=m[e[p]];c[1]=m[e[(p+1)%3]];c.sort(b);var n=c.toString();void 0===d[n]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[n]=!0,h++)}c=new Float32Array(6*h);a=0;for(l=h;ap;p++)d=f[k[2*a+p]],h=6*a+3*p,c[h+0]=d.x,c[h+1]=d.y, -c[h+2]=d.z;this.addAttribute("position",new THREE.BufferAttribute(c,3))}else if(a instanceof THREE.BufferGeometry){if(null!==a.index){l=a.index.array;f=a.attributes.position;e=a.groups;h=0;0===e.length&&a.addGroup(0,l.length);k=new Uint32Array(2*l.length);g=0;for(m=e.length;gp;p++)c[0]=l[a+p],c[1]=l[a+(p+1)%3],c.sort(b),n=c.toString(),void 0===d[n]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[n]=!0,h++)}c=new Float32Array(6*h);a=0;for(l=h;a< -l;a++)for(p=0;2>p;p++)h=6*a+3*p,d=k[2*a+p],c[h+0]=f.getX(d),c[h+1]=f.getY(d),c[h+2]=f.getZ(d)}else for(f=a.attributes.position.array,h=f.length/3,k=h/3,c=new Float32Array(6*h),a=0,l=k;ap;p++)h=18*a+6*p,k=9*a+3*p,c[h+0]=f[k],c[h+1]=f[k+1],c[h+2]=f[k+2],d=9*a+(p+1)%3*3,c[h+3]=f[d],c[h+4]=f[d+1],c[h+5]=f[d+2];this.addAttribute("position",new THREE.BufferAttribute(c,3))}};THREE.WireframeGeometry.prototype=Object.create(THREE.BufferGeometry.prototype); -THREE.WireframeGeometry.prototype.constructor=THREE.WireframeGeometry;THREE.AxisHelper=function(a){a=a||1;var b=new Float32Array([0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a]),c=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]);a=new THREE.BufferGeometry;a.addAttribute("position",new THREE.BufferAttribute(b,3));a.addAttribute("color",new THREE.BufferAttribute(c,3));b=new THREE.LineBasicMaterial({vertexColors:THREE.VertexColors});THREE.LineSegments.call(this,a,b)};THREE.AxisHelper.prototype=Object.create(THREE.LineSegments.prototype); -THREE.AxisHelper.prototype.constructor=THREE.AxisHelper; -THREE.ArrowHelper=function(){var a=new THREE.BufferGeometry;a.addAttribute("position",new THREE.Float32Attribute([0,0,0,0,1,0],3));var b=new THREE.CylinderBufferGeometry(0,.5,1,5,1);b.translate(0,-.5,0);return function(c,d,e,f,g,h){THREE.Object3D.call(this);void 0===f&&(f=16776960);void 0===e&&(e=1);void 0===g&&(g=.2*e);void 0===h&&(h=.2*g);this.position.copy(d);this.line=new THREE.Line(a,new THREE.LineBasicMaterial({color:f}));this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new THREE.Mesh(b, -new THREE.MeshBasicMaterial({color:f}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(c);this.setLength(e,g,h)}}();THREE.ArrowHelper.prototype=Object.create(THREE.Object3D.prototype);THREE.ArrowHelper.prototype.constructor=THREE.ArrowHelper; -THREE.ArrowHelper.prototype.setDirection=function(){var a=new THREE.Vector3,b;return function(c){.99999c.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();THREE.ArrowHelper.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix();this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()}; -THREE.ArrowHelper.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};THREE.BoxHelper=function(a,b){void 0===b&&(b=16776960);var c=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),d=new Float32Array(24),e=new THREE.BufferGeometry;e.setIndex(new THREE.BufferAttribute(c,1));e.addAttribute("position",new THREE.BufferAttribute(d,3));THREE.LineSegments.call(this,e,new THREE.LineBasicMaterial({color:b}));void 0!==a&&this.update(a)}; -THREE.BoxHelper.prototype=Object.create(THREE.LineSegments.prototype);THREE.BoxHelper.prototype.constructor=THREE.BoxHelper; -THREE.BoxHelper.prototype.update=function(){var a=new THREE.Box3;return function(b){b instanceof THREE.Box3?a.copy(b):a.setFromObject(b);if(!a.isEmpty()){b=a.min;var c=a.max,d=this.geometry.attributes.position,e=d.array;e[0]=c.x;e[1]=c.y;e[2]=c.z;e[3]=b.x;e[4]=c.y;e[5]=c.z;e[6]=b.x;e[7]=b.y;e[8]=c.z;e[9]=c.x;e[10]=b.y;e[11]=c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=b.x;e[16]=c.y;e[17]=b.z;e[18]=b.x;e[19]=b.y;e[20]=b.z;e[21]=c.x;e[22]=b.y;e[23]=b.z;d.needsUpdate=!0;this.geometry.computeBoundingSphere()}}}(); -THREE.BoundingBoxHelper=function(a,b){var c=void 0!==b?b:8947848;this.object=a;this.box=new THREE.Box3;THREE.Mesh.call(this,new THREE.BoxGeometry(1,1,1),new THREE.MeshBasicMaterial({color:c,wireframe:!0}))};THREE.BoundingBoxHelper.prototype=Object.create(THREE.Mesh.prototype);THREE.BoundingBoxHelper.prototype.constructor=THREE.BoundingBoxHelper;THREE.BoundingBoxHelper.prototype.update=function(){this.box.setFromObject(this.object);this.box.size(this.scale);this.box.center(this.position)}; -THREE.CameraHelper=function(a){function b(a,b,d){c(a,d);c(b,d)}function c(a,b){d.vertices.push(new THREE.Vector3);d.colors.push(new THREE.Color(b));void 0===f[a]&&(f[a]=[]);f[a].push(d.vertices.length-1)}var d=new THREE.Geometry,e=new THREE.LineBasicMaterial({color:16777215,vertexColors:THREE.FaceColors}),f={};b("n1","n2",16755200);b("n2","n4",16755200);b("n4","n3",16755200);b("n3","n1",16755200);b("f1","f2",16755200);b("f2","f4",16755200);b("f4","f3",16755200);b("f3","f1",16755200);b("n1","f1",16755200); -b("n2","f2",16755200);b("n3","f3",16755200);b("n4","f4",16755200);b("p","n1",16711680);b("p","n2",16711680);b("p","n3",16711680);b("p","n4",16711680);b("u1","u2",43775);b("u2","u3",43775);b("u3","u1",43775);b("c","t",16777215);b("p","c",3355443);b("cn1","cn2",3355443);b("cn3","cn4",3355443);b("cf1","cf2",3355443);b("cf3","cf4",3355443);THREE.LineSegments.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate= -!1;this.pointMap=f;this.update()};THREE.CameraHelper.prototype=Object.create(THREE.LineSegments.prototype);THREE.CameraHelper.prototype.constructor=THREE.CameraHelper; -THREE.CameraHelper.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);a=c[a];if(void 0!==a)for(g=0,h=a.length;gd;d++)c.faces[d].color=this.colors[4>d?0:1];d=new THREE.MeshBasicMaterial({vertexColors:THREE.FaceColors,wireframe:!0});this.lightSphere=new THREE.Mesh(c,d);this.add(this.lightSphere);this.update()}; -THREE.HemisphereLightHelper.prototype=Object.create(THREE.Object3D.prototype);THREE.HemisphereLightHelper.prototype.constructor=THREE.HemisphereLightHelper;THREE.HemisphereLightHelper.prototype.dispose=function(){this.lightSphere.geometry.dispose();this.lightSphere.material.dispose()}; -THREE.HemisphereLightHelper.prototype.update=function(){var a=new THREE.Vector3;return function(){this.colors[0].copy(this.light.color).multiplyScalar(this.light.intensity);this.colors[1].copy(this.light.groundColor).multiplyScalar(this.light.intensity);this.lightSphere.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate());this.lightSphere.geometry.colorsNeedUpdate=!0}}(); -THREE.PointLightHelper=function(a,b){this.light=a;this.light.updateMatrixWorld();var c=new THREE.SphereBufferGeometry(b,4,2),d=new THREE.MeshBasicMaterial({wireframe:!0,fog:!1});d.color.copy(this.light.color).multiplyScalar(this.light.intensity);THREE.Mesh.call(this,c,d);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1};THREE.PointLightHelper.prototype=Object.create(THREE.Mesh.prototype);THREE.PointLightHelper.prototype.constructor=THREE.PointLightHelper; -THREE.PointLightHelper.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};THREE.PointLightHelper.prototype.update=function(){this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)}; -THREE.SkeletonHelper=function(a){this.bones=this.getBoneList(a);for(var b=new THREE.Geometry,c=0;cc;c++,d++){var e=c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new THREE.Float32Attribute(b,3));b=new THREE.LineBasicMaterial({fog:!1});this.cone=new THREE.LineSegments(a, -b);this.add(this.cone);this.update()};THREE.SpotLightHelper.prototype=Object.create(THREE.Object3D.prototype);THREE.SpotLightHelper.prototype.constructor=THREE.SpotLightHelper;THREE.SpotLightHelper.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()}; -THREE.SpotLightHelper.prototype.update=function(){var a=new THREE.Vector3,b=new THREE.Vector3;return function(){var c=this.light.distance?this.light.distance:1E3,d=c*Math.tan(this.light.angle);this.cone.scale.set(d,d,c);a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(b.sub(a));this.cone.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)}}(); -THREE.VertexNormalsHelper=function(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16711680;d=void 0!==d?d:1;b=0;c=this.object.geometry;c instanceof THREE.Geometry?b=3*c.faces.length:c instanceof THREE.BufferGeometry&&(b=c.attributes.normal.count);c=new THREE.BufferGeometry;b=new THREE.Float32Attribute(6*b,3);c.addAttribute("position",b);THREE.LineSegments.call(this,c,new THREE.LineBasicMaterial({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}; -THREE.VertexNormalsHelper.prototype=Object.create(THREE.LineSegments.prototype);THREE.VertexNormalsHelper.prototype.constructor=THREE.VertexNormalsHelper; -THREE.VertexNormalsHelper.prototype.update=function(){var a=new THREE.Vector3,b=new THREE.Vector3,c=new THREE.Matrix3;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g instanceof THREE.Geometry)for(var h=g.vertices,k=g.faces,l=g=0,m=k.length;lh.end&&(h.end=f);c||(c=k)}}for(k in d)h=d[k],this.createAnimation(k,h.start,h.end,a);this.firstAnimation=c}; -THREE.MorphBlendMesh.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=-1,a.directionBackwards=!0};THREE.MorphBlendMesh.prototype.setAnimationFPS=function(a,b){var c=this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)}; -THREE.MorphBlendMesh.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/c.duration)};THREE.MorphBlendMesh.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};THREE.MorphBlendMesh.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};THREE.MorphBlendMesh.prototype.getAnimationTime=function(a){var b=0;if(a=this.animationsMap[a])b=a.time;return b}; -THREE.MorphBlendMesh.prototype.getAnimationDuration=function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};THREE.MorphBlendMesh.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+a+"] undefined in .playAnimation()")};THREE.MorphBlendMesh.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1}; -THREE.MorphBlendMesh.prototype.update=function(a){for(var b=0,c=this.animationsList.length;bd.duration||0>d.time)d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),0>d.time&&(d.time=0,d.directionBackwards=!1)}else d.time%=d.duration,0>d.time&&(d.time+=d.duration);var f=d.start+THREE.Math.clamp(Math.floor(d.time/e),0,d.length-1),g=d.weight;f!==d.currentFrame&& -(this.morphTargetInfluences[d.lastFrame]=0,this.morphTargetInfluences[d.currentFrame]=1*g,this.morphTargetInfluences[f]=0,d.lastFrame=d.currentFrame,d.currentFrame=f);e=d.time%e/e;d.directionBackwards&&(e=1-e);d.currentFrame!==d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}}; +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.THREE=t.THREE||{})}(this,function(t){"use strict";function e(){this.isEventDispatcher=!0}function n(t,e){this.isVector2=!0,this.x=t||0,this.y=e||0}function i(e,a,o,s,h,c,l,u,d,p){this.isTexture=!0,Object.defineProperty(this,"id",{value:r()}),this.uuid=t.Math.generateUUID(),this.name="",this.sourceFile="",this.image=void 0!==e?e:i.DEFAULT_IMAGE,this.mipmaps=[],this.mapping=void 0!==a?a:i.DEFAULT_MAPPING,this.wrapS=void 0!==o?o:yr,this.wrapT=void 0!==s?s:yr,this.magFilter=void 0!==h?h:Mr,this.minFilter=void 0!==c?c:Sr,this.anisotropy=void 0!==d?d:1,this.format=void 0!==l?l:zr,this.type=void 0!==u?u:Tr,this.offset=new n(0,0),this.repeat=new n(1,1),this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.encoding=void 0!==p?p:ua,this.version=0,this.onUpdate=null}function r(){return _a++}function a(){this.isMatrix4=!0,this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function o(t,e,n,i){this.isQuaternion=!0,this._x=t||0,this._y=e||0,this._z=n||0,this._w=void 0!==i?i:1}function s(t,e,n){this.isVector3=!0,this.x=t||0,this.y=e||0,this.z=n||0}function h(t,e){function n(){var t=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),e=new Uint16Array([0,1,2,0,2,3]);h=f.createBuffer(),c=f.createBuffer(),f.bindBuffer(f.ARRAY_BUFFER,h),f.bufferData(f.ARRAY_BUFFER,t,f.STATIC_DRAW),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c),f.bufferData(f.ELEMENT_ARRAY_BUFFER,e,f.STATIC_DRAW),l=r(),u={position:f.getAttribLocation(l,"position"),uv:f.getAttribLocation(l,"uv")},d={uvOffset:f.getUniformLocation(l,"uvOffset"),uvScale:f.getUniformLocation(l,"uvScale"),rotation:f.getUniformLocation(l,"rotation"),scale:f.getUniformLocation(l,"scale"),color:f.getUniformLocation(l,"color"),map:f.getUniformLocation(l,"map"),opacity:f.getUniformLocation(l,"opacity"),modelViewMatrix:f.getUniformLocation(l,"modelViewMatrix"),projectionMatrix:f.getUniformLocation(l,"projectionMatrix"),fogType:f.getUniformLocation(l,"fogType"),fogDensity:f.getUniformLocation(l,"fogDensity"),fogNear:f.getUniformLocation(l,"fogNear"),fogFar:f.getUniformLocation(l,"fogFar"),fogColor:f.getUniformLocation(l,"fogColor"),alphaTest:f.getUniformLocation(l,"alphaTest")};var n=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");n.width=8,n.height=8;var a=n.getContext("2d");a.fillStyle="white",a.fillRect(0,0,8,8),p=new i(n),p.needsUpdate=!0}function r(){var e=f.createProgram(),n=f.createShader(f.VERTEX_SHADER),i=f.createShader(f.FRAGMENT_SHADER);return f.shaderSource(n,["precision "+t.getPrecision()+" float;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float rotation;","uniform vec2 scale;","uniform vec2 uvOffset;","uniform vec2 uvScale;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","void main() {","vUV = uvOffset + uv * uvScale;","vec2 alignedPosition = position * scale;","vec2 rotatedPosition;","rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;","rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;","vec4 finalPosition;","finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );","finalPosition.xy += rotatedPosition;","finalPosition = projectionMatrix * finalPosition;","gl_Position = finalPosition;","}"].join("\n")),f.shaderSource(i,["precision "+t.getPrecision()+" float;","uniform vec3 color;","uniform sampler2D map;","uniform float opacity;","uniform int fogType;","uniform vec3 fogColor;","uniform float fogDensity;","uniform float fogNear;","uniform float fogFar;","uniform float alphaTest;","varying vec2 vUV;","void main() {","vec4 texture = texture2D( map, vUV );","if ( texture.a < alphaTest ) discard;","gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );","if ( fogType > 0 ) {","float depth = gl_FragCoord.z / gl_FragCoord.w;","float fogFactor = 0.0;","if ( fogType == 1 ) {","fogFactor = smoothstep( fogNear, fogFar, depth );","} else {","const float LOG2 = 1.442695;","fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","}","gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","}","}"].join("\n")),f.compileShader(n),f.compileShader(i),f.attachShader(e,n),f.attachShader(e,i),f.linkProgram(e),e}function a(t,e){return t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:e.id-t.id}this.isSpritePlugin=!0;var h,c,l,u,d,p,f=t.context,m=t.state,g=new s,v=new o,y=new s;this.render=function(i,r){if(0!==e.length){void 0===l&&n(),f.useProgram(l),m.initAttributes(),m.enableAttribute(u.position),m.enableAttribute(u.uv),m.disableUnusedAttributes(),m.disable(f.CULL_FACE),m.enable(f.BLEND),f.bindBuffer(f.ARRAY_BUFFER,h),f.vertexAttribPointer(u.position,2,f.FLOAT,!1,16,0),f.vertexAttribPointer(u.uv,2,f.FLOAT,!1,16,8),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c),f.uniformMatrix4fv(d.projectionMatrix,!1,r.projectionMatrix.elements),m.activeTexture(f.TEXTURE0),f.uniform1i(d.map,0);var o=0,s=0,x=i.fog;x?(f.uniform3f(d.fogColor,x.color.r,x.color.g,x.color.b),x&&x.isFog?(f.uniform1f(d.fogNear,x.near),f.uniform1f(d.fogFar,x.far),f.uniform1i(d.fogType,1),o=1,s=1):x&&x.isFogExp2&&(f.uniform1f(d.fogDensity,x.density),f.uniform1i(d.fogType,2),o=2,s=2)):(f.uniform1i(d.fogType,0),o=0,s=0);for(var b=0,_=e.length;b<_;b++){var w=e[b];w.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,w.matrixWorld),w.z=-w.modelViewMatrix.elements[14]}e.sort(a);for(var M=[],b=0,_=e.length;b<_;b++){var w=e[b],E=w.material;if(E.visible!==!1){f.uniform1f(d.alphaTest,E.alphaTest),f.uniformMatrix4fv(d.modelViewMatrix,!1,w.modelViewMatrix.elements),w.matrixWorld.decompose(g,v,y),M[0]=y.x,M[1]=y.y;var S=0;i.fog&&E.fog&&(S=s),o!==S&&(f.uniform1i(d.fogType,S),o=S),null!==E.map?(f.uniform2f(d.uvOffset,E.map.offset.x,E.map.offset.y),f.uniform2f(d.uvScale,E.map.repeat.x,E.map.repeat.y)):(f.uniform2f(d.uvOffset,0,0),f.uniform2f(d.uvScale,1,1)),f.uniform1f(d.opacity,E.opacity),f.uniform3f(d.color,E.color.r,E.color.g,E.color.b),f.uniform1f(d.rotation,E.rotation),f.uniform2fv(d.scale,M),m.setBlending(E.blending,E.blendEquation,E.blendSrc,E.blendDst),m.setDepthTest(E.depthTest),m.setDepthWrite(E.depthWrite),E.map?t.setTexture2D(E.map,0):t.setTexture2D(p,0),f.drawElements(f.TRIANGLES,6,f.UNSIGNED_SHORT,0)}}m.enable(f.CULL_FACE),t.resetGLState()}}}function c(t,e){this.isBox2=!0,this.min=void 0!==t?t:new n((+(1/0)),(+(1/0))),this.max=void 0!==e?e:new n((-(1/0)),(-(1/0)))}function l(t,e){function i(){var t=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),e=new Uint16Array([0,1,2,0,2,3]);a=m.createBuffer(),o=m.createBuffer(),m.bindBuffer(m.ARRAY_BUFFER,a),m.bufferData(m.ARRAY_BUFFER,t,m.STATIC_DRAW),m.bindBuffer(m.ELEMENT_ARRAY_BUFFER,o),m.bufferData(m.ELEMENT_ARRAY_BUFFER,e,m.STATIC_DRAW),p=m.createTexture(),f=m.createTexture(),g.bindTexture(m.TEXTURE_2D,p),m.texImage2D(m.TEXTURE_2D,0,m.RGB,16,16,0,m.RGB,m.UNSIGNED_BYTE,null),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_S,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_T,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MAG_FILTER,m.NEAREST),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MIN_FILTER,m.NEAREST),g.bindTexture(m.TEXTURE_2D,f),m.texImage2D(m.TEXTURE_2D,0,m.RGBA,16,16,0,m.RGBA,m.UNSIGNED_BYTE,null),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_S,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_T,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MAG_FILTER,m.NEAREST),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MIN_FILTER,m.NEAREST),h={vertexShader:["uniform lowp int renderType;","uniform vec3 screenPosition;","uniform vec2 scale;","uniform float rotation;","uniform sampler2D occlusionMap;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","varying float vVisibility;","void main() {","vUV = uv;","vec2 pos = position;","if ( renderType == 2 ) {","vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );","vVisibility = visibility.r / 9.0;","vVisibility *= 1.0 - visibility.g / 9.0;","vVisibility *= visibility.b / 9.0;","vVisibility *= 1.0 - visibility.a / 9.0;","pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;","pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;","}","gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );","}"].join("\n"),fragmentShader:["uniform lowp int renderType;","uniform sampler2D map;","uniform float opacity;","uniform vec3 color;","varying vec2 vUV;","varying float vVisibility;","void main() {","if ( renderType == 0 ) {","gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );","} else if ( renderType == 1 ) {","gl_FragColor = texture2D( map, vUV );","} else {","vec4 texture = texture2D( map, vUV );","texture.a *= opacity * vVisibility;","gl_FragColor = texture;","gl_FragColor.rgb *= color;","}","}"].join("\n")},l=r(h),u={vertex:m.getAttribLocation(l,"position"),uv:m.getAttribLocation(l,"uv")},d={renderType:m.getUniformLocation(l,"renderType"),map:m.getUniformLocation(l,"map"),occlusionMap:m.getUniformLocation(l,"occlusionMap"),opacity:m.getUniformLocation(l,"opacity"),color:m.getUniformLocation(l,"color"),scale:m.getUniformLocation(l,"scale"),rotation:m.getUniformLocation(l,"rotation"),screenPosition:m.getUniformLocation(l,"screenPosition")}}function r(e){var n=m.createProgram(),i=m.createShader(m.FRAGMENT_SHADER),r=m.createShader(m.VERTEX_SHADER),a="precision "+t.getPrecision()+" float;\n";return m.shaderSource(i,a+e.fragmentShader),m.shaderSource(r,a+e.vertexShader),m.compileShader(i),m.compileShader(r),m.attachShader(n,i),m.attachShader(n,r),m.linkProgram(n),n}this.isLensFlarePlugin=!0;var a,o,h,l,u,d,p,f,m=t.context,g=t.state;this.render=function(r,h,v){if(0!==e.length){var y=new s,x=v.w/v.z,b=.5*v.z,_=.5*v.w,w=16/v.w,M=new n(w*x,w),E=new s(1,1,0),S=new n(1,1),T=new c;T.min.set(0,0),T.max.set(v.z-16,v.w-16),void 0===l&&i(),m.useProgram(l),g.initAttributes(),g.enableAttribute(u.vertex),g.enableAttribute(u.uv),g.disableUnusedAttributes(),m.uniform1i(d.occlusionMap,0),m.uniform1i(d.map,1),m.bindBuffer(m.ARRAY_BUFFER,a),m.vertexAttribPointer(u.vertex,2,m.FLOAT,!1,16,0),m.vertexAttribPointer(u.uv,2,m.FLOAT,!1,16,8),m.bindBuffer(m.ELEMENT_ARRAY_BUFFER,o),g.disable(m.CULL_FACE),g.setDepthWrite(!1);for(var A=0,L=e.length;A.001&&U.scale>.001&&(E.x=U.x,E.y=U.y,E.z=U.z,w=U.size*U.scale/v.w,M.x=w*x,M.y=w,m.uniform3f(d.screenPosition,E.x,E.y,E.z),m.uniform2f(d.scale,M.x,M.y),m.uniform1f(d.rotation,U.rotation),m.uniform1f(d.opacity,U.opacity),m.uniform3f(d.color,U.color.r,U.color.g,U.color.b),g.setBlending(U.blending,U.blendEquation,U.blendSrc,U.blendDst),t.setTexture2D(U.texture,1),m.drawElements(m.TRIANGLES,6,m.UNSIGNED_SHORT,0))}}}g.enable(m.CULL_FACE),g.enable(m.DEPTH_TEST),g.setDepthWrite(!0),t.resetGLState()}}}function u(t,e,n,r,a,o,s,h,c,l){this.isCubeTexture=this.isTexture=!0,t=void 0!==t?t:[],e=void 0!==e?e:lr,i.call(this,t,e,n,r,a,o,s,h,c,l),this.flipY=!1}function d(e,n,i,r,a,o,s){function h(t,e){if(t.width>e||t.height>e){var n=e/Math.max(t.width,t.height),i=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");i.width=Math.floor(t.width*n),i.height=Math.floor(t.height*n);var r=i.getContext("2d");return r.drawImage(t,0,0,t.width,t.height,0,0,i.width,i.height),console.warn("THREE.WebGLRenderer: image is too big ("+t.width+"x"+t.height+"). Resized to "+i.width+"x"+i.height,t),i}return t}function c(e){return t.Math.isPowerOfTwo(e.width)&&t.Math.isPowerOfTwo(e.height)}function l(e){if(e instanceof HTMLImageElement||e instanceof HTMLCanvasElement){var n=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");n.width=t.Math.nearestPowerOfTwo(e.width),n.height=t.Math.nearestPowerOfTwo(e.height);var i=n.getContext("2d");return i.drawImage(e,0,0,n.width,n.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+e.width+"x"+e.height+"). Resized to "+n.width+"x"+n.height,e),n}return e}function u(t){return t.wrapS!==yr||t.wrapT!==yr||t.minFilter!==br&&t.minFilter!==Mr}function d(t){return t===br||t===_r||t===wr?e.NEAREST:e.LINEAR}function p(t){var e=t.target;e.removeEventListener("dispose",p),m(e),L.textures--}function f(t){var e=t.target;e.removeEventListener("dispose",f),g(e),L.textures--}function m(t){var n=r.get(t);if(t.image&&n.__image__webglTextureCube)e.deleteTexture(n.__image__webglTextureCube);else{if(void 0===n.__webglInit)return;e.deleteTexture(n.__webglTexture)}r.delete(t)}function g(t){var n=r.get(t),i=r.get(t.texture);if(t){if(void 0!==i.__webglTexture&&e.deleteTexture(i.__webglTexture),t.depthTexture&&t.depthTexture.dispose(),t&&t.isWebGLRenderTargetCube)for(var a=0;a<6;a++)e.deleteFramebuffer(n.__webglFramebuffer[a]),n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[a]);else e.deleteFramebuffer(n.__webglFramebuffer),n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer);r.delete(t.texture),r.delete(t)}}function v(t,n){var a=r.get(t);if(t.version>0&&a.__version!==t.version){var o=t.image;if(void 0===o)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",t);else{if(o.complete!==!1)return void _(a,t,n);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",t)}}i.activeTexture(e.TEXTURE0+n),i.bindTexture(e.TEXTURE_2D,a.__webglTexture)}function y(t,n){var s=r.get(t);if(6===t.image.length)if(t.version>0&&s.__version!==t.version){s.__image__webglTextureCube||(t.addEventListener("dispose",p),s.__image__webglTextureCube=e.createTexture(),L.textures++),i.activeTexture(e.TEXTURE0+n),i.bindTexture(e.TEXTURE_CUBE_MAP,s.__image__webglTextureCube),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,t.flipY);for(var l=t&&t.isCompressedTexture,u=t.image[0]&&t.image[0].isDataTexture,d=[],f=0;f<6;f++)l||u?d[f]=u?t.image[f].image:t.image[f]:d[f]=h(t.image[f],a.maxCubemapSize);var m=d[0],g=c(m),v=o(t.format),y=o(t.type);b(e.TEXTURE_CUBE_MAP,t,g);for(var f=0;f<6;f++)if(l)for(var x,_=d[f].mipmaps,w=0,M=_.length;w-1?i.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,w,v,x.width,x.height,0,x.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,w,v,x.width,x.height,0,v,y,x.data);else u?i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,v,d[f].width,d[f].height,0,v,y,d[f].data):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,v,v,y,d[f]);t.generateMipmaps&&g&&e.generateMipmap(e.TEXTURE_CUBE_MAP),s.__version=t.version,t.onUpdate&&t.onUpdate(t)}else i.activeTexture(e.TEXTURE0+n),i.bindTexture(e.TEXTURE_CUBE_MAP,s.__image__webglTextureCube)}function x(t,n){i.activeTexture(e.TEXTURE0+n),i.bindTexture(e.TEXTURE_CUBE_MAP,r.get(t).__webglTexture)}function b(t,i,s){var h;if(s?(e.texParameteri(t,e.TEXTURE_WRAP_S,o(i.wrapS)),e.texParameteri(t,e.TEXTURE_WRAP_T,o(i.wrapT)),e.texParameteri(t,e.TEXTURE_MAG_FILTER,o(i.magFilter)),e.texParameteri(t,e.TEXTURE_MIN_FILTER,o(i.minFilter))):(e.texParameteri(t,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(t,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),i.wrapS===yr&&i.wrapT===yr||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",i),e.texParameteri(t,e.TEXTURE_MAG_FILTER,d(i.magFilter)),e.texParameteri(t,e.TEXTURE_MIN_FILTER,d(i.minFilter)),i.minFilter!==br&&i.minFilter!==Mr&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",i)),h=n.get("EXT_texture_filter_anisotropic")){if(i.type===Ur&&null===n.get("OES_texture_float_linear"))return;if(i.type===Ir&&null===n.get("OES_texture_half_float_linear"))return;(i.anisotropy>1||r.get(i).__currentAnisotropy)&&(e.texParameterf(t,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i.anisotropy,a.getMaxAnisotropy())),r.get(i).__currentAnisotropy=i.anisotropy)}}function _(t,n,r){void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",p),t.__webglTexture=e.createTexture(),L.textures++),i.activeTexture(e.TEXTURE0+r),i.bindTexture(e.TEXTURE_2D,t.__webglTexture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,n.unpackAlignment);var s=h(n.image,a.maxTextureSize);u(n)&&c(s)===!1&&(s=l(s));var d=c(s),f=o(n.format),m=o(n.type);b(e.TEXTURE_2D,n,d);var g,v=n.mipmaps;if(n&&n.isDepthTexture){var y=e.DEPTH_COMPONENT;if(n.type===Ur){if(!R)throw new Error("Float Depth Texture only supported in WebGL2.0");y=e.DEPTH_COMPONENT32F}else R&&(y=e.DEPTH_COMPONENT16);i.texImage2D(e.TEXTURE_2D,0,y,s.width,s.height,0,f,m,null)}else if(n&&n.isDataTexture)if(v.length>0&&d){for(var x=0,_=v.length;x<_;x++)g=v[x],i.texImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,f,m,g.data);n.generateMipmaps=!1}else i.texImage2D(e.TEXTURE_2D,0,f,s.width,s.height,0,f,m,s.data);else if(n&&n.isCompressedTexture)for(var x=0,_=v.length;x<_;x++)g=v[x],n.format!==zr&&n.format!==Br?i.getCompressedTextureFormats().indexOf(f)>-1?i.compressedTexImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,g.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):i.texImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,f,m,g.data);else if(v.length>0&&d){for(var x=0,_=v.length;x<_;x++)g=v[x],i.texImage2D(e.TEXTURE_2D,x,f,f,m,g);n.generateMipmaps=!1}else i.texImage2D(e.TEXTURE_2D,0,f,f,m,s);n.generateMipmaps&&d&&e.generateMipmap(e.TEXTURE_2D),t.__version=n.version,n.onUpdate&&n.onUpdate(n)}function w(t,n,a,s){var h=o(n.texture.format),c=o(n.texture.type);i.texImage2D(s,0,h,n.width,n.height,0,h,c,null),e.bindFramebuffer(e.FRAMEBUFFER,t),e.framebufferTexture2D(e.FRAMEBUFFER,a,s,r.get(n.texture).__webglTexture,0),e.bindFramebuffer(e.FRAMEBUFFER,null)}function M(t,n){e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer&&!n.stencilBuffer?(e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t)):n.depthBuffer&&n.stencilBuffer?(e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_STENCIL,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,t)):e.renderbufferStorage(e.RENDERBUFFER,e.RGBA4,n.width,n.height),e.bindRenderbuffer(e.RENDERBUFFER,null)}function E(t,n){var i=n&&n.isWebGLRenderTargetCube;if(i)throw new Error("Depth Texture with cube render targets is not supported!");if(e.bindFramebuffer(e.FRAMEBUFFER,t),!n.depthTexture||!n.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");r.get(n.depthTexture).__webglTexture&&n.depthTexture.image.width===n.width&&n.depthTexture.image.height===n.height||(n.depthTexture.image.width=n.width,n.depthTexture.image.height=n.height,n.depthTexture.needsUpdate=!0),v(n.depthTexture,0);var a=r.get(n.depthTexture).__webglTexture;e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0)}function S(t){var n=r.get(t),i=t&&t.isWebGLRenderTargetCube;if(t.depthTexture){if(i)throw new Error("target.depthTexture not supported in Cube render targets");E(n.__webglFramebuffer,t)}else if(i){n.__webglDepthbuffer=[];for(var a=0;a<6;a++)e.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer[a]),n.__webglDepthbuffer[a]=e.createRenderbuffer(),M(n.__webglDepthbuffer[a],t)}else e.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer),n.__webglDepthbuffer=e.createRenderbuffer(),M(n.__webglDepthbuffer,t);e.bindFramebuffer(e.FRAMEBUFFER,null)}function T(t){var n=r.get(t),a=r.get(t.texture);t.addEventListener("dispose",f),a.__webglTexture=e.createTexture(),L.textures++;var o=t&&t.isWebGLRenderTargetCube,s=c(t);if(o){n.__webglFramebuffer=[];for(var h=0;h<6;h++)n.__webglFramebuffer[h]=e.createFramebuffer()}else n.__webglFramebuffer=e.createFramebuffer();if(o){i.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture),b(e.TEXTURE_CUBE_MAP,t.texture,s);for(var h=0;h<6;h++)w(n.__webglFramebuffer[h],t,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+h);t.texture.generateMipmaps&&s&&e.generateMipmap(e.TEXTURE_CUBE_MAP),i.bindTexture(e.TEXTURE_CUBE_MAP,null)}else i.bindTexture(e.TEXTURE_2D,a.__webglTexture),b(e.TEXTURE_2D,t.texture,s),w(n.__webglFramebuffer,t,e.COLOR_ATTACHMENT0,e.TEXTURE_2D),t.texture.generateMipmaps&&s&&e.generateMipmap(e.TEXTURE_2D),i.bindTexture(e.TEXTURE_2D,null);t.depthBuffer&&S(t)}function A(t){var n=t.texture;if(n.generateMipmaps&&c(t)&&n.minFilter!==br&&n.minFilter!==Mr){var a=t&&t.isWebGLRenderTargetCube?e.TEXTURE_CUBE_MAP:e.TEXTURE_2D,o=r.get(n).__webglTexture;i.bindTexture(a,o),e.generateMipmap(a),i.bindTexture(a,null)}}this.isWebGLTextures=!0;var L=s.memory,R="undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext;this.setTexture2D=v,this.setTextureCube=y,this.setTextureCubeDynamic=x,this.setupRenderTarget=T,this.updateRenderTargetMipmap=A}function p(t,e,n,i){this.isVector4=!0,this.x=t||0,this.y=e||0,this.z=n||0,this.w=void 0!==i?i:1}function f(t,e,n){function i(e,n,i){var r=new Uint8Array(4),a=t.createTexture();t.bindTexture(e,a),t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST);for(var o=0;o0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function A(t,e){this.isPlane=!0,this.normal=void 0!==t?t:new s(1,0,0),this.constant=void 0!==e?e:0}function L(t,e,n,i,r,a){this.isFrustum=!0,this.planes=[void 0!==t?t:new A,void 0!==e?e:new A,void 0!==n?n:new A,void 0!==i?i:new A,void 0!==r?r:new A,void 0!==a?a:new A]}function R(e,i,r,o){function h(t,n,i,r){var a=t.geometry,o=null,s=A,h=t.customDepthMaterial;if(i&&(s=R,h=t.customDistanceMaterial),h)o=h;else{var c=!1;n.morphTargets&&(a&&a.isBufferGeometry?c=a.morphAttributes&&a.morphAttributes.position&&a.morphAttributes.position.length>0:a&&a.isGeometry&&(c=a.morphTargets&&a.morphTargets.length>0));var l=t&&t.isSkinnedMesh&&n.skinning,u=0;c&&(u|=E),l&&(u|=S),o=s[u]}if(e.localClippingEnabled&&n.clipShadows===!0&&0!==n.clippingPlanes.length){var d=o.uuid,p=n.uuid,f=C[d];void 0===f&&(f={},C[d]=f);var m=f[p];void 0===m&&(m=o.clone(),f[p]=m),o=m}o.visible=n.visible,o.wireframe=n.wireframe;var g=n.side;return H.renderSingleSided&&g==xi&&(g=vi),H.renderReverseSided&&(g===vi?g=yi:g===yi&&(g=vi)),o.side=g,o.clipShadows=n.clipShadows,o.clippingPlanes=n.clippingPlanes,o.wireframeLinewidth=n.wireframeLinewidth,o.linewidth=n.linewidth,i&&void 0!==o.uniforms.lightPos&&o.uniforms.lightPos.value.copy(r),o}function c(t,e,n){if(t.visible!==!1){if(t.layers.test(e.layers)&&(t&&t.isMesh||t&&t.isLine||t&&t.isPoints)&&t.castShadow&&(t.frustumCulled===!1||d.intersectsObject(t)===!0)){var i=t.material;i.visible===!0&&(t.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,t.matrixWorld),w.push(t))}for(var r=t.children,a=0,o=r.length;a0,shadowMapType:e.shadowMap.type,toneMapping:e.toneMapping,physicallyCorrectLights:e.physicallyCorrectLights,premultipliedAlpha:t.premultipliedAlpha,alphaTest:t.alphaTest,doubleSided:t.side===xi,flipSided:t.side===yi,depthPacking:void 0!==t.depthPacking&&t.depthPacking};return f},this.getProgramCode=function(t,e){var n=[];if(e.shaderID?n.push(e.shaderID):(n.push(t.fragmentShader),n.push(t.vertexShader)),void 0!==t.defines)for(var i in t.defines)n.push(i),n.push(t.defines[i]);for(var r=0;r65535?Uint32Array:Uint16Array,y=new U(new v(a),1);return r(y,t.ELEMENT_ARRAY_BUFFER),i.wireframe=y,y}function c(t,e,n){if(e>n){var i=e;e=n,n=i}var r=t[e];return void 0===r?(t[e]=[n],!0):r.indexOf(n)===-1&&(r.push(n),!0)}this.isWebGLObjects=!0;var l=new K(t,e,n);this.getAttributeBuffer=s,this.getWireframeAttribute=h,this.update=i}function tt(){this.isWebGLLights=!0;var t={};this.get=function(e){if(void 0!==t[e.id])return t[e.id];var i;switch(e.type){case"DirectionalLight":i={direction:new s,color:new w,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new n};break;case"SpotLight":i={position:new s,direction:new s,color:new w,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new n};break;case"PointLight":i={position:new s,color:new w,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new n};break;case"HemisphereLight":i={direction:new s,skyColor:new w,groundColor:new w}}return t[e.id]=i,i}}function et(t,e,n){function i(){if(void 0!==a)return a;var n=e.get("EXT_texture_filter_anisotropic");return a=null!==n?t.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}function r(e){if("highp"===e){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}this.isWebGLCapabilities=!0;var a;this.getMaxAnisotropy=i,this.getMaxPrecision=r,this.precision=void 0!==n.precision?n.precision:"highp",this.logarithmicDepthBuffer=void 0!==n.logarithmicDepthBuffer&&n.logarithmicDepthBuffer,this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubemapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxAttributes=t.getParameter(t.MAX_VERTEX_ATTRIBS),this.maxVertexUniforms=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.maxVaryings=t.getParameter(t.MAX_VARYING_VECTORS),this.maxFragmentUniforms=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.vertexTextures=this.maxVertexTextures>0,this.floatFragmentTextures=!!e.get("OES_texture_float"),this.floatVertexTextures=this.vertexTextures&&this.floatFragmentTextures;var o=r(this.precision);o!==this.precision&&(console.warn("THREE.WebGLRenderer:",this.precision,"not supported, using",o,"instead."),this.precision=o),this.logarithmicDepthBuffer&&(this.logarithmicDepthBuffer=!!e.get("EXT_frag_depth"))}function nt(t){this.isWebGLExtensions=!0;var e={};this.get=function(n){if(void 0!==e[n])return e[n];var i;switch(n){case"WEBGL_depth_texture":i=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case"WEBGL_compressed_texture_etc1":i=t.getExtension("WEBGL_compressed_texture_etc1");break;default:i=t.getExtension(n)}return null===i&&console.warn("THREE.WebGLRenderer: "+n+" extension not supported."),e[n]=i,i}}function it(t,e,n){function i(t){s=t}function r(n){n.array instanceof Uint32Array&&e.get("OES_element_index_uint")?(h=t.UNSIGNED_INT,c=4):(h=t.UNSIGNED_SHORT,c=2)}function a(e,i){t.drawElements(s,i,h,e*c),n.calls++,n.vertices+=i,s===t.TRIANGLES&&(n.faces+=i/3)}function o(i,r,a){var o=e.get("ANGLE_instanced_arrays");return null===o?void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(o.drawElementsInstancedANGLE(s,a,h,r*c,i.maxInstancedCount),n.calls++,n.vertices+=a*i.maxInstancedCount,void(s===t.TRIANGLES&&(n.faces+=i.maxInstancedCount*a/3)))}this.isWebGLIndexedBufferRenderer=!0;var s,h,c;this.setMode=i,this.setIndex=r,this.render=a,this.renderInstances=o}function rt(){function t(){c.value!==i&&(c.value=i,c.needsUpdate=r>0),n.numPlanes=r}function e(t,e,i,r){var a=null!==t?t.length:0,o=null;if(0!==a){if(o=c.value,r!==!0||null===o){var l=i+4*a,u=e.matrixWorldInverse;h.getNormalMatrix(u),(null===o||o.length0?1:-1,m[v]=P.x,m[v+1]=P.y,m[v+2]=P.z,g[y]=D/c,g[y+1]=1-U/u,v+=3,y+=2,R+=1}for(U=0;U65535?Uint32Array:Uint16Array)(d),f=new Float32Array(3*u),m=new Float32Array(3*u),g=new Float32Array(2*u),v=0,y=0,x=0,b=0,_=0;c("z","y","x",-1,-1,n,e,t,a,r,0),c("z","y","x",1,-1,n,e,-t,a,r,1),c("x","z","y",1,1,t,n,e,i,a,2),c("x","z","y",1,-1,t,n,-e,i,a,3),c("x","y","z",1,-1,t,e,n,i,r,4),c("x","y","z",-1,-1,t,e,-n,i,r,5),this.setIndex(new U(p,1)),this.addAttribute("position",new U(f,3)),this.addAttribute("normal",new U(m,3)),this.addAttribute("uv",new U(g,2))}function ht(t,e){this.isRay=!0,this.origin=void 0!==t?t:new s,this.direction=void 0!==e?e:new s}function ct(t,e){this.isLine3=!0,this.start=void 0!==t?t:new s,this.end=void 0!==e?e:new s}function lt(t,e,n){this.isTriangle=!0,this.a=void 0!==t?t:new s,this.b=void 0!==e?e:new s,this.c=void 0!==n?n:new s}function ut(t){this.isMeshBasicMaterial=this.isMaterial=!0,x.call(this),this.type="MeshBasicMaterial",this.color=new w(16777215),this.map=null,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.lights=!1,this.setValues(t)}function dt(t,e){this.isMesh=!0,X.call(this),this.type="Mesh",this.geometry=void 0!==t?t:new Q,this.material=void 0!==e?e:new ut({color:16777215*Math.random()}),this.drawMode=ha,this.updateMorphTargets()}function pt(t,e,n,i){this.isPlaneBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="PlaneBufferGeometry",this.parameters={width:t,height:e,widthSegments:n,heightSegments:i};for(var r=t/2,a=e/2,o=Math.floor(n)||1,s=Math.floor(i)||1,h=o+1,c=s+1,l=t/o,u=e/s,d=new Float32Array(h*c*3),p=new Float32Array(h*c*3),f=new Float32Array(h*c*2),m=0,g=0,v=0;v65535?Uint32Array:Uint16Array)(o*s*6),v=0;v=0){var l=a[h];if(void 0!==l){var u=ee.FLOAT,d=l.array,p=l.normalized;d instanceof Float32Array?u=ee.FLOAT:d instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):d instanceof Uint16Array?u=ee.UNSIGNED_SHORT:d instanceof Int16Array?u=ee.SHORT:d instanceof Uint32Array?u=ee.UNSIGNED_INT:d instanceof Int32Array?u=ee.INT:d instanceof Int8Array?u=ee.BYTE:d instanceof Uint8Array&&(u=ee.UNSIGNED_BYTE);var f=l.itemSize,m=he.getAttributeBuffer(l);if(l&&l.isInterleavedBufferAttribute){var g=l.data,v=g.stride,y=l.offset;g&&g.isInstancedInterleavedBuffer?(ae.enableAttributeAndDivisor(c,g.meshPerAttribute,r),void 0===n.maxInstancedCount&&(n.maxInstancedCount=g.meshPerAttribute*g.count)):ae.enableAttribute(c),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(c,f,u,p,v*g.array.BYTES_PER_ELEMENT,(i*v+y)*g.array.BYTES_PER_ELEMENT)}else l&&l.isInstancedBufferAttribute?(ae.enableAttributeAndDivisor(c,l.meshPerAttribute,r),void 0===n.maxInstancedCount&&(n.maxInstancedCount=l.meshPerAttribute*l.count)):ae.enableAttribute(c),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(c,f,u,p,0,i*f*l.array.BYTES_PER_ELEMENT)}else if(void 0!==s){var x=s[h];if(void 0!==x)switch(x.length){case 2:ee.vertexAttrib2fv(c,x);break;case 3:ee.vertexAttrib3fv(c,x);break;case 4:ee.vertexAttrib4fv(c,x);break;default:ee.vertexAttrib1fv(c,x)}}}}ae.disableUnusedAttributes()}function y(t,e){return Math.abs(e[0])-Math.abs(t[0])}function x(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.material.program&&e.material.program&&t.material.program!==e.material.program?t.material.program.id-e.material.program.id:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function b(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function M(t,e,n,i,r){var a,o;n.transparent?(a=wt,o=++Mt):(a=bt,o=++_t);var s=a[o];void 0!==s?(s.id=t.id,s.object=t,s.geometry=e,s.material=n,s.z=Kt.z,s.group=r):(s={id:t.id,object:t,geometry:e,material:n,z:Kt.z,group:r},a.push(s))}function E(t){var e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),Jt.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),A(Jt)}function T(t){return Jt.center.set(0,0,0),Jt.radius=.7071067811865476,Jt.applyMatrix4(t.matrixWorld),A(Jt)}function A(t){if(!Xt.intersectsSphere(t))return!1;var e=Yt.numPlanes;if(0===e)return!0;var n=At.clippingPlanes,i=t.center,r=-t.radius,a=0;do if(n[a].distanceToPoint(i)=0&&e.numSupportedMorphTargets++}if(e.morphNormals){e.numSupportedMorphNormals=0;for(var d=0;d=0&&e.numSupportedMorphNormals++}var p=r.__webglShader.uniforms;(e&&e.isShaderMaterial||e&&e.isRawShaderMaterial)&&e.clipping!==!0||(r.numClippingPlanes=Yt.numPlanes,p.clippingPlanes=Yt.uniform),e.lights&&(r.lightsHash=$t.hash,p.ambientLightColor.value=$t.ambient,p.directionalLights.value=$t.directional,p.spotLights.value=$t.spot,p.pointLights.value=$t.point,p.hemisphereLights.value=$t.hemi,p.directionalShadowMap.value=$t.directionalShadowMap,p.directionalShadowMatrix.value=$t.directionalShadowMatrix,p.spotShadowMap.value=$t.spotShadowMap, +p.spotShadowMatrix.value=$t.spotShadowMatrix,p.pointShadowMap.value=$t.pointShadowMap,p.pointShadowMatrix.value=$t.pointShadowMatrix);var f=r.program.getUniforms(),m=t.WebGLUniforms.seqWithValue(f.seq,p);r.uniformsList=m,r.dynamicUniforms=t.WebGLUniforms.splitDynamic(m,p)}function N(t){t.side!==xi?ae.enable(ee.CULL_FACE):ae.disable(ee.CULL_FACE),ae.setFlipSided(t.side===yi),t.transparent===!0?ae.setBlending(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.premultipliedAlpha):ae.setBlending(Si),ae.setDepthFunc(t.depthFunc),ae.setDepthTest(t.depthTest),ae.setDepthWrite(t.depthWrite),ae.setColorWrite(t.colorWrite),ae.setPolygonOffset(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits)}function O(e,n,i,r){Ft=0;var a=oe.get(i);if(qt){if(Zt||e!==It){var o=e===It&&i.id===Pt;Yt.setState(i.clippingPlanes,i.clipShadows,e,a,o)}void 0!==a.numClippingPlanes&&a.numClippingPlanes!==Yt.numPlanes&&(i.needsUpdate=!0)}void 0===a.program&&(i.needsUpdate=!0),void 0!==a.lightsHash&&a.lightsHash!==$t.hash&&(i.needsUpdate=!0),i.needsUpdate&&(D(i,n,r),i.needsUpdate=!1);var s=!1,h=!1,c=!1,l=a.program,u=l.getUniforms(),d=a.__webglShader.uniforms;if(l.id!==Lt&&(ee.useProgram(l.program),Lt=l.id,s=!0,h=!0,c=!0),i.id!==Pt&&(Pt=i.id,h=!0),s||e!==It){if(u.set(ee,e,"projectionMatrix"),re.logarithmicDepthBuffer&&u.setValue(ee,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),e!==It&&(It=e,h=!0,c=!0),i&&i.isShaderMaterial||i&&i.isMeshPhongMaterial||i&&i.isMeshStandardMaterial||i.envMap){var p=u.map.cameraPosition;void 0!==p&&p.setValue(ee,Kt.setFromMatrixPosition(e.matrixWorld))}(i&&i.isMeshPhongMaterial||i&&i.isMeshLambertMaterial||i&&i.isMeshBasicMaterial||i&&i.isMeshStandardMaterial||i&&i.isShaderMaterial||i.skinning)&&u.setValue(ee,"viewMatrix",e.matrixWorldInverse),u.set(ee,At,"toneMappingExposure"),u.set(ee,At,"toneMappingWhitePoint")}if(i.skinning){u.setOptional(ee,r,"bindMatrix"),u.setOptional(ee,r,"bindMatrixInverse");var f=r.skeleton;f&&(re.floatVertexTextures&&f.useVertexTexture?(u.set(ee,f,"boneTexture"),u.set(ee,f,"boneTextureWidth"),u.set(ee,f,"boneTextureHeight")):u.setOptional(ee,f,"boneMatrices"))}h&&(i.lights&&X(d,c),n&&i.fog&&k(d,n),(i&&i.isMeshBasicMaterial||i&&i.isMeshLambertMaterial||i&&i.isMeshPhongMaterial||i&&i.isMeshStandardMaterial||i&&i.isMeshDepthMaterial)&&F(d,i),i&&i.isLineBasicMaterial?B(d,i):i&&i.isLineDashedMaterial?(B(d,i),z(d,i)):i&&i.isPointsMaterial?G(d,i):i&&i.isMeshLambertMaterial?H(d,i):i&&i.isMeshPhongMaterial?V(d,i):i&&i.isMeshPhysicalMaterial?W(d,i):i&&i.isMeshStandardMaterial?j(d,i):i&&i.isMeshDepthMaterial?i.displacementMap&&(d.displacementMap.value=i.displacementMap,d.displacementScale.value=i.displacementScale,d.displacementBias.value=i.displacementBias):i&&i.isMeshNormalMaterial&&(d.opacity.value=i.opacity),t.WebGLUniforms.upload(ee,a.uniformsList,d,At)),u.set(ee,r,"modelViewMatrix"),u.set(ee,r,"normalMatrix"),u.setValue(ee,"modelMatrix",r.matrixWorld);var m=a.dynamicUniforms;return null!==m&&(t.WebGLUniforms.evalDynamic(m,d,r,e),t.WebGLUniforms.upload(ee,m,d,At)),l}function F(t,e){t.opacity.value=e.opacity,t.diffuse.value=e.color,e.emissive&&t.emissive.value.copy(e.emissive).multiplyScalar(e.emissiveIntensity),t.map.value=e.map,t.specularMap.value=e.specularMap,t.alphaMap.value=e.alphaMap,e.aoMap&&(t.aoMap.value=e.aoMap,t.aoMapIntensity.value=e.aoMapIntensity);var n;if(e.map?n=e.map:e.specularMap?n=e.specularMap:e.displacementMap?n=e.displacementMap:e.normalMap?n=e.normalMap:e.bumpMap?n=e.bumpMap:e.roughnessMap?n=e.roughnessMap:e.metalnessMap?n=e.metalnessMap:e.alphaMap?n=e.alphaMap:e.emissiveMap&&(n=e.emissiveMap),void 0!==n){n&&n.isWebGLRenderTarget&&(n=n.texture);var i=n.offset,r=n.repeat;t.offsetRepeat.value.set(i.x,i.y,r.x,r.y)}t.envMap.value=e.envMap,t.flipEnvMap.value=e.envMap&&e.envMap.isCubeTexture?-1:1,t.reflectivity.value=e.reflectivity,t.refractionRatio.value=e.refractionRatio}function B(t,e){t.diffuse.value=e.color,t.opacity.value=e.opacity}function z(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}function G(t,e){if(t.diffuse.value=e.color,t.opacity.value=e.opacity,t.size.value=e.size*Ht,t.scale.value=.5*K.clientHeight,t.map.value=e.map,null!==e.map){var n=e.map.offset,i=e.map.repeat;t.offsetRepeat.value.set(n.x,n.y,i.x,i.y)}}function k(t,e){t.fogColor.value=e.color,e&&e.isFog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e&&e.isFogExp2&&(t.fogDensity.value=e.density)}function H(t,e){e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap)}function V(t,e){t.specular.value=e.specular,t.shininess.value=Math.max(e.shininess,1e-4),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}function j(t,e){t.roughness.value=e.roughness,t.metalness.value=e.metalness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap),e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias),e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}function W(t,e){t.clearCoat.value=e.clearCoat,t.clearCoatRoughness.value=e.clearCoatRoughness,j(t,e)}function X(t,e){t.ambientLightColor.needsUpdate=e,t.directionalLights.needsUpdate=e,t.pointLights.needsUpdate=e,t.spotLights.needsUpdate=e,t.hemisphereLights.needsUpdate=e}function Y(t){for(var e=0,n=0,i=t.length;n=re.maxTextures&&console.warn("WebGLRenderer: trying to use "+t+" texture units while this GPU supports only "+re.maxTextures),Ft+=1,t}function J(t){var e;if(t===vr)return ee.REPEAT;if(t===yr)return ee.CLAMP_TO_EDGE;if(t===xr)return ee.MIRRORED_REPEAT;if(t===br)return ee.NEAREST;if(t===_r)return ee.NEAREST_MIPMAP_NEAREST;if(t===wr)return ee.NEAREST_MIPMAP_LINEAR;if(t===Mr)return ee.LINEAR;if(t===Er)return ee.LINEAR_MIPMAP_NEAREST;if(t===Sr)return ee.LINEAR_MIPMAP_LINEAR;if(t===Tr)return ee.UNSIGNED_BYTE;if(t===Dr)return ee.UNSIGNED_SHORT_4_4_4_4;if(t===Nr)return ee.UNSIGNED_SHORT_5_5_5_1;if(t===Or)return ee.UNSIGNED_SHORT_5_6_5;if(t===Ar)return ee.BYTE;if(t===Lr)return ee.SHORT;if(t===Rr)return ee.UNSIGNED_SHORT;if(t===Cr)return ee.INT;if(t===Pr)return ee.UNSIGNED_INT;if(t===Ur)return ee.FLOAT;if(e=ie.get("OES_texture_half_float"),null!==e&&t===Ir)return e.HALF_FLOAT_OES;if(t===Fr)return ee.ALPHA;if(t===Br)return ee.RGB;if(t===zr)return ee.RGBA;if(t===Gr)return ee.LUMINANCE;if(t===kr)return ee.LUMINANCE_ALPHA;if(t===Vr)return ee.DEPTH_COMPONENT;if(t===Pi)return ee.FUNC_ADD;if(t===Ui)return ee.FUNC_SUBTRACT;if(t===Ii)return ee.FUNC_REVERSE_SUBTRACT;if(t===Oi)return ee.ZERO;if(t===Fi)return ee.ONE;if(t===Bi)return ee.SRC_COLOR;if(t===zi)return ee.ONE_MINUS_SRC_COLOR;if(t===Gi)return ee.SRC_ALPHA;if(t===ki)return ee.ONE_MINUS_SRC_ALPHA;if(t===Hi)return ee.DST_ALPHA;if(t===Vi)return ee.ONE_MINUS_DST_ALPHA;if(t===ji)return ee.DST_COLOR;if(t===Wi)return ee.ONE_MINUS_DST_COLOR;if(t===Xi)return ee.SRC_ALPHA_SATURATE;if(e=ie.get("WEBGL_compressed_texture_s3tc"),null!==e){if(t===jr)return e.COMPRESSED_RGB_S3TC_DXT1_EXT;if(t===Wr)return e.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(t===Xr)return e.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(t===Yr)return e.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e=ie.get("WEBGL_compressed_texture_pvrtc"),null!==e){if(t===qr)return e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(t===Zr)return e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(t===Jr)return e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(t===Qr)return e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e=ie.get("WEBGL_compressed_texture_etc1"),null!==e&&t===Kr)return e.COMPRESSED_RGB_ETC1_WEBGL;if(e=ie.get("EXT_blend_minmax"),null!==e){if(t===Di)return e.MIN_EXT;if(t===Ni)return e.MAX_EXT}return 0}this.isWebGLRenderer=!0,console.log("THREE.WebGLRenderer","jsnext"),e=e||{};var K=void 0!==e.canvas?e.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),ot=void 0!==e.context?e.context:null,ht=void 0!==e.alpha&&e.alpha,ct=void 0===e.depth||e.depth,lt=void 0===e.stencil||e.stencil,ft=void 0!==e.antialias&&e.antialias,vt=void 0===e.premultipliedAlpha||e.premultipliedAlpha,yt=void 0!==e.preserveDrawingBuffer&&e.preserveDrawingBuffer,xt=[],bt=[],_t=-1,wt=[],Mt=-1,Et=new Float32Array(8),St=[],Tt=[];this.domElement=K,this.context=null,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.gammaFactor=2,this.gammaInput=!1,this.gammaOutput=!1,this.physicallyCorrectLights=!1,this.toneMapping=ar,this.toneMappingExposure=1,this.toneMappingWhitePoint=1,this.maxMorphTargets=8,this.maxMorphNormals=4;var At=this,Lt=null,Rt=null,Ct=null,Pt=-1,Ut="",It=null,Dt=new p,Nt=null,Ot=new p,Ft=0,Bt=new w(0),zt=0,Gt=K.width,kt=K.height,Ht=1,Vt=new p(0,0,Gt,kt),jt=!1,Wt=new p(0,0,Gt,kt),Xt=new L,Yt=new rt,qt=!1,Zt=!1,Jt=new S,Qt=new a,Kt=new s,$t={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},te={calls:0,vertices:0,faces:0,points:0};this.info={render:te,memory:{geometries:0,textures:0},programs:null};var ee;try{var ne={alpha:ht,depth:ct,stencil:lt,antialias:ft,premultipliedAlpha:vt,preserveDrawingBuffer:yt};if(ee=ot||K.getContext("webgl",ne)||K.getContext("experimental-webgl",ne),null===ee)throw null!==K.getContext("webgl")?"Error creating WebGL context with your selected attributes.":"Error creating WebGL context.";void 0===ee.getShaderPrecisionFormat&&(ee.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}}),K.addEventListener("webglcontextlost",c,!1)}catch(t){console.error("THREE.WebGLRenderer: "+t)}var ie=new nt(ee);ie.get("WEBGL_depth_texture"),ie.get("OES_texture_float"),ie.get("OES_texture_float_linear"),ie.get("OES_texture_half_float"),ie.get("OES_texture_half_float_linear"),ie.get("OES_standard_derivatives"),ie.get("ANGLE_instanced_arrays"),ie.get("OES_element_index_uint")&&(Q.MaxIndex=4294967296);var re=new et(ee,ie,e),ae=new f(ee,ie,J),oe=new C,se=new d(ee,ie,ae,oe,re,J,this.info),he=new $(ee,oe,this.info),ce=new P(this,re),le=new tt;this.info.programs=ce.programs;var ue=new at(ee,ie,te),de=new it(ee,ie,te),pe=new gt((-1),1,1,(-1),0,1),fe=new mt,me=new dt(new pt(2,2),new ut({depthTest:!1,depthWrite:!1,fog:!1})),ge=t.ShaderLib.cube,ve=new dt(new st(5,5,5),new _({uniforms:ge.uniforms,vertexShader:ge.vertexShader,fragmentShader:ge.fragmentShader,side:yi,depthTest:!1,depthWrite:!1,fog:!1}));r(),this.context=ee,this.capabilities=re,this.extensions=ie,this.properties=oe,this.state=ae;var ye=new R(this,$t,he,re);this.shadowMap=ye;var xe=new h(this,St),be=new l(this,Tt);this.getContext=function(){return ee},this.getContextAttributes=function(){return ee.getContextAttributes()},this.forceContextLoss=function(){ie.get("WEBGL_lose_context").loseContext()},this.getMaxAnisotropy=function(){return re.getMaxAnisotropy()},this.getPrecision=function(){return re.precision},this.getPixelRatio=function(){return Ht},this.setPixelRatio=function(t){void 0!==t&&(Ht=t,this.setSize(Wt.z,Wt.w,!1))},this.getSize=function(){return{width:Gt,height:kt}},this.setSize=function(t,e,n){Gt=t,kt=e,K.width=t*Ht,K.height=e*Ht,n!==!1&&(K.style.width=t+"px",K.style.height=e+"px"),this.setViewport(0,0,t,e)},this.setViewport=function(t,e,n,i){ae.viewport(Wt.set(t,e,n,i))},this.setScissor=function(t,e,n,i){ae.scissor(Vt.set(t,e,n,i))},this.setScissorTest=function(t){ae.setScissorTest(jt=t)},this.getClearColor=function(){return Bt},this.setClearColor=function(t,e){Bt.set(t),zt=void 0!==e?e:1,i(Bt.r,Bt.g,Bt.b,zt)},this.getClearAlpha=function(){return zt},this.setClearAlpha=function(t){zt=t,i(Bt.r,Bt.g,Bt.b,zt)},this.clear=function(t,e,n){var i=0;(void 0===t||t)&&(i|=ee.COLOR_BUFFER_BIT),(void 0===e||e)&&(i|=ee.DEPTH_BUFFER_BIT),(void 0===n||n)&&(i|=ee.STENCIL_BUFFER_BIT),ee.clear(i)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.clearTarget=function(t,e,n,i){this.setRenderTarget(t),this.clear(e,n,i)},this.resetGLState=o,this.dispose=function(){wt=[],Mt=-1,bt=[],_t=-1,K.removeEventListener("webglcontextlost",c,!1)},this.renderBufferImmediate=function(t,e,n){ae.initAttributes();var i=oe.get(t);t.hasPositions&&!i.position&&(i.position=ee.createBuffer()),t.hasNormals&&!i.normal&&(i.normal=ee.createBuffer()),t.hasUvs&&!i.uv&&(i.uv=ee.createBuffer()),t.hasColors&&!i.color&&(i.color=ee.createBuffer());var r=e.getAttributes();if(t.hasPositions&&(ee.bindBuffer(ee.ARRAY_BUFFER,i.position),ee.bufferData(ee.ARRAY_BUFFER,t.positionArray,ee.DYNAMIC_DRAW),ae.enableAttribute(r.position),ee.vertexAttribPointer(r.position,3,ee.FLOAT,!1,0,0)),t.hasNormals){if(ee.bindBuffer(ee.ARRAY_BUFFER,i.normal),"MeshPhongMaterial"!==n.type&&"MeshStandardMaterial"!==n.type&&"MeshPhysicalMaterial"!==n.type&&n.shading===bi)for(var a=0,o=3*t.count;a8&&(u.length=8);for(var m=i.morphAttributes,d=0,p=u.length;d0&&b.renderInstances(i,A,R):b.render(A,R)},this.render=function(t,e,n,r){if((e&&e.isCamera)===!1)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");var a=t.fog;Ut="",Pt=-1,It=null,t.autoUpdate===!0&&t.updateMatrixWorld(),null===e.parent&&e.updateMatrixWorld(),e.matrixWorldInverse.getInverse(e.matrixWorld),Qt.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Xt.setFromMatrix(Qt),xt.length=0,_t=-1,Mt=-1,St.length=0,Tt.length=0,Zt=this.localClippingEnabled,qt=Yt.init(this.clippingPlanes,Zt,e),U(t,e),bt.length=_t+1,wt.length=Mt+1,At.sortObjects===!0&&(bt.sort(x),wt.sort(b)),qt&&Yt.beginShadows(),Y(xt),ye.render(t,e),q(xt,e),qt&&Yt.endShadows(),te.calls=0,te.vertices=0,te.faces=0,te.points=0,void 0===n&&(n=null),this.setRenderTarget(n);var o=t.background;if(null===o?i(Bt.r,Bt.g,Bt.b,zt):o&&o.isColor&&i(o.r,o.g,o.b,1),(this.autoClear||r)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil),o&&o.isCubeTexture?(fe.projectionMatrix.copy(e.projectionMatrix),fe.matrixWorld.extractRotation(e.matrixWorld),fe.matrixWorldInverse.getInverse(fe.matrixWorld),ve.material.uniforms.tCube.value=o,ve.modelViewMatrix.multiplyMatrices(fe.matrixWorldInverse,ve.matrixWorld),he.update(ve),At.renderBufferDirect(fe,null,ve.geometry,ve.material,ve,null)):o&&o.isTexture&&(me.material.map=o,he.update(me),At.renderBufferDirect(pe,null,me.geometry,me.material,me,null)),t.overrideMaterial){var s=t.overrideMaterial;I(bt,e,a,s),I(wt,e,a,s)}else ae.setBlending(Si),I(bt,e,a),I(wt,e,a);xe.render(t,e),be.render(t,e,Ot),n&&se.updateRenderTargetMipmap(n),ae.setDepthTest(!0),ae.setDepthWrite(!0),ae.setColorWrite(!0)},this.setFaceCulling=function(t,e){ae.setCullFace(t),ae.setFlipSided(e===di)},this.allocTextureUnit=Z,this.setTexture2D=function(){var t=!1;return function(e,n){e&&e.isWebGLRenderTarget&&(t||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),se.setTexture2D(e,n)}}(),this.setTexture=function(){var t=!1;return function(e,n){t||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),t=!0),se.setTexture2D(e,n)}}(),this.setTextureCube=function(){var t=!1;return function(e,n){e&&e.isWebGLRenderTargetCube&&(t||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),e&&e.isCubeTexture||Array.isArray(e.image)&&6===e.image.length?se.setTextureCube(e,n):se.setTextureCubeDynamic(e,n)}}(),this.getCurrentRenderTarget=function(){return Rt},this.setRenderTarget=function(t){Rt=t,t&&void 0===oe.get(t).__webglFramebuffer&&se.setupRenderTarget(t);var e,n=t&&t.isWebGLRenderTargetCube;if(t){var i=oe.get(t);e=n?i.__webglFramebuffer[t.activeCubeFace]:i.__webglFramebuffer,Dt.copy(t.scissor),Nt=t.scissorTest,Ot.copy(t.viewport)}else e=null,Dt.copy(Vt).multiplyScalar(Ht),Nt=jt,Ot.copy(Wt).multiplyScalar(Ht);if(Ct!==e&&(ee.bindFramebuffer(ee.FRAMEBUFFER,e),Ct=e),ae.scissor(Dt),ae.setScissorTest(Nt),ae.viewport(Ot),n){var r=oe.get(t.texture);ee.framebufferTexture2D(ee.FRAMEBUFFER,ee.COLOR_ATTACHMENT0,ee.TEXTURE_CUBE_MAP_POSITIVE_X+t.activeCubeFace,r.__webglTexture,t.activeMipMapLevel)}},this.readRenderTargetPixels=function(t,e,n,i,r,a){if((t&&t.isWebGLRenderTarget)===!1)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");var o=oe.get(t).__webglFramebuffer;if(o){var s=!1;o!==Ct&&(ee.bindFramebuffer(ee.FRAMEBUFFER,o),s=!0);try{var h=t.texture;if(h.format!==zr&&J(h.format)!==ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!(h.type===Tr||J(h.type)===ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_TYPE)||h.type===Ur&&ie.get("WEBGL_color_buffer_float")||h.type===Ir&&ie.get("EXT_color_buffer_half_float")))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");ee.checkFramebufferStatus(ee.FRAMEBUFFER)===ee.FRAMEBUFFER_COMPLETE?e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r&&ee.readPixels(e,n,i,r,J(h.format),J(h.type),a):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{s&&ee.bindFramebuffer(ee.FRAMEBUFFER,Ct)}}}}function yt(t,e){this.isFogExp2=!0,this.name="",this.color=new w(t),this.density=void 0!==e?e:25e-5}function xt(t,e,n){this.isFog=!0,this.name="",this.color=new w(t),this.near=void 0!==e?e:1,this.far=void 0!==n?n:1e3}function bt(){this.isScene=this.isObject3D=!0,X.call(this),this.type="Scene",this.background=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0}function _t(t,e,n,i,r){this.isLensFlare=!0,X.call(this),this.lensFlares=[],this.positionScreen=new s,this.customUpdateCallback=void 0,void 0!==t&&this.add(t,e,n,i,r)}function wt(t){this.isSpriteMaterial=this.isMaterial=!0,x.call(this),this.type="SpriteMaterial",this.color=new w(16777215),this.map=null,this.rotation=0,this.fog=!1,this.lights=!1,this.setValues(t)}function Mt(t){this.isSprite=!0,X.call(this),this.type="Sprite",this.material=void 0!==t?t:new wt}function Et(){this.isLOD=!0,X.call(this),this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function St(t,e,n,r,a,o,s,h,c,l,u,d){this.isDataTexture=this.isTexture=!0,i.call(this,null,o,s,h,c,l,r,a,u,d),this.image={data:t,width:e,height:n},this.magFilter=void 0!==c?c:br,this.minFilter=void 0!==l?l:br,this.flipY=!1,this.generateMipmaps=!1}function Tt(e,n,i){if(this.isSkeleton=!0,this.useVertexTexture=void 0===i||i,this.identityMatrix=new a,e=e||[],this.bones=e.slice(0),this.useVertexTexture){var r=Math.sqrt(4*this.bones.length);r=t.Math.nextPowerOfTwo(Math.ceil(r)),r=Math.max(r,4),this.boneTextureWidth=r,this.boneTextureHeight=r,this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new St(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,zr,Ur)}else this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===n)this.calculateInverses();else if(this.bones.length===n.length)this.boneInverses=n.slice(0);else{console.warn("THREE.Skeleton bonInverses is the wrong length."),this.boneInverses=[];for(var o=0,s=this.bones.length;o=t.HAVE_CURRENT_DATA&&(u.needsUpdate=!0)}this.isVideoTexture=this.isTexture=!0,i.call(this,t,e,n,r,a,o,s,h,c),this.generateMipmaps=!1;var u=this;l()}function Ot(t,e,n,r,a,o,s,h,c,l,u,d){this.isCompressedTexture=this.isTexture=!0,i.call(this,null,o,s,h,c,l,r,a,u,d),this.image={width:e,height:n},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}function Ft(t,e,n,r,a,o,s,h,c){this.isCanvasTexture=this.isTexture=!0,i.call(this,t,e,n,r,a,o,s,h,c),this.needsUpdate=!0}function Bt(t,e,n,r,a,o,s,h,c){this.isDepthTexture=this.isTexture=!0,i.call(this,null,r,a,o,s,h,Vr,n,c),this.image={width:t,height:e},this.type=void 0!==n?n:Rr,this.magFilter=void 0!==s?s:br,this.minFilter=void 0!==h?h:br,this.flipY=!1,this.generateMipmaps=!1}function zt(){this.isShadowMaterial=this.isShaderMaterial=this.isMaterial=!0,_.call(this,{uniforms:t.UniformsUtils.merge([t.UniformsLib.lights,{opacity:{value:1}}]),vertexShader:t.ShaderChunk.shadow_vert,fragmentShader:t.ShaderChunk.shadow_frag}),this.lights=!0,this.transparent=!0,Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(t){this.uniforms.opacity.value=t}}})}function Gt(t){this.isRawShaderMaterial=this.isShaderMaterial=this.isMaterial=!0,_.call(this,t),this.type="RawShaderMaterial"}function kt(e){this.isMultiMaterial=!0,this.uuid=t.Math.generateUUID(),this.type="MultiMaterial",this.materials=e instanceof Array?e:[],this.visible=!0}function Ht(t){this.isMeshStandardMaterial=this.isMaterial=!0,x.call(this),this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new w(16777215),this.roughness=.5,this.metalness=.5,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new n(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Vt(t){this.isMeshPhysicalMaterial=this.isMeshStandardMaterial=this.isMaterial=!0,Ht.call(this),this.defines={PHYSICAL:""},this.type="MeshPhysicalMaterial",this.reflectivity=.5,this.clearCoat=0,this.clearCoatRoughness=0,this.setValues(t)}function jt(t){this.isMeshPhongMaterial=this.isMaterial=!0,x.call(this),this.type="MeshPhongMaterial",this.color=new w(16777215),this.specular=new w(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new n(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Wt(t){this.isMeshNormalMaterial=this.isMaterial=!0,x.call(this,t),this.type="MeshNormalMaterial",this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.morphTargets=!1,this.setValues(t)}function Xt(t){this.isMeshLambertMaterial=this.isMaterial=!0,x.call(this),this.type="MeshLambertMaterial",this.color=new w(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Yt(t){this.isLineDashedMaterial=this.isMaterial=!0,x.call(this),this.type="LineDashedMaterial",this.color=new w(16777215),this.linewidth=1,this.scale=1,this.dashSize=3,this.gapSize=1,this.lights=!1,this.setValues(t)}function qt(t,e,n){this.isLoadingManager=!0;var i=this,r=!1,a=0,o=0;this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=n,this.itemStart=function(t){o++,r===!1&&void 0!==i.onStart&&i.onStart(t,a,o),r=!0},this.itemEnd=function(t){a++,void 0!==i.onProgress&&i.onProgress(t,a,o),a===o&&(r=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(t){void 0!==i.onError&&i.onError(t)}}function Zt(e){this.isXHRLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function Jt(e){this.isCompressedTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Qt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Kt(e){ +this.isImageLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function $t(e){this.isCubeTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function te(e){this.isTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function ee(t,e){this.isLight=!0,X.call(this),this.type="Light",this.color=new w(t),this.intensity=void 0!==e?e:1,this.receiveShadow=void 0}function ne(t,e,n){this.isHemisphereLight=!0,ee.call(this,t,n),this.type="HemisphereLight",this.castShadow=void 0,this.position.copy(X.DefaultUp),this.updateMatrix(),this.groundColor=new w(e)}function ie(t){this.isLightShadow=!0,this.camera=t,this.bias=0,this.radius=1,this.mapSize=new n(512,512),this.map=null,this.matrix=new a}function re(){this.isSpotLightShadow=!0,ie.call(this,new mt(50,1,.5,500))}function ae(t,e,n,i,r,a){this.isSpotLight=!0,ee.call(this,t,e),this.type="SpotLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(t){this.intensity=t/Math.PI}}),this.distance=void 0!==n?n:0,this.angle=void 0!==i?i:Math.PI/3,this.penumbra=void 0!==r?r:0,this.decay=void 0!==a?a:1,this.shadow=new re}function oe(t,e,n,i){this.isPointLight=!0,ee.call(this,t,e),this.type="PointLight",Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(t){this.intensity=t/(4*Math.PI)}}),this.distance=void 0!==n?n:0,this.decay=void 0!==i?i:1,this.shadow=new ie(new mt(90,1,.5,500))}function se(t){this.isDirectionalLightShadow=!0,ie.call(this,new gt((-5),5,5,(-5),.5,500))}function he(t,e){this.isDirectionalLight=!0,ee.call(this,t,e),this.type="DirectionalLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,this.shadow=new se}function ce(t,e){this.isAmbientLight=!0,ee.call(this,t,e),this.type="AmbientLight",this.castShadow=void 0}function le(t,e,n,i){this.isInterpolant=!0,this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==i?i:new e.constructor(n),this.sampleValues=e,this.valueSize=n}function ue(t,e,n,i){this.isCubicInterpolant=!0,le.call(this,t,e,n,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0}function de(t,e,n,i){this.isLinearInterpolant=!0,le.call(this,t,e,n,i)}function pe(t,e,n,i){this.isDiscreteInterpolant=!0,le.call(this,t,e,n,i)}function fe(e,n,i,r){if(this.isKeyframeTrack=!0,void 0===e)throw new Error("track name is undefined");if(void 0===n||0===n.length)throw new Error("no keyframes in track named "+e);this.name=e,this.times=t.AnimationUtils.convertArray(n,this.TimeBufferType),this.values=t.AnimationUtils.convertArray(i,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation),this.validate(),this.optimize()}function me(t,e,n,i){this.isVectorKeyframeTrack=!0,fe.call(this,t,e,n,i)}function ge(t,e,n,i){this.isQuaternionLinearInterpolant=!0,le.call(this,t,e,n,i)}function ve(t,e,n,i){this.isQuaternionKeyframeTrack=!0,fe.call(this,t,e,n,i)}function ye(t,e,n,i){this.isNumberKeyframeTrack=!0,fe.call(this,t,e,n,i)}function xe(t,e,n,i){this.isStringKeyframeTrack=!0,fe.call(this,t,e,n,i)}function be(t,e,n){this.isBooleanKeyframeTrack=!0,fe.call(this,t,e,n)}function _e(t,e,n,i){this.isColorKeyframeTrack=!0,fe.call(this,t,e,n,i)}function we(t,e,n,i){fe.apply(this,arguments)}function Me(e,n,i){this.isAnimationClip=!0,this.name=e,this.tracks=i,this.duration=void 0!==n?n:-1,this.uuid=t.Math.generateUUID(),this.duration<0&&this.resetDuration(),this.trim(),this.optimize()}function Ee(e){this.isMaterialLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this.textures={}}function Se(e){this.isBufferGeometryLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function Te(){this.isLoader=!0,this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){}}function Ae(e){this.isJSONLoader=!0,"boolean"==typeof e&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),e=void 0),this.manager=void 0!==e?e:t.DefaultLoadingManager,this.withCredentials=!1}function Le(e){this.isObjectLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this.texturePath=""}function Re(){this.isCurve=!0}function Ce(t,e){this.isLineCurve=this.isCurve=!0,this.v1=t,this.v2=e}function Pe(){this.isCurvePath=!0,this.curves=[],this.autoClose=!1}function Ue(t,e,n,i,r,a,o,s){this.isEllipseCurve=this.isCurve=!0,this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s||0}function Ie(t){this.isSplineCurve=this.isCurve=!0,this.points=void 0==t?[]:t}function De(t,e,n,i){this.isCubicBezierCurve=this.isCurve=!0,this.v0=t,this.v1=e,this.v2=n,this.v3=i}function Ne(t,e,n){this.isQuadraticBezierCurve=this.isCurve=!0,this.v0=t,this.v1=e,this.v2=n}function Oe(t,e,i,r,a,o){function h(t,e,n){return P.vertices.push(new s(t,e,n))-1}this.isTubeGeometry=this.isGeometry=!0,q.call(this),this.type="TubeGeometry",this.parameters={path:t,segments:e,radius:i,radialSegments:r,closed:a,taper:o},e=e||64,i=i||1,r=r||8,a=a||!1,o=o||Oe.NoTaper;var c,l,u,d,p,f,m,g,v,y,x,b,_,w,M,E,S,T,A,L,R,C=[],P=this,U=e+1,I=new s,D=new Oe.FrenetFrames(t,e,a),N=D.tangents,O=D.normals,F=D.binormals;for(this.tangents=N,this.normals=O,this.binormals=F,y=0;ythis.points.length-2?this.points.length-1:i+1,d[3]=i>this.points.length-3?this.points.length-1:i+2,h=this.points[d[0]],c=this.points[d[1]],l=this.points[d[2]],u=this.points[d[3]],a=r*r,o=r*a,p.x=e(h.x,c.x,l.x,u.x,r,a,o),p.y=e(h.y,c.y,l.y,u.y,r,a,o),p.z=e(h.z,c.z,l.z,u.z,r,a,o),p},this.getControlPointsArray=function(){var t,e,n=this.points.length,i=[];for(t=0;t0)&&E.push(T,A,R),(g!==n-1||h65535?z:F)(E,1)),this.addAttribute("position",l),this.addAttribute("normal",u),this.addAttribute("uv",d),this.boundingSphere=new S(new s,t)}function En(t,e){this.isPointLightHelper=this.isMesh=!0,this.light=t,this.light.updateMatrixWorld();var n=new Mn(e,4,2),i=new ut({wireframe:!0,fog:!1});i.color.copy(this.light.color).multiplyScalar(this.light.intensity),dt.call(this,n,i),this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1}function Sn(t,e,n,i,r,a,o){this.isSphereGeometry=this.isGeometry=!0,q.call(this),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:n,phiStart:i,phiLength:r,thetaStart:a,thetaLength:o},this.fromBufferGeometry(new Mn(t,e,n,i,r,a,o))}function Tn(t,e){this.isHemisphereLightHelper=this.isObject3D=!0,X.call(this),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.colors=[new w,new w];var n=new Sn(e,4,2);n.rotateX(-Math.PI/2);for(var i=0,r=8;i0&&m++,e>0&&m++);var g=l(),v=u(),y=new U(new(v>65535?Uint32Array:Uint16Array)(v),1),x=new U(new Float32Array(3*g),3),b=new U(new Float32Array(3*g),3),_=new U(new Float32Array(2*g),2),w=0,M=0,E=[],S=i/2,T=0;d(),o===!1&&(t>0&&p(!0),e>0&&p(!1)),this.setIndex(y),this.addAttribute("position",x),this.addAttribute("normal",b),this.addAttribute("uv",_)}function Fn(t){this.isAxisHelper=this.isLineSegments=!0,t=t||1;var e=new Float32Array([0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t]),n=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]),i=new Q;i.addAttribute("position",new U(e,3)),i.addAttribute("color",new U(n,3));var r=new Rt({vertexColors:Ei});Pt.call(this,i,r)}function Bn(t,e,i){this.isParametricGeometry=this.isGeometry=!0,q.call(this),this.type="ParametricGeometry",this.parameters={func:t,slices:e,stacks:i};var r,a,o,s,h,c=this.vertices,l=this.faces,u=this.faceVertexUvs[0],d=e+1;for(r=0;r<=i;r++)for(h=r/i,a=0;a<=e;a++)s=a/e,o=t(s,h),c.push(o);var p,f,m,g,v,y,x,b;for(r=0;r.9&&L<.1&&(M<.2&&(w[0].x+=1),E<.2&&(w[1].x+=1),T<.2&&(w[2].x+=1))}for(var p=0,f=this.vertices.length;p65535?Uint32Array:Uint16Array)(d),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=new s,b=new s,_=new n,w=new s,M=new s,E=new s,S=new s,T=new s;for(c=0;c<=i;++c){var A=c/i*a*Math.PI*2;for(h(A,a,o,t,w),h(A+.01,a,o,t,M),S.subVectors(M,w),T.addVectors(M,w),E.crossVectors(S,T),T.crossVectors(E,S),E.normalize(),T.normalize(),l=0;l<=r;++l){var L=l/r*Math.PI*2,R=-e*Math.cos(L),C=e*Math.sin(L);x.x=w.x+(R*T.x+C*E.x),x.y=w.y+(R*T.y+C*E.y),x.z=w.z+(R*T.z+C*E.z),f.setXYZ(v,x.x,x.y,x.z),b.subVectors(x,w).normalize(),m.setXYZ(v,b.x,b.y,b.z),_.x=c/i,_.y=l/r,g.setXY(v,_.x,_.y),v++}}for(l=1;l<=i;l++)for(c=1;c<=r;c++){var P=(r+1)*(l-1)+(c-1),I=(r+1)*l+(c-1),D=(r+1)*l+c,N=(r+1)*(l-1)+c;p.setX(y,P),y++,p.setX(y,I),y++,p.setX(y,N),y++,p.setX(y,I),y++,p.setX(y,D),y++,p.setX(y,N),y++}this.setIndex(p),this.addAttribute("position",f),this.addAttribute("normal",m),this.addAttribute("uv",g)}function Wn(t,e,n,i,r,a,o){this.isTorusKnotGeometry=this.isGeometry=!0,q.call(this),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,tubularSegments:n,radialSegments:i,p:r,q:a},void 0!==o&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead."),this.fromBufferGeometry(new jn(t,e,n,i,r,a)),this.mergeVertices()}function Xn(t,e,n,i,r){this.isTorusBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="TorusBufferGeometry",this.parameters={radius:t,tube:e,radialSegments:n,tubularSegments:i,arc:r},t=t||100,e=e||40,n=Math.floor(n)||8,i=Math.floor(i)||6,r=r||2*Math.PI;var a,o,h=(n+1)*(i+1),c=n*i*2*3,l=new(c>65535?Uint32Array:Uint16Array)(c),u=new Float32Array(3*h),d=new Float32Array(3*h),p=new Float32Array(2*h),f=0,m=0,g=0,v=new s,y=new s,x=new s;for(a=0;a<=n;a++)for(o=0;o<=i;o++){var b=o/i*r,_=a/n*Math.PI*2;y.x=(t+e*Math.cos(_))*Math.cos(b),y.y=(t+e*Math.cos(_))*Math.sin(b),y.z=e*Math.sin(_),u[f]=y.x,u[f+1]=y.y,u[f+2]=y.z,v.x=t*Math.cos(b),v.y=t*Math.sin(b),x.subVectors(y,v).normalize(),d[f]=x.x,d[f+1]=x.y,d[f+2]=x.z,p[m]=o/i,p[m+1]=a/n,f+=3,m+=2}for(a=1;a<=n;a++)for(o=1;o<=i;o++){var w=(i+1)*a+o-1,M=(i+1)*(a-1)+o-1,E=(i+1)*(a-1)+o,S=(i+1)*a+o;l[g]=w,l[g+1]=M,l[g+2]=S,l[g+3]=M,l[g+4]=E,l[g+5]=S, +g+=6}this.setIndex(new U(l,1)),this.addAttribute("position",new U(u,3)),this.addAttribute("normal",new U(d,3)),this.addAttribute("uv",new U(p,2))}function Yn(t,e,n,i,r){this.isTorusGeometry=this.isGeometry=!0,q.call(this),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:n,tubularSegments:i,arc:r},this.fromBufferGeometry(new Xn(t,e,n,i,r))}function qn(t,e){this.isTextGeometry=this.isExtrudeGeometry=this.isGeometry=!0,e=e||{};var n=e.font;if((n&&n.isFont)===!1)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new q;var i=n.generateShapes(t,e.size,e.curveSegments);e.amount=void 0!==e.height?e.height:50,void 0===e.bevelThickness&&(e.bevelThickness=10),void 0===e.bevelSize&&(e.bevelSize=8),void 0===e.bevelEnabled&&(e.bevelEnabled=!1),Fe.call(this,i,e),this.type="TextGeometry"}function Zn(t,e,i,r,a,o){this.isRingBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="RingBufferGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:i,phiSegments:r,thetaStart:a,thetaLength:o},t=t||20,e=e||50,a=void 0!==a?a:0,o=void 0!==o?o:2*Math.PI,i=void 0!==i?Math.max(3,i):8,r=void 0!==r?Math.max(1,r):1;var h,c,l,u=(i+1)*(r+1),d=i*r*2*3,p=new U(new(d>65535?Uint32Array:Uint16Array)(d),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=t,b=(e-t)/r,_=new s,w=new n;for(c=0;c<=r;c++){for(l=0;l<=i;l++)h=a+l/i*o,_.x=x*Math.cos(h),_.y=x*Math.sin(h),f.setXYZ(v,_.x,_.y,_.z),m.setXYZ(v,0,0,1),w.x=(_.x/e+1)/2,w.y=(_.y/e+1)/2,g.setXY(v,w.x,w.y),v++;x+=b}for(c=0;c65535?Uint32Array:Uint16Array)(u),1),p=new U(new Float32Array(3*l),3),f=new U(new Float32Array(2*l),2),m=0,g=0,v=(1/(e.length-1),1/i),y=new s,x=new n;for(h=0;h<=i;h++){var b=r+h*v*a,_=Math.sin(b),w=Math.cos(b);for(c=0;c<=e.length-1;c++)y.x=e[c].x*_,y.y=e[c].y,y.z=e[c].x*w,p.setXYZ(m,y.x,y.y,y.z),x.x=h/i,x.y=c/(e.length-1),f.setXY(m,x.x,x.y),m++}for(h=0;h>=4,n[r]=e[19===r?3&t|8:t]);return n.join("")}}(),clamp:function(t,e,n){return Math.max(e,Math.min(n,t))},euclideanModulo:function(t,e){return(t%e+e)%e},mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*(3-2*t))},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*t*(t*(6*t-15)+10))},random16:function(){return console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead."),Math.random()},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},degToRad:function(e){return e*t.Math.DEG2RAD},radToDeg:function(e){return e*t.Math.RAD2DEG},isPowerOfTwo:function(t){return 0===(t&t-1)&&0!==t},nearestPowerOfTwo:function(t){return Math.pow(2,Math.round(Math.log(t)/Math.LN2))},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}},n.prototype={constructor:n,get width(){return this.x},set width(t){this.x=t},get height(){return this.y},set height(t){this.y=t},set:function(t,e){return this.x=t,this.y=e,this},setScalar:function(t){return this.x=t,this.y=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(t){return this.x=t.x,this.y=t.y,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)},addScalar:function(t){return this.x+=t,this.y+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)},subScalar:function(t){return this.x-=t,this.y-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t):(this.x=0,this.y=0),this},divide:function(t){return this.x/=t.x,this.y/=t.y,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this},clampScalar:function(){var t,e;return function(i,r){return void 0===t&&(t=new n,e=new n),t.set(i,i),e.set(r,r),this.clamp(t,e)}}(),clampLength:function(t,e){var n=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,n))/n)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(t){return this.x*t.x+this.y*t.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var t=Math.atan2(this.y,this.x);return t<0&&(t+=2*Math.PI),t},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,n=this.y-t.y;return e*e+n*n},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this},lerpVectors:function(t,e,n){return this.subVectors(e,t).multiplyScalar(n).add(t)},equals:function(t){return t.x===this.x&&t.y===this.y},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t},fromAttribute:function(t,e,n){return void 0===n&&(n=0),e=e*t.itemSize+n,this.x=t.array[e],this.y=t.array[e+1],this},rotateAround:function(t,e){var n=Math.cos(e),i=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*n-a*i+t.x,this.y=r*i+a*n+t.y,this}},i.DEFAULT_IMAGE=void 0,i.DEFAULT_MAPPING=cr,i.prototype={constructor:i,set needsUpdate(t){t===!0&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.encoding=t.encoding,this},toJSON:function(e){function n(t){var e;return void 0!==t.toDataURL?e=t:(e=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0,t.width,t.height)),e.width>2048||e.height>2048?e.toDataURL("image/jpeg",.6):e.toDataURL("image/png")}if(void 0!==e.textures[this.uuid])return e.textures[this.uuid];var i={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var r=this.image;void 0===r.uuid&&(r.uuid=t.Math.generateUUID()),void 0===e.images[r.uuid]&&(e.images[r.uuid]={uuid:r.uuid,url:n(r)}),i.image=r.uuid}return e.textures[this.uuid]=i,i},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(t){if(this.mapping===cr){if(t.multiply(this.repeat),t.add(this.offset),t.x<0||t.x>1)switch(this.wrapS){case vr:t.x=t.x-Math.floor(t.x);break;case yr:t.x=t.x<0?0:1;break;case xr:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case vr:t.y=t.y-Math.floor(t.y);break;case yr:t.y=t.y<0?0:1;break;case xr:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}this.flipY&&(t.y=1-t.y)}}},Object.assign(i.prototype,e.prototype);var _a=0;a.prototype={constructor:a,set:function(t,e,n,i,r,a,o,s,h,c,l,u,d,p,f,m){var g=this.elements;return g[0]=t,g[4]=e,g[8]=n,g[12]=i,g[1]=r,g[5]=a,g[9]=o,g[13]=s,g[2]=h,g[6]=c,g[10]=l,g[14]=u,g[3]=d,g[7]=p,g[11]=f,g[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},clone:function(){return(new a).fromArray(this.elements)},copy:function(t){return this.elements.set(t.elements),this},copyPosition:function(t){var e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this},extractBasis:function(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this},makeBasis:function(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this},extractRotation:function(){var t;return function(e){void 0===t&&(t=new s);var n=this.elements,i=e.elements,r=1/t.setFromMatrixColumn(e,0).length(),a=1/t.setFromMatrixColumn(e,1).length(),o=1/t.setFromMatrixColumn(e,2).length();return n[0]=i[0]*r,n[1]=i[1]*r,n[2]=i[2]*r,n[4]=i[4]*a,n[5]=i[5]*a,n[6]=i[6]*a,n[8]=i[8]*o,n[9]=i[9]*o,n[10]=i[10]*o,this}}(),makeRotationFromEuler:function(t){(t&&t.isEuler)===!1&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var e=this.elements,n=t.x,i=t.y,r=t.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(i),h=Math.sin(i),c=Math.cos(r),l=Math.sin(r);if("XYZ"===t.order){var u=a*c,d=a*l,p=o*c,f=o*l;e[0]=s*c,e[4]=-s*l,e[8]=h,e[1]=d+p*h,e[5]=u-f*h,e[9]=-o*s,e[2]=f-u*h,e[6]=p+d*h,e[10]=a*s}else if("YXZ"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m+y*o,e[4]=v*o-g,e[8]=a*h,e[1]=a*l,e[5]=a*c,e[9]=-o,e[2]=g*o-v,e[6]=y+m*o,e[10]=a*s}else if("ZXY"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m-y*o,e[4]=-a*l,e[8]=v+g*o,e[1]=g+v*o,e[5]=a*c,e[9]=y-m*o,e[2]=-a*h,e[6]=o,e[10]=a*s}else if("ZYX"===t.order){var u=a*c,d=a*l,p=o*c,f=o*l;e[0]=s*c,e[4]=p*h-d,e[8]=u*h+f,e[1]=s*l,e[5]=f*h+u,e[9]=d*h-p,e[2]=-h,e[6]=o*s,e[10]=a*s}else if("YZX"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=w-x*l,e[8]=_*l+b,e[1]=l,e[5]=a*c,e[9]=-o*c,e[2]=-h*c,e[6]=b*l+_,e[10]=x-w*l}else if("XZY"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=-l,e[8]=h*c,e[1]=x*l+w,e[5]=a*c,e[9]=b*l-_,e[2]=_*l-b,e[6]=o*c,e[10]=w*l+x}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},makeRotationFromQuaternion:function(t){var e=this.elements,n=t.x,i=t.y,r=t.z,a=t.w,o=n+n,s=i+i,h=r+r,c=n*o,l=n*s,u=n*h,d=i*s,p=i*h,f=r*h,m=a*o,g=a*s,v=a*h;return e[0]=1-(d+f),e[4]=l-v,e[8]=u+g,e[1]=l+v,e[5]=1-(c+f),e[9]=p-m,e[2]=u-g,e[6]=p+m,e[10]=1-(c+d),e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},lookAt:function(){var t,e,n;return function(i,r,a){void 0===t&&(t=new s,e=new s,n=new s);var o=this.elements;return n.subVectors(i,r).normalize(),0===n.lengthSq()&&(n.z=1),t.crossVectors(a,n).normalize(),0===t.lengthSq()&&(n.z+=1e-4,t.crossVectors(a,n).normalize()),e.crossVectors(n,t),o[0]=t.x,o[4]=e.x,o[8]=n.x,o[1]=t.y,o[5]=e.y,o[9]=n.y,o[2]=t.z,o[6]=e.z,o[10]=n.z,this}}(),multiply:function(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)},premultiply:function(t){return this.multiplyMatrices(t,this)},multiplyMatrices:function(t,e){var n=t.elements,i=e.elements,r=this.elements,a=n[0],o=n[4],s=n[8],h=n[12],c=n[1],l=n[5],u=n[9],d=n[13],p=n[2],f=n[6],m=n[10],g=n[14],v=n[3],y=n[7],x=n[11],b=n[15],_=i[0],w=i[4],M=i[8],E=i[12],S=i[1],T=i[5],A=i[9],L=i[13],R=i[2],C=i[6],P=i[10],U=i[14],I=i[3],D=i[7],N=i[11],O=i[15];return r[0]=a*_+o*S+s*R+h*I,r[4]=a*w+o*T+s*C+h*D,r[8]=a*M+o*A+s*P+h*N,r[12]=a*E+o*L+s*U+h*O,r[1]=c*_+l*S+u*R+d*I,r[5]=c*w+l*T+u*C+d*D,r[9]=c*M+l*A+u*P+d*N,r[13]=c*E+l*L+u*U+d*O,r[2]=p*_+f*S+m*R+g*I,r[6]=p*w+f*T+m*C+g*D,r[10]=p*M+f*A+m*P+g*N,r[14]=p*E+f*L+m*U+g*O,r[3]=v*_+y*S+x*R+b*I,r[7]=v*w+y*T+x*C+b*D,r[11]=v*M+y*A+x*P+b*N,r[15]=v*E+y*L+x*U+b*O,this},multiplyToArray:function(t,e,n){var i=this.elements;return this.multiplyMatrices(t,e),n[0]=i[0],n[1]=i[1],n[2]=i[2],n[3]=i[3],n[4]=i[4],n[5]=i[5],n[6]=i[6],n[7]=i[7],n[8]=i[8],n[9]=i[9],n[10]=i[10],n[11]=i[11],n[12]=i[12],n[13]=i[13],n[14]=i[14],n[15]=i[15],this},multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this},applyToVector3Array:function(){var t;return function(e,n,i){void 0===t&&(t=new s),void 0===n&&(n=0),void 0===i&&(i=e.length);for(var r=0,a=n;r0?(e=.5/Math.sqrt(d+1),this._w=.25/e,this._x=(l-h)*e,this._y=(a-c)*e,this._z=(o-r)*e):i>s&&i>u?(e=2*Math.sqrt(1+i-s-u),this._w=(l-h)/e,this._x=.25*e,this._y=(r+o)/e,this._z=(a+c)/e):s>u?(e=2*Math.sqrt(1+s-i-u),this._w=(a-c)/e,this._x=(r+o)/e,this._y=.25*e,this._z=(h+l)/e):(e=2*Math.sqrt(1+u-i-s),this._w=(o-r)/e,this._x=(a+c)/e,this._y=(h+l)/e,this._z=.25*e),this.onChangeCallback(),this},setFromUnitVectors:function(){var t,e,n=1e-6;return function(i,r){return void 0===t&&(t=new s),e=i.dot(r)+1,eMath.abs(i.z)?t.set(-i.y,i.x,0):t.set(0,-i.z,i.y)):t.crossVectors(i,r),this._x=t.x,this._y=t.y,this._z=t.z,this._w=e,this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this.onChangeCallback(),this},dot:function(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this.onChangeCallback(),this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)},premultiply:function(t){return this.multiplyQuaternions(t,this)},multiplyQuaternions:function(t,e){var n=t._x,i=t._y,r=t._z,a=t._w,o=e._x,s=e._y,h=e._z,c=e._w;return this._x=n*c+a*o+i*h-r*s,this._y=i*c+a*s+r*o-n*h,this._z=r*c+a*h+n*s-i*o,this._w=a*c-n*o-i*s-r*h,this.onChangeCallback(),this},slerp:function(t,e){if(0===e)return this;if(1===e)return this.copy(t);var n=this._x,i=this._y,r=this._z,a=this._w,o=a*t._w+n*t._x+i*t._y+r*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=a,this._x=n,this._y=i,this._z=r,this;var s=Math.sqrt(1-o*o);if(Math.abs(s)<.001)return this._w=.5*(a+this._w),this._x=.5*(n+this._x),this._y=.5*(i+this._y),this._z=.5*(r+this._z),this;var h=Math.atan2(s,o),c=Math.sin((1-e)*h)/s,l=Math.sin(e*h)/s;return this._w=a*c+this._w*l,this._x=n*c+this._x*l,this._y=i*c+this._y*l,this._z=r*c+this._z*l,this.onChangeCallback(),this},equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w},fromArray:function(t,e){return void 0===e&&(e=0),this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this.onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t},onChange:function(t){return this.onChangeCallback=t,this},onChangeCallback:function(){}},Object.assign(o,{slerp:function(t,e,n,i){return n.copy(t).slerp(e,i)},slerpFlat:function(t,e,n,i,r,a,o){var s=n[i+0],h=n[i+1],c=n[i+2],l=n[i+3],u=r[a+0],d=r[a+1],p=r[a+2],f=r[a+3];if(l!==f||s!==u||h!==d||c!==p){var m=1-o,g=s*u+h*d+c*p+l*f,v=g>=0?1:-1,y=1-g*g;if(y>Number.EPSILON){var x=Math.sqrt(y),b=Math.atan2(x,g*v);m=Math.sin(m*b)/x,o=Math.sin(o*b)/x}var _=o*v;if(s=s*m+u*_,h=h*m+d*_,c=c*m+p*_,l=l*m+f*_,m===1-o){var w=1/Math.sqrt(s*s+h*h+c*c+l*l);s*=w,h*=w,c*=w,l*=w}}t[e]=s,t[e+1]=h,t[e+2]=c,t[e+3]=l}}),s.prototype={constructor:s,set:function(t,e,n){return this.x=t,this.y=e,this.z=n,this},setScalar:function(t){return this.x=t,this.y=t,this.z=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x,this.y*=t.y,this.z*=t.z,this)},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t,this.z*=t):(this.x=0,this.y=0,this.z=0),this},multiplyVectors:function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},applyEuler:function(){var t;return function(e){return(e&&e.isEuler)===!1&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),void 0===t&&(t=new o),this.applyQuaternion(t.setFromEuler(e))}}(),applyAxisAngle:function(){var t;return function(e,n){return void 0===t&&(t=new o), +this.applyQuaternion(t.setFromAxisAngle(e,n))}}(),applyMatrix3:function(t){var e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*i,this.y=r[1]*e+r[4]*n+r[7]*i,this.z=r[2]*e+r[5]*n+r[8]*i,this},applyMatrix4:function(t){var e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i+r[12],this.y=r[1]*e+r[5]*n+r[9]*i+r[13],this.z=r[2]*e+r[6]*n+r[10]*i+r[14],this},applyProjection:function(t){var e=this.x,n=this.y,i=this.z,r=t.elements,a=1/(r[3]*e+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*i+r[12])*a,this.y=(r[1]*e+r[5]*n+r[9]*i+r[13])*a,this.z=(r[2]*e+r[6]*n+r[10]*i+r[14])*a,this},applyQuaternion:function(t){var e=this.x,n=this.y,i=this.z,r=t.x,a=t.y,o=t.z,s=t.w,h=s*e+a*i-o*n,c=s*n+o*e-r*i,l=s*i+r*n-a*e,u=-r*e-a*n-o*i;return this.x=h*s+u*-r+c*-o-l*-a,this.y=c*s+u*-a+l*-r-h*-o,this.z=l*s+u*-o+h*-a-c*-r,this},project:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.projectionMatrix,t.getInverse(e.matrixWorld)),this.applyProjection(t)}}(),unproject:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.matrixWorld,t.getInverse(e.projectionMatrix)),this.applyProjection(t)}}(),transformDirection:function(t){var e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i,this.y=r[1]*e+r[5]*n+r[9]*i,this.z=r[2]*e+r[6]*n+r[10]*i,this.normalize()},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this},clampScalar:function(){var t,e;return function(n,i){return void 0===t&&(t=new s,e=new s),t.set(n,n,n),e.set(i,i,i),this.clamp(t,e)}}(),clampLength:function(t,e){var n=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,n))/n)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this},lerpVectors:function(t,e,n){return this.subVectors(e,t).multiplyScalar(n).add(t)},cross:function(t,e){if(void 0!==e)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e);var n=this.x,i=this.y,r=this.z;return this.x=i*t.z-r*t.y,this.y=r*t.x-n*t.z,this.z=n*t.y-i*t.x,this},crossVectors:function(t,e){var n=t.x,i=t.y,r=t.z,a=e.x,o=e.y,s=e.z;return this.x=i*s-r*o,this.y=r*a-n*s,this.z=n*o-i*a,this},projectOnVector:function(t){var e=t.dot(this)/t.lengthSq();return this.copy(t).multiplyScalar(e)},projectOnPlane:function(){var t;return function(e){return void 0===t&&(t=new s),t.copy(this).projectOnVector(e),this.sub(t)}}(),reflect:function(){var t;return function(e){return void 0===t&&(t=new s),this.sub(t.copy(e).multiplyScalar(2*this.dot(e)))}}(),angleTo:function(e){var n=this.dot(e)/Math.sqrt(this.lengthSq()*e.lengthSq());return Math.acos(t.Math.clamp(n,-1,1))},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return e*e+n*n+i*i},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)},setFromSpherical:function(t){var e=Math.sin(t.phi)*t.radius;return this.x=e*Math.sin(t.theta),this.y=Math.cos(t.phi)*t.radius,this.z=e*Math.cos(t.theta),this},setFromMatrixPosition:function(t){return this.setFromMatrixColumn(t,3)},setFromMatrixScale:function(t){var e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=i,this},setFromMatrixColumn:function(t,e){if("number"==typeof t){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var n=t;t=e,e=n}return this.fromArray(t.elements,4*e)},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t},fromAttribute:function(t,e,n){return void 0===n&&(n=0),e=e*t.itemSize+n,this.x=t.array[e],this.y=t.array[e+1],this.z=t.array[e+2],this}},c.prototype={constructor:c,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,n=t.length;ethis.max.x||t.ythis.max.y)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y},getParameter:function(t,e){var i=e||new n;return i.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)},clampPoint:function(t,e){var i=e||new n;return i.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new n;return function(e){var n=t.copy(e).clamp(this.min,this.max);return n.sub(e).length()}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},u.prototype=Object.create(i.prototype),u.prototype.constructor=u,Object.defineProperty(u.prototype,"images",{get:function(){return this.image},set:function(t){this.image=t}}),t.WebGLUniforms=function(){var t=new i,e=new u,n=function(){this.seq=[],this.map={}},r=[],a=[],o=function(t,e,n){var i=t[0];if(i<=0||i>0)return t;var a=e*n,o=r[a];if(void 0===o&&(o=new Float32Array(a),r[a]=o),0!==e){i.toArray(o,0);for(var s=1,h=0;s!==e;++s)h+=n,t[s].toArray(o,h)}return o},s=function(t,e){var n=a[e];void 0===n&&(n=new Int32Array(e),a[e]=n);for(var i=0;i!==e;++i)n[i]=t.allocTextureUnit();return n},h=function(t,e){t.uniform1f(this.addr,e)},c=function(t,e){t.uniform1i(this.addr,e)},l=function(t,e){void 0===e.x?t.uniform2fv(this.addr,e):t.uniform2f(this.addr,e.x,e.y)},d=function(t,e){void 0!==e.x?t.uniform3f(this.addr,e.x,e.y,e.z):void 0!==e.r?t.uniform3f(this.addr,e.r,e.g,e.b):t.uniform3fv(this.addr,e)},p=function(t,e){void 0===e.x?t.uniform4fv(this.addr,e):t.uniform4f(this.addr,e.x,e.y,e.z,e.w)},f=function(t,e){t.uniformMatrix2fv(this.addr,!1,e.elements||e)},m=function(t,e){t.uniformMatrix3fv(this.addr,!1,e.elements||e)},g=function(t,e){t.uniformMatrix4fv(this.addr,!1,e.elements||e)},v=function(e,n,i){var r=i.allocTextureUnit();e.uniform1i(this.addr,r),i.setTexture2D(n||t,r)},y=function(t,n,i){var r=i.allocTextureUnit();t.uniform1i(this.addr,r),i.setTextureCube(n||e,r)},x=function(t,e){t.uniform2iv(this.addr,e)},b=function(t,e){t.uniform3iv(this.addr,e)},_=function(t,e){t.uniform4iv(this.addr,e)},w=function(t){switch(t){case 5126:return h;case 35664:return l;case 35665:return d;case 35666:return p;case 35674:return f;case 35675:return m;case 35676:return g;case 35678:return v;case 35680:return y;case 5124:case 35670:return c;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},M=function(t,e){t.uniform1fv(this.addr,e)},E=function(t,e){t.uniform1iv(this.addr,e)},S=function(t,e){t.uniform2fv(this.addr,o(e,this.size,2))},T=function(t,e){t.uniform3fv(this.addr,o(e,this.size,3))},A=function(t,e){t.uniform4fv(this.addr,o(e,this.size,4))},L=function(t,e){t.uniformMatrix2fv(this.addr,!1,o(e,this.size,4))},R=function(t,e){t.uniformMatrix3fv(this.addr,!1,o(e,this.size,9))},C=function(t,e){t.uniformMatrix4fv(this.addr,!1,o(e,this.size,16))},P=function(e,n,i){var r=n.length,a=s(i,r);e.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)i.setTexture2D(n[o]||t,a[o])},U=function(t,n,i){var r=n.length,a=s(i,r);t.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)i.setTextureCube(n[o]||e,a[o])},I=function(t){switch(t){case 5126:return M;case 35664:return S;case 35665:return T;case 35666:return A;case 35674:return L;case 35675:return R;case 35676:return C;case 35678:return P;case 35680:return U;case 5124:case 35670:return E;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},D=function(t,e,n){this.id=t,this.addr=n,this.setValue=w(e.type)},N=function(t,e,n){this.id=t,this.addr=n,this.size=e.size,this.setValue=I(e.type)},O=function(t){this.id=t,n.call(this)};O.prototype.setValue=function(t,e){for(var n=this.seq,i=0,r=n.length;i!==r;++i){var a=n[i];a.setValue(t,e[a.id])}};var F=/([\w\d_]+)(\])?(\[|\.)?/g,B=function(t,e){t.seq.push(e),t.map[e.id]=e},z=function(t,e,n){var i=t.name,r=i.length;for(F.lastIndex=0;;){var a=F.exec(i),o=F.lastIndex,s=a[1],h="]"===a[2],c=a[3];if(h&&(s=0|s),void 0===c||"["===c&&o+2===r){B(n,void 0===c?new D(s,t,e):new N(s,t,e));break}var l=n.map,u=l[s];void 0===u&&(u=new O(s),B(n,u)),n=u}},G=function(t,e,i){n.call(this),this.renderer=i;for(var r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),a=0;a!==r;++a){var o=t.getActiveUniform(e,a),s=o.name,h=t.getUniformLocation(e,s);z(o,h,this)}};return G.prototype.setValue=function(t,e,n){var i=this.map[e];void 0!==i&&i.setValue(t,n,this.renderer)},G.prototype.set=function(t,e,n){var i=this.map[n];void 0!==i&&i.setValue(t,e[n],this.renderer)},G.prototype.setOptional=function(t,e,n){var i=e[n];void 0!==i&&this.setValue(t,n,i)},G.upload=function(t,e,n,i){for(var r=0,a=e.length;r!==a;++r){var o=e[r],s=n[o.id];s.needsUpdate!==!1&&o.setValue(t,s.value,i)}},G.seqWithValue=function(t,e){for(var n=[],i=0,r=t.length;i!==r;++i){var a=t[i];a.id in e&&n.push(a)}return n},G.splitDynamic=function(t,e){for(var n=null,i=t.length,r=0,a=0;a!==i;++a){var o=t[a],s=e[o.id];s&&s.dynamic===!0?(null===n&&(n=[]),n.push(o)):(ry&&v>x?vx?y0&&(i.alphaTest=this.alphaTest),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=this.premultipliedAlpha),this.wireframe===!0&&(i.wireframe=this.wireframe),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),n){var r=e(t.textures),a=e(t.images);r.length>0&&(i.textures=r),a.length>0&&(i.images=a)}return i},clone:function(){return(new this.constructor).copy(this)},copy:function(t){this.name=t.name,this.fog=t.fog,this.lights=t.lights,this.blending=t.blending,this.side=t.side,this.shading=t.shading,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.alphaTest=t.alphaTest,this.premultipliedAlpha=t.premultipliedAlpha,this.overdraw=t.overdraw,this.visible=t.visible,this.clipShadows=t.clipShadows;var e=t.clippingPlanes,n=null;if(null!==e){var i=e.length;n=new Array(i);for(var r=0;r!==i;++r)n[r]=e[r].clone()}return this.clippingPlanes=n,this},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}},Object.assign(x.prototype,e.prototype);var wa=0;t.UniformsUtils={merge:function(t){for(var e={},n=0;n>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this},setRGB:function(t,e,n){return this.r=t,this.g=e,this.b=n,this},setHSL:function(){function e(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+6*(e-t)*(2/3-n):t}return function(n,i,r){if(n=t.Math.euclideanModulo(n,1),i=t.Math.clamp(i,0,1),r=t.Math.clamp(r,0,1),0===i)this.r=this.g=this.b=r;else{var a=r<=.5?r*(1+i):r+i-r*i,o=2*r-a;this.r=e(o,a,n+1/3),this.g=e(o,a,n),this.b=e(o,a,n-1/3)}return this}}(),setStyle:function(e){function n(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}var i;if(i=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(e)){var r,a=i[1],o=i[2];switch(a){case"rgb":case"rgba":if(r=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(255,parseInt(r[1],10))/255,this.g=Math.min(255,parseInt(r[2],10))/255,this.b=Math.min(255,parseInt(r[3],10))/255,n(r[5]),this;if(r=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(100,parseInt(r[1],10))/100,this.g=Math.min(100,parseInt(r[2],10))/100,this.b=Math.min(100,parseInt(r[3],10))/100,n(r[5]),this;break;case"hsl":case"hsla":if(r=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o)){var s=parseFloat(r[1])/360,h=parseInt(r[2],10)/100,c=parseInt(r[3],10)/100;return n(r[5]),this.setHSL(s,h,c)}}}else if(i=/^\#([A-Fa-f0-9]+)$/.exec(e)){var l=i[1],u=l.length;if(3===u)return this.r=parseInt(l.charAt(0)+l.charAt(0),16)/255,this.g=parseInt(l.charAt(1)+l.charAt(1),16)/255,this.b=parseInt(l.charAt(2)+l.charAt(2),16)/255,this;if(6===u)return this.r=parseInt(l.charAt(0)+l.charAt(1),16)/255,this.g=parseInt(l.charAt(2)+l.charAt(3),16)/255,this.b=parseInt(l.charAt(4)+l.charAt(5),16)/255,this}if(e&&e.length>0){var l=t.ColorKeywords[e];void 0!==l?this.setHex(l):console.warn("THREE.Color: Unknown color "+e)}return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},copyGammaToLinear:function(t,e){return void 0===e&&(e=2),this.r=Math.pow(t.r,e),this.g=Math.pow(t.g,e),this.b=Math.pow(t.b,e),this},copyLinearToGamma:function(t,e){void 0===e&&(e=2);var n=e>0?1/e:1;return this.r=Math.pow(t.r,n),this.g=Math.pow(t.g,n),this.b=Math.pow(t.b,n),this},convertGammaToLinear:function(){var t=this.r,e=this.g,n=this.b;return this.r=t*t,this.g=e*e,this.b=n*n,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(t){var e,n,i=t||{h:0,s:0,l:0},r=this.r,a=this.g,o=this.b,s=Math.max(r,a,o),h=Math.min(r,a,o),c=(h+s)/2;if(h===s)e=0,n=0;else{var l=s-h;switch(n=c<=.5?l/(s+h):l/(2-s-h),s){case r:e=(a-o)/l+(ar&&(r=c),l>a&&(a=l),u>o&&(o=u)}this.min.set(e,n,i),this.max.set(r,a,o)},setFromPoints:function(t){this.makeEmpty();for(var e=0,n=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z},getParameter:function(t,e){var n=e||new s;return n.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)},intersectsSphere:function(){var t;return function(e){return void 0===t&&(t=new s),this.clampPoint(e.center,t),t.distanceToSquared(e.center)<=e.radius*e.radius}}(),intersectsPlane:function(t){var e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=t.constant&&n>=t.constant},clampPoint:function(t,e){var n=e||new s;return n.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new s;return function(e){var n=t.copy(e).clamp(this.min,this.max);return n.sub(e).length()}}(),getBoundingSphere:function(){var t=new s;return function(e){var n=e||new S;return n.center=this.center(),n.radius=.5*this.size(t).length(),n}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},applyMatrix4:function(){var t=[new s,new s,new s,new s,new s,new s,new s,new s];return function(e){return this.isEmpty()?this:(t[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),t[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),t[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),t[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),t[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),t[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),t[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),t[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(t),this)}}(),translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},S.prototype={constructor:S,set:function(t,e){return this.center.copy(t),this.radius=e,this},setFromPoints:function(){var t=new E;return function(e,n){var i=this.center;void 0!==n?i.copy(n):t.setFromPoints(e).center(i);for(var r=0,a=0,o=e.length;athis.radius*this.radius&&(i.sub(this.center).normalize(),i.multiplyScalar(this.radius).add(this.center)),i},getBoundingBox:function(t){var e=t||new E;return e.set(this.center,this.center),e.expandByScalar(this.radius),e},applyMatrix4:function(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this},translate:function(t){return this.center.add(t),this},equals:function(t){return t.center.equals(this.center)&&t.radius===this.radius}},T.prototype={constructor:T,set:function(t,e,n,i,r,a,o,s,h){var c=this.elements;return c[0]=t,c[1]=i,c[2]=o,c[3]=e,c[4]=r,c[5]=s,c[6]=n,c[7]=a,c[8]=h,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(t){var e=t.elements;return this.set(e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]),this},setFromMatrix4:function(t){var e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this},applyToVector3Array:function(){var t;return function(e,n,i){void 0===t&&(t=new s),void 0===n&&(n=0),void 0===i&&(i=e.length);for(var r=0,a=n;r1))return i.copy(r).multiplyScalar(o).add(e.start)}else if(0===this.distanceToPoint(e.start))return i.copy(e.start)}}(),intersectsLine:function(t){var e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0},intersectsBox:function(t){return t.intersectsPlane(this)},intersectsSphere:function(t){return t.intersectsPlane(this)},coplanarPoint:function(t){var e=t||new s;return e.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var t=new s,e=new T;return function(n,i){var r=this.coplanarPoint(t).applyMatrix4(n),a=i||e.getNormalMatrix(n),o=this.normal.applyMatrix3(a).normalize();return this.constant=-r.dot(o),this}}(),translate:function(t){return this.constant=this.constant-t.dot(this.normal),this},equals:function(t){return t.normal.equals(this.normal)&&t.constant===this.constant}},L.prototype={constructor:L,set:function(t,e,n,i,r,a){var o=this.planes;return o[0].copy(t),o[1].copy(e),o[2].copy(n),o[3].copy(i),o[4].copy(r),o[5].copy(a),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){for(var e=this.planes,n=0;n<6;n++)e[n].copy(t.planes[n]);return this},setFromMatrix:function(t){var e=this.planes,n=t.elements,i=n[0],r=n[1],a=n[2],o=n[3],s=n[4],h=n[5],c=n[6],l=n[7],u=n[8],d=n[9],p=n[10],f=n[11],m=n[12],g=n[13],v=n[14],y=n[15];return e[0].setComponents(o-i,l-s,f-u,y-m).normalize(),e[1].setComponents(o+i,l+s,f+u,y+m).normalize(),e[2].setComponents(o+r,l+h,f+d,y+g).normalize(),e[3].setComponents(o-r,l-h,f-d,y-g).normalize(),e[4].setComponents(o-a,l-c,f-p,y-v).normalize(),e[5].setComponents(o+a,l+c,f+p,y+v).normalize(),this},intersectsObject:function(){var t=new S;return function(e){var n=e.geometry;return null===n.boundingSphere&&n.computeBoundingSphere(),t.copy(n.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSprite:function(){var t=new S;return function(e){return t.center.set(0,0,0),t.radius=.7071067811865476,t.applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSphere:function(t){for(var e=this.planes,n=t.center,i=-t.radius,r=0;r<6;r++){var a=e[r].distanceToPoint(n);if(a0?n.min.x:n.max.x,e.x=a.normal.x>0?n.max.x:n.min.x,t.y=a.normal.y>0?n.min.y:n.max.y,e.y=a.normal.y>0?n.max.y:n.min.y,t.z=a.normal.z>0?n.min.z:n.max.z,e.z=a.normal.z>0?n.max.z:n.min.z;var o=a.distanceToPoint(t),s=a.distanceToPoint(e);if(o<0&&s<0)return!1}return!0}}(),containsPoint:function(t){for(var e=this.planes,n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}},t.WebGLShader=function(){function t(t){for(var e=t.split("\n"),n=0;n");return l(i)}var i=/#include +<([\w\d.]+)>/g;return e.replace(i,n)}function u(t){function e(t,e,n,i){for(var r="",a=parseInt(e);a0?e.gammaFactor:1,L=a(v,m,e.extensions),R=o(y),C=g.createProgram();f&&f.isRawShaderMaterial?(S=[R].filter(h).join("\n"),T=[R].filter(h).join("\n")):(S=["precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+A,"#define MAX_BONES "+m.maxBones,m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+M:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.displacementMap&&m.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.skinning?"#define USE_SKINNING":"",m.useVertexTexture?"#define BONE_TEXTURE":"",m.morphTargets?"#define USE_MORPHTARGETS":"",m.morphNormals&&m.flatShading===!1?"#define USE_MORPHNORMALS":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+_:"",m.sizeAttenuation?"#define USE_SIZEATTENUATION":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(h).join("\n"),T=[L,"precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.alphaTest?"#define ALPHATEST "+m.alphaTest:"","#define GAMMA_FACTOR "+A,m.useFog&&m.fog?"#define USE_FOG":"",m.useFog&&m.fogExp?"#define FOG_EXP2":"",m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+w:"",m.envMap?"#define "+M:"",m.envMap?"#define "+E:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+_:"",m.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",m.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",m.envMap&&e.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",m.toneMapping!==rr?"#define TONE_MAPPING":"",m.toneMapping!==rr?t.ShaderChunk.tonemapping_pars_fragment:"",m.toneMapping!==rr?r("toneMapping",m.toneMapping):"",m.outputEncoding||m.mapEncoding||m.envMapEncoding||m.emissiveMapEncoding?t.ShaderChunk.encodings_pars_fragment:"",m.mapEncoding?n("mapTexelToLinear",m.mapEncoding):"",m.envMapEncoding?n("envMapTexelToLinear",m.envMapEncoding):"",m.emissiveMapEncoding?n("emissiveMapTexelToLinear",m.emissiveMapEncoding):"",m.outputEncoding?i("linearToOutputTexel",m.outputEncoding):"",m.depthPacking?"#define DEPTH_PACKING "+f.depthPacking:"","\n"].filter(h).join("\n")),x=l(x,m),x=c(x,m),b=l(b,m),b=c(b,m),(f&&f.isShaderMaterial)===!1&&(x=u(x),b=u(b));var P=S+x,U=T+b,I=t.WebGLShader(g,g.VERTEX_SHADER,P),D=t.WebGLShader(g,g.FRAGMENT_SHADER,U);g.attachShader(C,I),g.attachShader(C,D),void 0!==f.index0AttributeName?g.bindAttribLocation(C,0,f.index0AttributeName):m.morphTargets===!0&&g.bindAttribLocation(C,0,"position"),g.linkProgram(C);var N=g.getProgramInfoLog(C),O=g.getShaderInfoLog(I),F=g.getShaderInfoLog(D),B=!0,z=!0;g.getProgramParameter(C,g.LINK_STATUS)===!1?(B=!1,console.error("THREE.WebGLProgram: shader error: ",g.getError(),"gl.VALIDATE_STATUS",g.getProgramParameter(C,g.VALIDATE_STATUS),"gl.getProgramInfoLog",N,O,F)):""!==N?console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",N):""!==O&&""!==F||(z=!1),z&&(this.diagnostics={runnable:B,material:f,programLog:N,vertexShader:{log:O,prefix:S},fragmentShader:{log:F,prefix:T}}),g.deleteShader(I),g.deleteShader(D);var G;this.getUniforms=function(){return void 0===G&&(G=new t.WebGLUniforms(g,C,e)),G};var k;return this.getAttributes=function(){return void 0===k&&(k=s(g,C)),k},this.destroy=function(){g.deleteProgram(C),this.program=void 0},Object.defineProperties(this,{uniforms:{get:function(){return console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms()."),this.getUniforms()}},attributes:{get:function(){return console.warn("THREE.WebGLProgram: .attributes is now .getAttributes()."),this.getAttributes()}}}),this.id=d++,this.code=p,this.usedTimes=1,this.program=C,this.vertexShader=I,this.fragmentShader=D,this}}(),U.prototype={constructor:U,get count(){return this.array.length/this.itemSize},set needsUpdate(t){t===!0&&this.version++},setDynamic:function(t){return this.dynamic=t,this},copy:function(t){return this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.dynamic=t.dynamic,this},copyAt:function(t,e,n){t*=this.itemSize,n*=e.itemSize;for(var i=0,r=this.itemSize;i1){for(var e=0;e1)for(var e=0;e0){r.children=[];for(var a=0;a0&&(i.geometries=o),s.length>0&&(i.materials=s),h.length>0&&(i.textures=h),c.length>0&&(i.images=c)}return i.object=r,i},clone:function(t){return(new this.constructor).copy(this,t)},copy:function(t,e){if(void 0===e&&(e=!0),this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(var n=0;n0)for(var m=0;m0&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var t,e,n,i,r;for(n=0,i=this.faces.length;n0&&(t+=e[n].distanceTo(e[n-1])),this.lineDistances[n]=t},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E),this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new S),this.boundingSphere.setFromPoints(this.vertices)},merge:function(t,e,n){if((t&&t.isGeometry)===!1)return void console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",t);var i,r=this.vertices.length,a=this.vertices,o=t.vertices,s=this.faces,h=t.faces,c=this.faceVertexUvs[0],l=t.faceVertexUvs[0];void 0===n&&(n=0),void 0!==e&&(i=(new T).getNormalMatrix(e));for(var u=0,d=o.length;u=0;n--){var g=p[n];for(this.faces.splice(g,1),o=0,s=this.faceVertexUvs.length;o0,w=v.vertexNormals.length>0,M=1!==v.color.r||1!==v.color.g||1!==v.color.b,E=v.vertexColors.length>0,S=0;if(S=t(S,0,0),S=t(S,1,y),S=t(S,2,x),S=t(S,3,b),S=t(S,4,_),S=t(S,5,w),S=t(S,6,M),S=t(S,7,E),l.push(S),l.push(v.a,v.b,v.c),l.push(v.materialIndex),b){var T=this.faceVertexUvs[0][h];l.push(i(T[0]),i(T[1]),i(T[2]))}if(_&&l.push(e(v.normal)),w){var A=v.vertexNormals;l.push(e(A[0]),e(A[1]),e(A[2]))}if(M&&l.push(n(v.color)),E){var L=v.vertexColors;l.push(n(L[0]),n(L[1]),n(L[2]))}}return r.data={},r.data.vertices=s,r.data.normals=u,p.length>0&&(r.data.colors=p),m.length>0&&(r.data.uvs=[m]),r.data.faces=l,r},clone:function(){return(new q).copy(this)},copy:function(t){this.vertices=[],this.faces=[],this.faceVertexUvs=[[]];for(var e=t.vertices,n=0,i=e.length;n0,s=a[1]&&a[1].length>0,h=t.morphTargets,c=h.length;if(c>0){e=[];for(var l=0;l0){u=[];for(var l=0;l0){var n=new Float32Array(3*t.normals.length);this.addAttribute("normal",new U(n,3).copyVector3sArray(t.normals))}if(t.colors.length>0){var i=new Float32Array(3*t.colors.length);this.addAttribute("color",new U(i,3).copyColorsArray(t.colors))}if(t.uvs.length>0){var r=new Float32Array(2*t.uvs.length);this.addAttribute("uv",new U(r,2).copyVector2sArray(t.uvs))}if(t.uvs2.length>0){var a=new Float32Array(2*t.uvs2.length);this.addAttribute("uv2",new U(a,2).copyVector2sArray(t.uvs2))}if(t.indices.length>0){var o=t.vertices.length>65535?Uint32Array:Uint16Array,s=new o(3*t.indices.length);this.setIndex(new U(s,1).copyIndicesArray(t.indices))}this.groups=t.groups;for(var h in t.morphTargets){for(var c=[],l=t.morphTargets[h],u=0,d=l.length;u0){var m=new G(4*t.skinIndices.length,4);this.addAttribute("skinIndex",m.copyVector4sArray(t.skinIndices))}if(t.skinWeights.length>0){var g=new G(4*t.skinWeights.length,4);this.addAttribute("skinWeight",g.copyVector4sArray(t.skinWeights))}return null!==t.boundingSphere&&(this.boundingSphere=t.boundingSphere.clone()),null!==t.boundingBox&&(this.boundingBox=t.boundingBox.clone()),this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E);var t=this.attributes.position.array;void 0!==t?this.boundingBox.setFromArray(t):this.boundingBox.makeEmpty(),(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var t=new E,e=new s;return function(){null===this.boundingSphere&&(this.boundingSphere=new S);var n=this.attributes.position;if(n){var i=n.array,r=this.boundingSphere.center;t.setFromArray(i),t.center(r);for(var a=0,o=0,s=i.length;o0&&(t.data.groups=JSON.parse(JSON.stringify(s)));var h=this.boundingSphere;return null!==h&&(t.data.boundingSphere={center:h.center.toArray(),radius:h.radius}),t},clone:function(){return(new Q).copy(this)},copy:function(t){var e=t.index;null!==e&&this.setIndex(e.clone());var n=t.attributes;for(var i in n){var r=n[i];this.addAttribute(i,r.clone())}for(var a=t.groups,o=0,s=a.length;o0)if(s=d*f-p,h=d*p-f,l=u*g,s>=0)if(h>=-l)if(h<=l){var v=1/g;s*=v,h*=v,c=s*(s+d*h+2*p)+h*(d*s+h+2*f)+m}else h=u,s=Math.max(0,-(d*h+p)),c=-s*s+h*(h+2*f)+m;else h=-u,s=Math.max(0,-(d*h+p)),c=-s*s+h*(h+2*f)+m;else h<=-l?(s=Math.max(0,-(-d*u+p)),h=s>0?-u:Math.min(Math.max(-u,-f),u),c=-s*s+h*(h+2*f)+m):h<=l?(s=0,h=Math.min(Math.max(-u,-f),u),c=h*(h+2*f)+m):(s=Math.max(0,-(d*u+p)),h=s>0?u:Math.min(Math.max(-u,-f),u),c=-s*s+h*(h+2*f)+m);else h=d>0?-u:u,s=Math.max(0,-(d*h+p)),c=-s*s+h*(h+2*f)+m;return a&&a.copy(this.direction).multiplyScalar(s).add(this.origin),o&&o.copy(e).multiplyScalar(h).add(t),c}}(),intersectSphere:function(){var t=new s;return function(e,n){t.subVectors(e.center,this.origin);var i=t.dot(this.direction),r=t.dot(t)-i*i,a=e.radius*e.radius;if(r>a)return null;var o=Math.sqrt(a-r),s=i-o,h=i+o;return s<0&&h<0?null:s<0?this.at(h,n):this.at(s,n)}}(),intersectsSphere:function(t){return this.distanceToPoint(t.center)<=t.radius},distanceToPlane:function(t){var e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;var n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null},intersectPlane:function(t,e){var n=this.distanceToPlane(t);return null===n?null:this.at(n,e)},intersectsPlane:function(t){var e=t.distanceToPoint(this.origin);if(0===e)return!0;var n=t.normal.dot(this.direction);return n*e<0},intersectBox:function(t,e){var n,i,r,a,o,s,h=1/this.direction.x,c=1/this.direction.y,l=1/this.direction.z,u=this.origin;return h>=0?(n=(t.min.x-u.x)*h,i=(t.max.x-u.x)*h):(n=(t.max.x-u.x)*h,i=(t.min.x-u.x)*h),c>=0?(r=(t.min.y-u.y)*c,a=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,a=(t.min.y-u.y)*c),n>a||r>i?null:((r>n||n!==n)&&(n=r),(a=0?(o=(t.min.z-u.z)*l,s=(t.max.z-u.z)*l):(o=(t.max.z-u.z)*l,s=(t.min.z-u.z)*l),n>s||o>i?null:((o>n||n!==n)&&(n=o),(s=0?n:i,e)))},intersectsBox:function(){var t=new s;return function(e){return null!==this.intersectBox(e,t)}}(),intersectTriangle:function(){var t=new s,e=new s,n=new s,i=new s;return function(r,a,o,s,h){e.subVectors(a,r),n.subVectors(o,r),i.crossVectors(e,n);var c,l=this.direction.dot(i);if(l>0){if(s)return null;c=1}else{if(!(l<0))return null;c=-1,l=-l}t.subVectors(this.origin,r);var u=c*this.direction.dot(n.crossVectors(t,n));if(u<0)return null;var d=c*this.direction.dot(e.cross(t));if(d<0)return null;if(u+d>l)return null;var p=-c*t.dot(i);return p<0?null:this.at(p/l,h)}}(),applyMatrix4:function(t){return this.direction.add(this.origin).applyMatrix4(t),this.origin.applyMatrix4(t),this.direction.sub(this.origin),this.direction.normalize(),this},equals:function(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}},ct.prototype={constructor:ct,set:function(t,e){return this.start.copy(t),this.end.copy(e),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.start.copy(t.start),this.end.copy(t.end),this},center:function(t){var e=t||new s;return e.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(t){var e=t||new s;return e.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(t,e){var n=e||new s;return this.delta(n).multiplyScalar(t).add(this.start)},closestPointToPointParameter:function(){var e=new s,n=new s;return function(i,r){e.subVectors(i,this.start),n.subVectors(this.end,this.start);var a=n.dot(n),o=n.dot(e),s=o/a;return r&&(s=t.Math.clamp(s,0,1)),s}}(),closestPointToPoint:function(t,e,n){var i=this.closestPointToPointParameter(t,e),r=n||new s;return this.delta(r).multiplyScalar(i).add(this.start)},applyMatrix4:function(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this},equals:function(t){return t.start.equals(this.start)&&t.end.equals(this.end)}},lt.normal=function(){var t=new s;return function(e,n,i,r){var a=r||new s;a.subVectors(i,n),t.subVectors(e,n),a.cross(t);var o=a.lengthSq();return o>0?a.multiplyScalar(1/Math.sqrt(o)):a.set(0,0,0)}}(),lt.barycoordFromPoint=function(){var t=new s,e=new s,n=new s;return function(i,r,a,o,h){t.subVectors(o,r),e.subVectors(a,r),n.subVectors(i,r);var c=t.dot(t),l=t.dot(e),u=t.dot(n),d=e.dot(e),p=e.dot(n),f=c*d-l*l,m=h||new s;if(0===f)return m.set(-2,-1,-1);var g=1/f,v=(d*u-l*p)*g,y=(c*p-l*u)*g;return m.set(1-v-y,y,v)}}(),lt.containsPoint=function(){var t=new s;return function(e,n,i,r){var a=lt.barycoordFromPoint(e,n,i,r,t);return a.x>=0&&a.y>=0&&a.x+a.y<=1}}(),lt.prototype={constructor:lt,set:function(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this},setFromPointsAndIndices:function(t,e,n,i){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[i]),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this},area:function(){var t=new s,e=new s;return function(){return t.subVectors(this.c,this.b),e.subVectors(this.a,this.b),.5*t.cross(e).length()}}(),midpoint:function(t){var e=t||new s;return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(t){return lt.normal(this.a,this.b,this.c,t)},plane:function(t){var e=t||new A;return e.setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(t,e){return lt.barycoordFromPoint(t,this.a,this.b,this.c,e)},containsPoint:function(t){return lt.containsPoint(t,this.a,this.b,this.c)},closestPointToPoint:function(){var t,e,n,i;return function(r,a){void 0===t&&(t=new A,e=[new ct,new ct,new ct],n=new s,i=new s);var o=a||new s,h=1/0;if(t.setFromCoplanarPoints(this.a,this.b,this.c),t.projectPoint(r,n),this.containsPoint(n)===!0)o.copy(n);else{e[0].set(this.a,this.b),e[1].set(this.b,this.c),e[2].set(this.c,this.a);for(var c=0;c0){this.morphTargetBase=-1,this.morphTargetInfluences=[],this.morphTargetDictionary={};for(var t=0,e=this.geometry.morphTargets.length;te.far?null:{distance:c,point:b.clone(),object:t}}function i(n,i,r,a,o,s,h,d){c.fromArray(a,3*s),l.fromArray(a,3*h),u.fromArray(a,3*d);var p=e(n,i,r,c,l,u,x);return p&&(o&&(m.fromArray(o,2*s),g.fromArray(o,2*h),v.fromArray(o,2*d),p.uv=t(x,c,l,u,m,g,v)),p.face=new V(s,h,d,lt.normal(c,l,u)),p.faceIndex=s),p}var r=new a,o=new ht,h=new S,c=new s,l=new s,u=new s,d=new s,p=new s,f=new s,m=new n,g=new n,v=new n,y=new s,x=new s,b=new s;return function(n,a){var s=this.geometry,y=this.material,b=this.matrixWorld;if(void 0!==y&&(null===s.boundingSphere&&s.computeBoundingSphere(),h.copy(s.boundingSphere),h.applyMatrix4(b),n.ray.intersectsSphere(h)!==!1&&(r.getInverse(b),o.copy(n.ray).applyMatrix4(r),null===s.boundingBox||o.intersectsBox(s.boundingBox)!==!1))){var _,w;if(s&&s.isBufferGeometry){var M,E,S,T=s.index,A=s.attributes,L=A.position.array;if(void 0!==A.uv&&(_=A.uv.array),null!==T)for(var R=T.array,C=0,P=R.length;C0&&(_=z);for(var G=0,k=B.length;Gr||n.push({distance:Math.sqrt(i),point:this.position,face:null,object:this})}}(),clone:function(){return new this.constructor(this.material).copy(this)}}),Et.prototype=Object.assign(Object.create(X.prototype),{constructor:Et,copy:function(t){X.prototype.copy.call(this,t,!1);for(var e=t.levels,n=0,i=e.length;n1){t.setFromMatrixPosition(n.matrixWorld),e.setFromMatrixPosition(this.matrixWorld);var r=t.distanceTo(e);i[0].object.visible=!0;for(var a=1,o=i.length;a=i[a].distance;a++)i[a-1].object.visible=!1,i[a].object.visible=!0;for(;ao)){p.applyMatrix4(this.matrixWorld);var E=i.ray.origin.distanceTo(p);Ei.far||r.push({distance:E,point:d.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}else for(var x=0,b=v.length/3-1;xo)){p.applyMatrix4(this.matrixWorld);var E=i.ray.origin.distanceTo(p);Ei.far||r.push({distance:E,point:d.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}else if(h&&h.isGeometry)for(var S=h.vertices,T=S.length,x=0;xo)){p.applyMatrix4(this.matrixWorld);var E=i.ray.origin.distanceTo(p);Ei.far||r.push({distance:E,point:d.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}}),Pt.prototype=Object.assign(Object.create(Ct.prototype),{constructor:Pt}),Ut.prototype=Object.create(x.prototype),Ut.prototype.constructor=Ut,Ut.prototype.copy=function(t){return x.prototype.copy.call(this,t),this.color.copy(t.color),this.map=t.map,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this},It.prototype=Object.assign(Object.create(X.prototype),{constructor:It,raycast:function(){var t=new a,e=new ht,n=new S;return function(i,r){function a(t,n){var a=e.distanceSqToPoint(t);if(ai.far)return;r.push({distance:h,distanceToRay:Math.sqrt(a),point:s.clone(),index:n,face:null,object:o})}}var o=this,h=this.geometry,c=this.matrixWorld,l=i.params.Points.threshold;if(null===h.boundingSphere&&h.computeBoundingSphere(),n.copy(h.boundingSphere),n.applyMatrix4(c),i.ray.intersectsSphere(n)!==!1){t.getInverse(c),e.copy(i.ray).applyMatrix4(t);var u=l/((this.scale.x+this.scale.y+this.scale.z)/3),d=u*u,p=new s;if(h&&h.isBufferGeometry){var f=h.index,m=h.attributes,g=m.position.array;if(null!==f)for(var v=f.array,y=0,x=v.length;y0||0===t.search(/^data\:image\/jpeg/);a.format=i?Br:zr,a.image=n,a.needsUpdate=!0,void 0!==e&&e(a)},n,r),a},setCrossOrigin:function(t){return this.crossOrigin=t,this},setPath:function(t){return this.path=t,this}}),ee.prototype=Object.assign(Object.create(X.prototype),{constructor:ee,copy:function(t){return X.prototype.copy.call(this,t),this.color.copy(t.color),this.intensity=t.intensity,this},toJSON:function(t){var e=X.prototype.toJSON.call(this,t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),e}}),ne.prototype=Object.assign(Object.create(ee.prototype),{constructor:ne,copy:function(t){return ee.prototype.copy.call(this,t),this.groundColor.copy(t.groundColor),this}}),Object.assign(ie.prototype,{copy:function(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this},clone:function(){return(new this.constructor).copy(this)}}),re.prototype=Object.assign(Object.create(ie.prototype),{constructor:re,update:function(e){var n=2*t.Math.RAD2DEG*e.angle,i=this.mapSize.width/this.mapSize.height,r=e.distance||500,a=this.camera;n===a.fov&&i===a.aspect&&r===a.far||(a.fov=n,a.aspect=i,a.far=r,a.updateProjectionMatrix())}}),ae.prototype=Object.assign(Object.create(ee.prototype),{constructor:ae,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),oe.prototype=Object.assign(Object.create(ee.prototype),{constructor:oe,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}),se.prototype=Object.assign(Object.create(ie.prototype),{constructor:se}),he.prototype=Object.assign(Object.create(ee.prototype),{constructor:he,copy:function(t){return ee.prototype.copy.call(this,t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),ce.prototype=Object.assign(Object.create(ee.prototype),{constructor:ce}),t.AnimationUtils={arraySlice:function(e,n,i){return t.AnimationUtils.isTypedArray(e)?new e.constructor(e.subarray(n,i)):e.slice(n,i)},convertArray:function(t,e,n){return!t||!n&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)},isTypedArray:function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},getKeyframeOrder:function(t){function e(e,n){return t[e]-t[n]}for(var n=t.length,i=new Array(n),r=0;r!==n;++r)i[r]=r;return i.sort(e),i},sortedArray:function(t,e,n){for(var i=t.length,r=new t.constructor(i),a=0,o=0;o!==i;++a)for(var s=n[a]*e,h=0;h!==e;++h)r[o++]=t[s+h];return r},flattenJSON:function(t,e,n,i){for(var r=1,a=t[0];void 0!==a&&void 0===a[i];)a=t[r++];if(void 0!==a){var o=a[i];if(void 0!==o)if(Array.isArray(o)){do o=a[i],void 0!==o&&(e.push(a.time),n.push.apply(n,o)),a=t[r++];while(void 0!==a)}else if(void 0!==o.toArray){do o=a[i],void 0!==o&&(e.push(a.time),o.toArray(n,n.length)),a=t[r++];while(void 0!==a)}else do o=a[i],void 0!==o&&(e.push(a.time),n.push(o)),a=t[r++];while(void 0!==a)}}},le.prototype={constructor:le,evaluate:function(t){var e=this.parameterPositions,n=this._cachedIndex,i=e[n],r=e[n-1];t:{e:{var a;n:{i:if(!(t=r)break t;var s=e[1];t=r)break e}a=n,n=0}}for(;n>>1;tn;)--o;if(++o,0!==a||o!==r){a>=o&&(o=Math.max(o,1),a=o-1);var s=this.getValueSize();this.times=t.AnimationUtils.arraySlice(i,a,o),this.values=t.AnimationUtils.arraySlice(this.values,a*s,o*s)}return this},validate:function(){var e=!0,n=this.getValueSize();n-Math.floor(n)!==0&&(console.error("invalid value size in track",this),e=!1);var i=this.times,r=this.values,a=i.length;0===a&&(console.error("track is empty",this),e=!1);for(var o=null,s=0;s!==a;s++){var h=i[s];if("number"==typeof h&&isNaN(h)){console.error("time is not a valid number",this,s,h),e=!1;break}if(null!==o&&o>h){console.error("out of order keys",this,s,h,o),e=!1;break}o=h}if(void 0!==r&&t.AnimationUtils.isTypedArray(r))for(var s=0,c=r.length;s!==c;++s){var l=r[s];if(isNaN(l)){console.error("value is not a valid number",this,s,l),e=!1;break}}return e},optimize:function(){for(var e=this.times,n=this.values,i=this.getValueSize(),r=1,a=1,o=e.length-1;a<=o;++a){var s=!1,h=e[a],c=e[a+1];if(h!==c&&(1!==a||h!==h[0]))for(var l=a*i,u=l-i,d=l+i,p=0;p!==i;++p){var f=n[l+p];if(f!==n[u+p]||f!==n[d+p]){s=!0;break}}if(s){if(a!==r){e[r]=e[a];for(var m=a*i,g=r*i,p=0;p!==i;++p)n[g+p]=n[m+p]}++r}}return r!==e.length&&(this.times=t.AnimationUtils.arraySlice(e,0,r),this.values=t.AnimationUtils.arraySlice(n,0,r*i)),this}},me.prototype=Object.assign(Object.create(Ta),{constructor:me,ValueTypeName:"vector"}),ge.prototype=Object.assign(Object.create(le.prototype),{constructor:ge,interpolate_:function(t,e,n,i){for(var r=this.resultBuffer,a=this.sampleValues,s=this.valueSize,h=t*s,c=(n-e)/(i-e),l=h+s;h!==l;h+=4)o.slerpFlat(r,0,a,h-s,a,h,c);return r}}),ve.prototype=Object.assign(Object.create(Ta),{constructor:ve,ValueTypeName:"quaternion",DefaultInterpolation:ia,InterpolantFactoryMethodLinear:function(t){return new ge(this.times,this.values,this.getValueSize(),t)},InterpolantFactoryMethodSmooth:void 0}),ye.prototype=Object.assign(Object.create(Ta),{constructor:ye,ValueTypeName:"number"}),xe.prototype=Object.assign(Object.create(Ta),{constructor:xe,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:na,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),be.prototype=Object.assign(Object.create(Ta),{constructor:be,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:na,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),_e.prototype=Object.assign(Object.create(Ta),{constructor:_e,ValueTypeName:"color"}),we.prototype=Ta,Ta.constructor=we,Object.assign(we,{parse:function(e){if(void 0===e.type)throw new Error("track type undefined, can not parse");var n=we._getTrackTypeForValueTypeName(e.type);if(void 0===e.times){var i=[],r=[];t.AnimationUtils.flattenJSON(e.keys,i,r,"value"),e.times=i,e.values=r}return void 0!==n.parse?n.parse(e):new n(e.name,e.times,e.values,e.interpolation)},toJSON:function(e){var n,i=e.constructor;if(void 0!==i.toJSON)n=i.toJSON(e);else{n={name:e.name,times:t.AnimationUtils.convertArray(e.times,Array),values:t.AnimationUtils.convertArray(e.values,Array)};var r=e.getInterpolation();r!==e.DefaultInterpolation&&(n.interpolation=r)}return n.type=e.ValueTypeName,n},_getTrackTypeForValueTypeName:function(t){switch(t.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return ye;case"vector":case"vector2":case"vector3":case"vector4":return me;case"color":return _e;case"quaternion":return ve;case"bool":case"boolean":return be;case"string":return xe}throw new Error("Unsupported typeName: "+t)}}),Me.prototype={constructor:Me,resetDuration:function(){for(var t=this.tracks,e=0,n=0,i=t.length;n!==i;++n){var r=this.tracks[n];e=Math.max(e,r.times[r.times.length-1])}this.duration=e},trim:function(){for(var t=0;t1){var c=h[1],l=i[c];l||(i[c]=l=[]),l.push(s)}}var u=[];for(var c in i)u.push(Me.CreateFromMorphTargetSequence(c,i[c],e,n));return u},parseAnimation:function(e,n,i){if(!e)return console.error(" no animation in JSONLoader data"),null;for(var r=function(e,n,i,r,a){if(0!==i.length){var o=[],s=[];t.AnimationUtils.flattenJSON(i,o,s,r),0!==o.length&&a.push(new e(n,o,s))}},a=[],o=e.name||"default",s=e.length||-1,h=e.fps||30,c=e.hierarchy||[],l=0;l1?t.skinWeights[n+1]:0,o=e>2?t.skinWeights[n+2]:0,s=e>3?t.skinWeights[n+3]:0;h.skinWeights.push(new p(r,a,o,s))}if(t.skinIndices)for(var n=0,i=t.skinIndices.length;n1?t.skinIndices[n+1]:0,u=e>2?t.skinIndices[n+2]:0,d=e>3?t.skinIndices[n+3]:0;h.skinIndices.push(new p(c,l,u,d))}h.bones=t.bones,h.bones&&h.bones.length>0&&(h.skinWeights.length!==h.skinIndices.length||h.skinIndices.length!==h.vertices.length)&&console.warn("When skinning, number of vertices ("+h.vertices.length+"), skinIndices ("+h.skinIndices.length+"), and skinWeights ("+h.skinWeights.length+") should match.")}function a(e){if(void 0!==t.morphTargets)for(var n=0,i=t.morphTargets.length;n0){console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.');for(var u=h.faces,d=t.morphColors[0].colors,n=0,i=u.length;n0&&(h.animations=e)}var h=new q,c=void 0!==t.scale?1/t.scale:1;if(i(c),r(),a(c),o(),h.computeFaceNormals(),h.computeBoundingSphere(),void 0===t.materials||0===t.materials.length)return{geometry:h};var l=Te.prototype.initMaterials(t.materials,e,this.crossOrigin);return{geometry:h,materials:l}}}),Object.assign(Le.prototype,{load:function(t,e,n,i){""===this.texturePath&&(this.texturePath=t.substring(0,t.lastIndexOf("/")+1));var r=this,a=new Zt(r.manager);a.load(t,function(t){r.parse(JSON.parse(t),e)},n,i)},setTexturePath:function(t){this.texturePath=t},setCrossOrigin:function(t){this.crossOrigin=t},parse:function(t,e){var n=this.parseGeometries(t.geometries),i=this.parseImages(t.images,function(){void 0!==e&&e(o)}),r=this.parseTextures(t.textures,i),a=this.parseMaterials(t.materials,r),o=this.parseObject(t.object,n,a);return t.animations&&(o.animations=this.parseAnimations(t.animations)),void 0!==t.images&&0!==t.images.length||void 0!==e&&e(o),o},parseGeometries:function(t){var e={};if(void 0!==t)for(var n=new Ae,i=new Se,r=0,a=t.length;r0){var a=new qt(e),o=new Kt(a);o.setCrossOrigin(this.crossOrigin);for(var s=0,h=t.length;s0?new Lt(s,h):new dt(s,h);break;case"LOD":o=new Et;break;case"Line":o=new Ct(r(e.geometry),a(e.material),e.mode);break;case"PointCloud":case"Points":o=new It(r(e.geometry),a(e.material));break;case"Sprite":o=new Mt(a(e.material));break;case"Group":o=new Dt;break;default:o=new X}if(o.uuid=e.uuid,void 0!==e.name&&(o.name=e.name),void 0!==e.matrix?(t.fromArray(e.matrix),t.decompose(o.position,o.quaternion,o.scale)):(void 0!==e.position&&o.position.fromArray(e.position),void 0!==e.rotation&&o.rotation.fromArray(e.rotation),void 0!==e.scale&&o.scale.fromArray(e.scale)),void 0!==e.castShadow&&(o.castShadow=e.castShadow),void 0!==e.receiveShadow&&(o.receiveShadow=e.receiveShadow),void 0!==e.visible&&(o.visible=e.visible),void 0!==e.userData&&(o.userData=e.userData),void 0!==e.children)for(var c in e.children)o.add(this.parseObject(e.children[c],n,i));if("LOD"===e.type)for(var l=e.levels,u=0;u(c-s)*(d-h)-(l-h)*(u-s))return!1;var m,g,v,y,x,b,_,w,M,E,S,T,A,L,R;for(m=u-c,g=d-l,v=s-u,y=h-d,x=c-s,b=l-h,o=0;o=-Number.EPSILON&&L>=-Number.EPSILON&&A>=-Number.EPSILON))return!1;return!0}return function(n,i){var r=n.length;if(r<3)return null;var a,o,s,h=[],c=[],l=[];if(t.ShapeUtils.area(n)>0)for(o=0;o2;){if(d--<=0)return console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()"),i?l:h;if(a=o,u<=a&&(a=0),o=a+1,u<=o&&(o=0),s=o+1,u<=s&&(s=0),e(n,a,o,s,u,c)){var p,f,m,g,v;for(p=c[a],f=c[o],m=c[s],h.push([n[p],n[f],n[m]]),l.push([c[a],c[o],c[s]]),g=o,v=o+1;v2&&t[e-1].equals(t[0])&&t.pop()}function r(t,e,n){return t.x!==e.x?t.xNumber.EPSILON){var f;if(d>0){if(p<0||p>d)return[];if(f=c*l-h*u,f<0||f>d)return[]}else{if(p>0||p0||fS?[]:b===S?a?[]:[y]:_<=S?[y,x]:[y,M]}function o(t,e,n,i){var r=e.x-t.x,a=e.y-t.y,o=n.x-t.x,s=n.y-t.y,h=i.x-t.x,c=i.y-t.y,l=r*s-a*o,u=r*c-a*h;if(Math.abs(l)>Number.EPSILON){var d=h*s-c*o;return l>0?u>=0&&d>=0:u>=0||d>=0}return u>0}function s(t,e){function n(t,e){var n=y.length-1,i=t-1;i<0&&(i=n);var r=t+1;r>n&&(r=0);var a=o(y[t],y[i],y[r],s[e]);if(!a)return!1;var h=s.length-1,c=e-1;c<0&&(c=h);var l=e+1;return l>h&&(l=0),a=o(s[e],s[c],s[l],y[t]),!!a}function i(t,e){var n,i,r;for(n=0;n0)return!0;return!1}function r(t,n){var i,r,o,s,h;for(i=0;i0)return!0;return!1}for(var s,h,c,l,u,d,p,f,m,g,v,y=t.concat(),x=[],b=[],_=0,w=e.length;_0;){if(E--,E<0){console.log("Infinite Loop! Holes left:"+x.length+", Probably Hole outside Shape!");break}for(c=M;c=0)break;b[p]=!0}if(h>=0)break}}return y}i(e),n.forEach(i);for(var h,c,l,u,d,p,f={},m=e.concat(),g=0,v=n.length;g0)){h=r;break}h=r-1}if(r=h,i[r]===n){var c=r/(a-1);return c}var l=i[r],u=i[r+1],d=u-l,p=(n-l)/d,c=(r+p)/(a-1);return c},getTangent:function(t){var e=1e-4,n=t-e,i=t+e;n<0&&(n=0),i>1&&(i=1);var r=this.getPoint(n),a=this.getPoint(i),o=a.clone().sub(r);return o.normalize()},getTangentAt:function(t){var e=this.getUtoTmapping(t);return this.getTangent(e)}},Re.create=function(t,e){return t.prototype=Object.create(Re.prototype),t.prototype.constructor=t,t.prototype.getPoint=e,t},Ce.prototype=Object.create(Re.prototype),Ce.prototype.constructor=Ce,Ce.prototype.getPoint=function(t){if(1===t)return this.v2.clone();var e=this.v2.clone().sub(this.v1);return e.multiplyScalar(t).add(this.v1),e},Ce.prototype.getPointAt=function(t){return this.getPoint(t)},Ce.prototype.getTangent=function(t){var e=this.v2.clone().sub(this.v1);return e.normalize()},Pe.prototype=Object.assign(Object.create(Re.prototype),{constructor:Pe,add:function(t){this.curves.push(t)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);t.equals(e)||this.curves.push(new Ce(e,t))},getPoint:function(t){for(var e=t*this.getLength(),n=this.getCurveLengths(),i=0;i=e){var r=n[i]-e,a=this.curves[i],o=a.getLength(),s=0===o?0:1-r/o;return a.getPointAt(s)}i++}return null},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},updateArcLengths:function(){this.needsUpdate=!0,this.cacheLengths=null,this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var t=[],e=0,n=0,i=this.curves.length;n1&&!n[n.length-1].equals(n[0])&&n.push(n[0]),n},createPointsGeometry:function(t){var e=this.getPoints(t);return this.createGeometry(e)},createSpacedPointsGeometry:function(t){var e=this.getSpacedPoints(t);return this.createGeometry(e)},createGeometry:function(t){for(var e=new q,n=0,i=t.length;ne;)i-=e;ii.length-2?i.length-1:a+1],l=i[a>i.length-3?i.length-1:a+2],u=t.CurveUtils.interpolate;return new n(u(s.x,h.x,c.x,l.x,o),u(s.y,h.y,c.y,l.y,o))},De.prototype=Object.create(Re.prototype),De.prototype.constructor=De,De.prototype.getPoint=function(e){var i=t.ShapeUtils.b3;return new n(i(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),i(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y))},De.prototype.getTangent=function(e){var i=t.CurveUtils.tangentCubicBezier;return new n(i(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),i(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y)).normalize()},Ne.prototype=Object.create(Re.prototype),Ne.prototype.constructor=Ne,Ne.prototype.getPoint=function(e){var i=t.ShapeUtils.b2;return new n(i(e,this.v0.x,this.v1.x,this.v2.x),i(e,this.v0.y,this.v1.y,this.v2.y))},Ne.prototype.getTangent=function(e){var i=t.CurveUtils.tangentQuadraticBezier;return new n(i(e,this.v0.x,this.v1.x,this.v2.x),i(e,this.v0.y,this.v1.y,this.v2.y)).normalize()};var Aa;Aa=Object.assign(Object.create(Pe.prototype),{fromPoints:function(t){this.moveTo(t[0].x,t[0].y);for(var e=1,n=t.length;e0){var c=h.getPoint(0);c.equals(this.currentPoint)||this.lineTo(c.x,c.y)}this.curves.push(h);var l=h.getPoint(1);this.currentPoint.copy(l)}}),Oe.prototype=Object.create(q.prototype),Oe.prototype.constructor=Oe,Oe.NoTaper=function(t){return 1},Oe.SinusoidalTaper=function(t){return Math.sin(Math.PI*t)},Oe.FrenetFrames=function(e,n,i){function r(){g[0]=new s,v[0]=new s,h=Number.MAX_VALUE,c=Math.abs(m[0].x),l=Math.abs(m[0].y),u=Math.abs(m[0].z),c<=h&&(h=c,f.set(1,0,0)),l<=h&&(h=l,f.set(0,1,0)),u<=h&&f.set(0,0,1),y.crossVectors(m[0],f).normalize(),g[0].crossVectors(m[0],y),v[0].crossVectors(m[0],g[0])}var o,h,c,l,u,d,p,f=new s,m=[],g=[],v=[],y=new s,x=new a,b=n+1;for(this.tangents=m,this.normals=g,this.binormals=v,d=0;dNumber.EPSILON&&(y.normalize(),o=Math.acos(t.Math.clamp(m[d-1].dot(m[d]),-1,1)),g[d].applyMatrix4(x.makeRotationAxis(y,o))),v[d].crossVectors(m[d],g[d]);if(i)for(o=Math.acos(t.Math.clamp(g[0].dot(g[b-1]),-1,1)),o/=b-1,m[0].dot(y.crossVectors(g[0],g[b-1]))>0&&(o=-o),d=1;dNumber.EPSILON){var p=Math.sqrt(u),f=Math.sqrt(c*c+l*l),m=e.x-h/p,g=e.y+s/p,v=i.x-l/f,y=i.y+c/f,x=((v-m)*l-(y-g)*c)/(s*l-h*c);r=m+s*x-t.x,a=g+h*x-t.y;var b=r*r+a*a;if(b<=2)return new n(r,a);o=Math.sqrt(b/2)}else{var _=!1;s>Number.EPSILON?c>Number.EPSILON&&(_=!0):s<-Number.EPSILON?c<-Number.EPSILON&&(_=!0):Math.sign(h)===Math.sign(l)&&(_=!0),_?(r=-h,a=s,o=Math.sqrt(u)):(r=s,a=h,o=Math.sqrt(u/2))}return new n(r/o,a/o)}function o(){if(w){var t=0,e=X*t;for(Z=0;Z=0;){n=Z,i=Z-1,i<0&&(i=t.length-1);var r=0,a=E+2*_;for(r=0;r=0;z--){for(k=z/_,H=x*(1-k),G=b*Math.sin(k*Math.PI/2),Z=0,J=B.length;ZNumber.EPSILON){if(c<0&&(o=e[a],h=-h,s=e[r],c=-c),t.ys.y)continue;if(t.y===o.y){if(t.x===o.x)return!0}else{var l=c*(t.x-o.x)-h*(t.y-o.y);if(0===l)return!0;if(l<0)continue;i=!i}}else{if(t.y!==o.y)continue;if(s.x<=t.x&&t.x<=o.x||o.x<=t.x&&t.x<=s.x)return!0}}return i}var a=t.ShapeUtils.isClockWise,o=this.subPaths;if(0===o.length)return[];if(n===!0)return i(o);var s,h,c,l=[];if(1===o.length)return h=o[0],c=new ze,c.curves=h.curves,l.push(c),l;var u=!a(o[0].getPoints());u=e?!u:u;var d,p=[],f=[],m=[],g=0;f[g]=void 0,m[g]=[];for(var v=0,y=o.length;v1){for(var x=!1,b=[],_=0,w=f.length;_0&&(x||(m=p))}for(var L,v=0,R=f.length;v0){this.source.connect(this.filters[0]);for(var t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(var t=1,e=this.filters.length;t=.5)for(var a=0;a!==r;++a)t[e+a]=t[n+a]},_slerp:function(t,e,n,i,r){o.slerpFlat(t,e,t,e,t,n,i)},_lerp:function(t,e,n,i,r){for(var a=1-i,o=0;o!==r;++o){var s=e+o;t[s]=t[s]*a+t[n+o]*i}}},$e.prototype={constructor:$e,getValue:function(t,e){this.bind(),this.getValue(t,e)},setValue:function(t,e){this.bind(),this.setValue(t,e)},bind:function(){var t=this.node,e=this.parsedPath,n=e.objectName,i=e.propertyName,r=e.propertyIndex;if(t||(t=$e.findNode(this.rootNode,e.nodeName)||this.rootNode,this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t)return void console.error(" trying to update node for track: "+this.path+" but it wasn't found.");if(n){var a=e.objectIndex;switch(n){case"materials":if(!t.material)return void console.error(" can not bind to material as node does not have a material",this);if(!t.material.materials)return void console.error(" can not bind to material.materials as node.material does not have a materials array",this);t=t.material.materials;break;case"bones":if(!t.skeleton)return void console.error(" can not bind to bones as node does not have a skeleton",this);t=t.skeleton.bones;for(var o=0;o=n){var u=n++,d=e[u];i[d.uuid]=l,e[l]=d,i[c]=u,e[u]=h;for(var p=0,f=a;p!==f;++p){var m=r[p],g=m[u],v=m[l];m[l]=g,m[u]=v}}}this.nCachedObjects_=n},uncache:function(t){for(var e=this._objects,n=e.length,i=this.nCachedObjects_,r=this._indicesByUUID,a=this._bindings,o=a.length,s=0,h=arguments.length;s!==h;++s){var c=arguments[s],l=c.uuid,u=r[l];if(void 0!==u)if(delete r[l],u0)for(var h=this._interpolants,c=this._propertyBindings,l=0,u=h.length;l!==u;++l)h[l].evaluate(o),c[l].accumulate(i,s)},_updateWeight:function(t){var e=0;if(this.enabled){e=this.weight;var n=this._weightInterpolant;if(null!==n){var i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=e,e},_updateTimeScale:function(t){var e=0;if(!this.paused){e=this.timeScale;var n=this._timeScaleInterpolant;if(null!==n){var i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e},_updateTime:function(t){var e=this.time+t;if(0===t)return e;var n=this._clip.duration,i=this.loop,r=this._loopCount;if(i===$r){r===-1&&(this.loopCount=0,this._setEndings(!0,!0,!1));t:{if(e>=n)e=n;else{if(!(e<0))break t;e=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{var a=i===ea;if(r===-1&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,a)):this._setEndings(0===this.repetitions,!0,a)),e>=n||e<0){var o=Math.floor(e/n);e-=n*o,r+=Math.abs(o);var s=this.repetitions-r;if(s<0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,e=t>0?n:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(0===s){var h=t<0;this._setEndings(h,!h,a)}else this._setEndings(!1,!1,a);this._loopCount=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}if(a&&1===(1&r))return this.time=e,n-e}return this.time=e,e},_setEndings:function(t,e,n){var i=this._interpolantSettings;n?(i.endingStart=oa,i.endingEnd=oa):(t?i.endingStart=this.zeroSlopeAtStart?oa:aa:i.endingStart=sa,e?i.endingEnd=this.zeroSlopeAtEnd?oa:aa:i.endingEnd=sa)},_scheduleFading:function(t,e,n){var i=this._mixer,r=i.time,a=this._weightInterpolant;null===a&&(a=i._lendControlInterpolant(),this._weightInterpolant=a);var o=a.parameterPositions,s=a.sampleValues;return o[0]=r,s[0]=e,o[1]=r+t,s[1]=n,this}},Object.assign(nn.prototype,e.prototype,{clipAction:function(t,e){var n=e||this._root,i=n.uuid,r="string"==typeof t?Me.findByName(n,t):t,a=null!==r?r.uuid:t,o=this._actionsByClip[a],s=null;if(void 0!==o){var h=o.actionByRoot[i];if(void 0!==h)return h;s=o.knownActions[0],null===r&&(r=s._clip)}if(null===r)return null;var c=new nn._Action(this,r,e);return this._bindAction(c,s),this._addInactiveAction(c,a,i),c},existingAction:function(t,e){var n=e||this._root,i=n.uuid,r="string"==typeof t?Me.findByName(n,t):t,a=r?r.uuid:t,o=this._actionsByClip[a];return void 0!==o?o.actionByRoot[i]||null:null},stopAllAction:function(){var t=this._actions,e=this._nActiveActions,n=this._bindings,i=this._nActiveBindings;this._nActiveActions=0,this._nActiveBindings=0;for(var r=0;r!==e;++r)t[r].reset();for(var r=0;r!==i;++r)n[r].useCount=0;return this},update:function(t){t*=this.timeScale;for(var e=this._actions,n=this._nActiveActions,i=this.time+=t,r=Math.sign(t),a=this._accuIndex^=1,o=0;o!==n;++o){var s=e[o];s.enabled&&s._update(i,t,r,a)}for(var h=this._bindings,c=this._nActiveBindings,o=0;o!==c;++o)h[o].apply(a);return this},getRoot:function(){return this._root},uncacheClip:function(t){var e=this._actions,n=t.uuid,i=this._actionsByClip,r=i[n];if(void 0!==r){for(var a=r.knownActions,o=0,s=a.length;o!==s;++o){var h=a[o];this._deactivateAction(h);var c=h._cacheIndex,l=e[e.length-1];h._cacheIndex=null,h._byClipCacheIndex=null,l._cacheIndex=c,e[c]=l,e.pop(),this._removeInactiveBindingsForAction(h)}delete i[n]}},uncacheRoot:function(t){var e=t.uuid,n=this._actionsByClip;for(var i in n){var r=n[i].actionByRoot,a=r[e];void 0!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}var o=this._bindingsByRootAndName,s=o[e];if(void 0!==s)for(var h in s){var c=s[h];c.restoreOriginalState(),this._removeInactiveBinding(c)}},uncacheAction:function(t,e){var n=this.existingAction(t,e);null!==n&&(this._deactivateAction(n), +this._removeInactiveAction(n))}}),nn._Action=en._new,Object.assign(nn.prototype,{_bindAction:function(t,e){var n=t._localRoot||this._root,i=t._clip.tracks,r=i.length,a=t._propertyBindings,o=t._interpolants,s=n.uuid,h=this._bindingsByRootAndName,c=h[s];void 0===c&&(c={},h[s]=c);for(var l=0;l!==r;++l){var u=i[l],d=u.name,p=c[d];if(void 0!==p)a[l]=p;else{if(p=a[l],void 0!==p){null===p._cacheIndex&&(++p.referenceCount,this._addInactiveBinding(p,s,d));continue}var f=e&&e._propertyBindings[l].binding.parsedPath;p=new Ke($e.create(n,d,f),u.ValueTypeName,u.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,s,d),a[l]=p}o[l].resultBuffer=p.buffer}},_activateAction:function(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){var e=(t._localRoot||this._root).uuid,n=t._clip.uuid,i=this._actionsByClip[n];this._bindAction(t,i&&i.knownActions[0]),this._addInactiveAction(t,n,e)}for(var r=t._propertyBindings,a=0,o=r.length;a!==o;++a){var s=r[a];0===s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(t)}},_deactivateAction:function(t){if(this._isActiveAction(t)){for(var e=t._propertyBindings,n=0,i=e.length;n!==i;++n){var r=e[n];0===--r.useCount&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(t)}},_initMemoryManager:function(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;var t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}},_isActiveAction:function(t){var e=t._cacheIndex;return null!==e&&e1){var c=h[1];i[c]||(i[c]={start:1/0,end:-(1/0)});var l=i[c];al.end&&(l.end=a),e||(e=c)}}for(var c in i){var l=i[c];this.createAnimation(c,l.start,l.end,t)}this.firstAnimation=e},gn.prototype.setAnimationDirectionForward=function(t){var e=this.animationsMap[t];e&&(e.direction=1,e.directionBackwards=!1)},gn.prototype.setAnimationDirectionBackward=function(t){var e=this.animationsMap[t];e&&(e.direction=-1,e.directionBackwards=!0)},gn.prototype.setAnimationFPS=function(t,e){var n=this.animationsMap[t];n&&(n.fps=e,n.duration=(n.end-n.start)/n.fps)},gn.prototype.setAnimationDuration=function(t,e){var n=this.animationsMap[t];n&&(n.duration=e,n.fps=(n.end-n.start)/n.duration)},gn.prototype.setAnimationWeight=function(t,e){var n=this.animationsMap[t];n&&(n.weight=e)},gn.prototype.setAnimationTime=function(t,e){var n=this.animationsMap[t];n&&(n.time=e)},gn.prototype.getAnimationTime=function(t){var e=0,n=this.animationsMap[t];return n&&(e=n.time),e},gn.prototype.getAnimationDuration=function(t){var e=-1,n=this.animationsMap[t];return n&&(e=n.duration),e},gn.prototype.playAnimation=function(t){var e=this.animationsMap[t];e?(e.time=0,e.active=!0):console.warn("THREE.MorphBlendMesh: animation["+t+"] undefined in .playAnimation()")},gn.prototype.stopAnimation=function(t){var e=this.animationsMap[t];e&&(e.active=!1)},gn.prototype.update=function(e){for(var n=0,i=this.animationsList.length;nr.duration||r.time<0)&&(r.direction*=-1,r.time>r.duration&&(r.time=r.duration,r.directionBackwards=!0),r.time<0&&(r.time=0,r.directionBackwards=!1)):(r.time=r.time%r.duration,r.time<0&&(r.time+=r.duration));var o=r.start+t.Math.clamp(Math.floor(r.time/a),0,r.length-1),s=r.weight;o!==r.currentFrame&&(this.morphTargetInfluences[r.lastFrame]=0,this.morphTargetInfluences[r.currentFrame]=1*s,this.morphTargetInfluences[o]=0,r.lastFrame=r.currentFrame,r.currentFrame=o);var h=r.time%a/a;r.directionBackwards&&(h=1-h),r.currentFrame!==r.lastFrame?(this.morphTargetInfluences[r.currentFrame]=h*s,this.morphTargetInfluences[r.lastFrame]=(1-h)*s):this.morphTargetInfluences[r.currentFrame]=s}}},vn.prototype=Object.create(X.prototype),vn.prototype.constructor=vn,yn.prototype=Object.create(Q.prototype),yn.prototype.constructor=yn,xn.prototype=Object.create(Pt.prototype),xn.prototype.constructor=xn,bn.prototype=Object.create(Pt.prototype),bn.prototype.constructor=bn,bn.prototype.update=function(){var t=new s,e=new s,n=new T;return function(){var i=["a","b","c"];this.object.updateMatrixWorld(!0),n.getNormalMatrix(this.object.matrixWorld);var r=this.object.matrixWorld,a=this.geometry.attributes.position,o=this.object.geometry;if(o&&o.isGeometry)for(var s=o.vertices,h=o.faces,c=0,l=0,u=h.length;l.99999?this.quaternion.set(0,0,0,1):n.y<-.99999?this.quaternion.set(1,0,0,0):(e.set(n.z,0,-n.x).normalize(),t=Math.acos(n.y),this.quaternion.setFromAxisAngle(e,t))}}(),t.ArrowHelper.prototype.setLength=function(t,e,n){void 0===e&&(e=.2*t),void 0===n&&(n=.2*e),this.line.scale.set(1,Math.max(0,t-e),1),this.line.updateMatrix(),this.cone.scale.set(n,e,n),this.cone.position.y=t,this.cone.updateMatrix()},t.ArrowHelper.prototype.setColor=function(t){this.line.material.color.copy(t),this.cone.material.color.copy(t)},Fn.prototype=Object.create(Pt.prototype),Fn.prototype.constructor=Fn,Bn.prototype=Object.create(q.prototype),Bn.prototype.constructor=Bn,zn.prototype=Object.create(q.prototype),zn.prototype.constructor=zn,Gn.prototype=Object.create(zn.prototype),Gn.prototype.constructor=Gn,kn.prototype=Object.create(zn.prototype),kn.prototype.constructor=kn,Hn.prototype=Object.create(zn.prototype),Hn.prototype.constructor=Hn,Vn.prototype=Object.create(zn.prototype),Vn.prototype.constructor=Vn,jn.prototype=Object.create(Q.prototype),jn.prototype.constructor=jn,Wn.prototype=Object.create(q.prototype),Wn.prototype.constructor=Wn,Xn.prototype=Object.create(Q.prototype),Xn.prototype.constructor=Xn,Yn.prototype=Object.create(q.prototype),Yn.prototype.constructor=Yn,qn.prototype=Object.create(Fe.prototype),qn.prototype.constructor=qn,Zn.prototype=Object.create(Q.prototype),Zn.prototype.constructor=Zn,Jn.prototype=Object.create(q.prototype),Jn.prototype.constructor=Jn,Qn.prototype=Object.create(q.prototype),Qn.prototype.constructor=Qn,Kn.prototype=Object.create(Q.prototype),Kn.prototype.constructor=Kn,$n.prototype=Object.create(q.prototype),$n.prototype.constructor=$n,ti.prototype=Object.create(q.prototype),ti.prototype.constructor=ti,ei.prototype=Object.create(ti.prototype),ei.prototype.constructor=ei,ni.prototype=Object.create(Q.prototype),ni.prototype.constructor=ni,ii.prototype=Object.create(Q.prototype),ii.prototype.constructor=ii,ri.prototype=Object.create(q.prototype),ri.prototype.constructor=ri,t.CatmullRomCurve3=function(){function t(){}var e=new s,n=new t,i=new t,r=new t;return t.prototype.init=function(t,e,n,i){this.c0=t,this.c1=n,this.c2=-3*t+3*e-2*n-i,this.c3=2*t-2*e+n+i},t.prototype.initNonuniformCatmullRom=function(t,e,n,i,r,a,o){var s=(e-t)/r-(n-t)/(r+a)+(n-e)/a,h=(n-e)/a-(i-e)/(a+o)+(i-n)/o;s*=a,h*=a,this.init(e,n,s,h)},t.prototype.initCatmullRom=function(t,e,n,i,r){this.init(e,n,r*(n-t),r*(i-e))},t.prototype.calc=function(t){var e=t*t,n=e*t;return this.c0+this.c1*t+this.c2*e+this.c3*n},Re.create(function(t){this.points=t||[],this.closed=!1},function(t){var a,o,h,c,l=this.points;c=l.length,c<2&&console.log("duh, you need at least 2 points"),a=(c-(this.closed?0:1))*t,o=Math.floor(a),h=a-o,this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/l.length)+1)*l.length:0===h&&o===c-1&&(o=c-2,h=1);var u,d,p,f;if(this.closed||o>0?u=l[(o-1)%c]:(e.subVectors(l[0],l[1]).add(l[0]),u=e),d=l[o%c],p=l[(o+1)%c],this.closed||o+2n.length-2?n.length-1:r+1],l=n[r>n.length-3?n.length-1:r+2],u=t.CurveUtils.interpolate;return new s(u(o.x,h.x,c.x,l.x,a),u(o.y,h.y,c.y,l.y,a),u(o.z,h.z,c.z,l.z,a))}),t.CubicBezierCurve3=Re.create(function(t,e,n,i){this.v0=t,this.v1=e,this.v2=n,this.v3=i},function(e){var n=t.ShapeUtils.b3;return new s(n(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y),n(e,this.v0.z,this.v1.z,this.v2.z,this.v3.z))}),t.QuadraticBezierCurve3=Re.create(function(t,e,n){this.v0=t,this.v1=e,this.v2=n},function(e){var n=t.ShapeUtils.b2;return new s(n(e,this.v0.x,this.v1.x,this.v2.x),n(e,this.v0.y,this.v1.y,this.v2.y),n(e,this.v0.z,this.v1.z,this.v2.z))}),t.LineCurve3=Re.create(function(t,e){this.v1=t,this.v2=e},function(t){if(1===t)return this.v2.clone();var e=new s;return e.subVectors(this.v2,this.v1),e.multiplyScalar(t),e.add(this.v1),e}),oi.prototype=Object.create(Ue.prototype),oi.prototype.constructor=oi,t.SceneUtils={createMultiMaterialObject:function(t,e){for(var n=new Dt,i=0,r=e.length;i Date: Sat, 9 Jul 2016 00:48:17 -0400 Subject: [PATCH 3/4] move shaders back into glsl files --- build/three.js | 488 +++++++++++++----- build/three.min.js | 30 +- package.json | 1 + rollup.config.js | 6 + src/materials/ShadowMaterial.js | 4 +- src/renderers/shaders/ShaderChunk.js | 323 ++++++++---- .../ShaderChunk/alphamap_fragment.glsl | 5 + .../ShaderChunk/alphamap_pars_fragment.glsl | 5 + .../ShaderChunk/alphatest_fragment.glsl | 5 + .../shaders/ShaderChunk/ambient_pars.glsl | 15 + .../shaders/ShaderChunk/aomap_fragment.glsl | 15 + .../ShaderChunk/aomap_pars_fragment.glsl | 6 + .../shaders/ShaderChunk/begin_vertex.glsl | 2 + .../ShaderChunk/beginnormal_vertex.glsl | 2 + src/renderers/shaders/ShaderChunk/bsdfs.glsl | 179 +++++++ .../ShaderChunk/bumpmap_pars_fragment.glsl | 40 ++ .../ShaderChunk/clipping_planes_fragment.glsl | 10 + .../clipping_planes_pars_fragment.glsl | 9 + .../clipping_planes_pars_vertex.glsl | 3 + .../ShaderChunk/clipping_planes_vertex.glsl | 4 + .../shaders/ShaderChunk/color_fragment.glsl | 5 + .../ShaderChunk/color_pars_fragment.glsl | 5 + .../ShaderChunk/color_pars_vertex.glsl | 5 + .../shaders/ShaderChunk/color_vertex.glsl | 5 + src/renderers/shaders/ShaderChunk/common.glsl | 74 +++ .../cube_uv_reflection_fragment.glsl | 128 +++++ .../ShaderChunk/defaultnormal_vertex.glsl | 7 + .../displacementmap_pars_vertex.glsl | 7 + .../ShaderChunk/displacementmap_vertex.glsl | 5 + .../ShaderChunk/emissivemap_fragment.glsl | 9 + .../emissivemap_pars_fragment.glsl | 5 + .../ShaderChunk/encodings_fragment.glsl | 1 + .../ShaderChunk/encodings_pars_fragment.glsl | 78 +++ .../shaders/ShaderChunk/envmap_fragment.glsl | 60 +++ .../ShaderChunk/envmap_pars_fragment.glsl | 25 + .../ShaderChunk/envmap_pars_vertex.glsl | 13 + .../shaders/ShaderChunk/envmap_vertex.glsl | 25 + .../shaders/ShaderChunk/fog_fragment.glsl | 25 + .../ShaderChunk/fog_pars_fragment.glsl | 15 + .../ShaderChunk/lightmap_fragment.glsl | 5 + .../ShaderChunk/lightmap_pars_fragment.glsl | 6 + .../ShaderChunk/lights_lambert_vertex.glsl | 99 ++++ .../shaders/ShaderChunk/lights_pars.glsl | 300 +++++++++++ .../ShaderChunk/lights_phong_fragment.glsl | 5 + .../lights_phong_pars_fragment.glsl | 45 ++ .../ShaderChunk/lights_physical_fragment.glsl | 10 + .../lights_physical_pars_fragment.glsl | 91 ++++ .../shaders/ShaderChunk/lights_template.glsl | 136 +++++ .../ShaderChunk/logdepthbuf_fragment.glsl | 5 + .../logdepthbuf_pars_fragment.glsl | 11 + .../ShaderChunk/logdepthbuf_pars_vertex.glsl | 11 + .../ShaderChunk/logdepthbuf_vertex.glsl | 15 + .../shaders/ShaderChunk/map_fragment.glsl | 8 + .../ShaderChunk/map_pars_fragment.glsl | 5 + .../ShaderChunk/map_particle_fragment.glsl | 6 + .../map_particle_pars_fragment.glsl | 6 + .../ShaderChunk/metalnessmap_fragment.glsl | 8 + .../metalnessmap_pars_fragment.glsl | 5 + .../ShaderChunk/morphnormal_vertex.glsl | 8 + .../ShaderChunk/morphtarget_pars_vertex.glsl | 13 + .../ShaderChunk/morphtarget_vertex.glsl | 17 + .../shaders/ShaderChunk/normal_flip.glsl | 5 + .../shaders/ShaderChunk/normal_fragment.glsl | 23 + .../ShaderChunk/normalmap_pars_fragment.glsl | 27 + .../shaders/ShaderChunk/packing.glsl | 45 ++ .../premultiplied_alpha_fragment.glsl | 6 + .../shaders/ShaderChunk/project_vertex.glsl | 11 + .../ShaderChunk/roughnessmap_fragment.glsl | 8 + .../roughnessmap_pars_fragment.glsl | 5 + .../ShaderChunk/shadowmap_pars_fragment.glsl | 231 +++++++++ .../ShaderChunk/shadowmap_pars_vertex.glsl | 24 + .../shaders/ShaderChunk/shadowmap_vertex.glsl | 33 ++ .../ShaderChunk/shadowmask_pars_fragment.glsl | 50 ++ .../shaders/ShaderChunk/skinbase_vertex.glsl | 8 + .../ShaderChunk/skinning_pars_vertex.glsl | 47 ++ .../shaders/ShaderChunk/skinning_vertex.glsl | 12 + .../ShaderChunk/skinnormal_vertex.glsl | 12 + .../ShaderChunk/specularmap_fragment.glsl | 12 + .../specularmap_pars_fragment.glsl | 5 + .../ShaderChunk/tonemapping_fragment.glsl | 5 + .../tonemapping_pars_fragment.glsl | 39 ++ .../ShaderChunk/uv2_pars_fragment.glsl | 5 + .../shaders/ShaderChunk/uv2_pars_vertex.glsl | 6 + .../shaders/ShaderChunk/uv2_vertex.glsl | 5 + .../shaders/ShaderChunk/uv_pars_fragment.glsl | 5 + .../shaders/ShaderChunk/uv_pars_vertex.glsl | 6 + .../shaders/ShaderChunk/uv_vertex.glsl | 5 + .../shaders/ShaderChunk/worldpos_vertex.glsl | 13 + .../shaders/ShaderLib/cube_frag.glsl | 14 + .../shaders/ShaderLib/cube_vert.glsl | 12 + .../shaders/ShaderLib/depth_frag.glsl | 43 ++ .../shaders/ShaderLib/depth_vert.glsl | 23 + .../shaders/ShaderLib/distanceRGBA_frag.glsl | 14 + .../shaders/ShaderLib/distanceRGBA_vert.glsl | 20 + .../shaders/ShaderLib/equirect_frag.glsl | 17 + .../shaders/ShaderLib/equirect_vert.glsl | 12 + .../shaders/ShaderLib/linedashed_frag.glsl | 40 ++ .../shaders/ShaderLib/linedashed_vert.glsl | 23 + .../shaders/ShaderLib/meshbasic_frag.glsl | 56 ++ .../shaders/ShaderLib/meshbasic_vert.glsl | 37 ++ .../shaders/ShaderLib/meshlambert_frag.glsl | 83 +++ .../shaders/ShaderLib/meshlambert_vert.glsl | 48 ++ .../shaders/ShaderLib/meshphong_frag.glsl | 67 +++ .../shaders/ShaderLib/meshphong_vert.glsl | 55 ++ .../shaders/ShaderLib/meshphysical_frag.glsl | 84 +++ .../shaders/ShaderLib/meshphysical_vert.glsl | 54 ++ .../shaders/ShaderLib/normal_frag.glsl | 16 + .../shaders/ShaderLib/normal_vert.glsl | 18 + .../shaders/ShaderLib/points_frag.glsl | 33 ++ .../shaders/ShaderLib/points_vert.glsl | 27 + .../shaders/ShaderLib/shadow_frag.glsl | 14 + .../shaders/ShaderLib/shadow_vert.glsl | 10 + 112 files changed, 3673 insertions(+), 264 deletions(-) create mode 100644 src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/ambient_pars.glsl create mode 100644 src/renderers/shaders/ShaderChunk/aomap_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/begin_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/bsdfs.glsl create mode 100644 src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/color_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/color_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/common.glsl create mode 100644 src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/encodings_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/envmap_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/envmap_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/fog_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/lights_pars.glsl create mode 100644 src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/lights_template.glsl create mode 100644 src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/map_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/normal_flip.glsl create mode 100644 src/renderers/shaders/ShaderChunk/normal_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/packing.glsl create mode 100644 src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/project_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/skinning_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/uv2_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl create mode 100644 src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/uv_vertex.glsl create mode 100644 src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl create mode 100644 src/renderers/shaders/ShaderLib/cube_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/cube_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/depth_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/depth_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/equirect_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/equirect_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/linedashed_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/linedashed_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/meshbasic_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/meshbasic_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/meshlambert_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/meshlambert_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/meshphong_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/meshphong_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/meshphysical_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/meshphysical_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/normal_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/normal_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/points_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/points_vert.glsl create mode 100644 src/renderers/shaders/ShaderLib/shadow_frag.glsl create mode 100644 src/renderers/shaders/ShaderLib/shadow_vert.glsl diff --git a/build/three.js b/build/three.js index 3bceefc0b511c5..0b98760d5a8687 100644 --- a/build/three.js +++ b/build/three.js @@ -8001,114 +8001,327 @@ }; - exports.ShaderChunk = {}; - - exports.ShaderChunk["alphamap_fragment"] = "#ifdef USE_ALPHAMAP\n\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n"; - exports.ShaderChunk["alphamap_pars_fragment"] = "#ifdef USE_ALPHAMAP\n\n\tuniform sampler2D alphaMap;\n\n#endif\n"; - exports.ShaderChunk["alphatest_fragment"] = "#ifdef ALPHATEST\n\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n"; - exports.ShaderChunk["ambient_pars"] = "uniform vec3 ambientLightColor;\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n"; - exports.ShaderChunk["aomap_fragment"] = "#ifdef USE_AOMAP\n\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["aomap_pars_fragment"] = "#ifdef USE_AOMAP\n\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n\n#endif"; - exports.ShaderChunk["begin_vertex"] = "\nvec3 transformed = vec3( position );\n"; - exports.ShaderChunk["beginnormal_vertex"] = "\nvec3 objectNormal = vec3( normal );\n"; - exports.ShaderChunk["bsdfs"] = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n\n}\n\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\n\t\tif( decayExponent > 0.0 ) {\n\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\n\t\t\t// based upon Frostbite 3 Moving to Physically-based Rendering\n\t\t\t// page 32, equation 26: E[window1]\n\t\t\t// http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\n\t\t\t// this is intended to be used on spot and point lights who are represented as luminous intensity\n\t\t\t// but who must be converted to luminous irradiance for surface lighting calculation\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n\n#else\n\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\n#endif\n\n\t\t}\n\n\t\treturn 1.0;\n}\n\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\n\treturn RECIPROCAL_PI * diffuseColor;\n\n} // validated\n\n\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\n\t// Original approximation by Christophe Schlick '94\n\t//;float fresnel = pow( 1.0 - dotLH, 5.0 );\n\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n\n} // validated\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (34)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\t// geometry term = G(l)⋅G(v) / 4(n⋅l)(n⋅v)\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\n\treturn 1.0 / ( gl * gv );\n\n} // validated\n\n// from page 12, listing 2 of http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\tfloat a2 = pow2( alpha );\n\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\n\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\n\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n\n}\n\n\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat alpha = pow2( roughness ); // UE4's roughness\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\n\tfloat D = D_GGX( alpha, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\n\tvec4 r = roughness * c0 + c1;\n\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\n\treturn specularColor * AB.x + AB.y;\n\n} // validated\n\n\nfloat G_BlinnPhong_Implicit( /* const in float dotNL, const in float dotNV */ ) {\n\n\t// geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v)\n\treturn 0.25;\n\n}\n\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n\n}\n\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\t//float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\t//float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\n\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; - exports.ShaderChunk["bumpmap_pars_fragment"] = "#ifdef USE_BUMPMAP\n\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\n\t// Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n\t// http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n\t// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n\tvec2 dHdxy_fwd() {\n\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n\t\treturn vec2( dBx, dBy );\n\n\t}\n\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\t\t// normalized\n\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\n\t}\n\n#endif\n"; - exports.ShaderChunk["clipping_planes_fragment"] = "#if NUM_CLIPPING_PLANES > 0\n\n\tfor ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\n\t}\n\n#endif\n"; - exports.ShaderChunk["clipping_planes_pars_fragment"] = "#if NUM_CLIPPING_PLANES > 0\n\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n\n#endif\n"; - exports.ShaderChunk["clipping_planes_pars_vertex"] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; - exports.ShaderChunk["clipping_planes_vertex"] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n\n"; - exports.ShaderChunk["color_fragment"] = "#ifdef USE_COLOR\n\n\tdiffuseColor.rgb *= vColor;\n\n#endif"; - exports.ShaderChunk["color_pars_fragment"] = "#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif\n"; - exports.ShaderChunk["color_pars_vertex"] = "#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif"; - exports.ShaderChunk["color_vertex"] = "#ifdef USE_COLOR\n\n\tvColor.xyz = color.xyz;\n\n#endif"; - exports.ShaderChunk["common"] = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\n\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\n// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range.\n// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\n\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\n\n\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n}\n\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n\n}\n\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\n\treturn - distance * planeNormal + point;\n\n}\n\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n\n}\n\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n\n}\n"; - exports.ShaderChunk["cube_uv_reflection_fragment"] = "#ifdef ENVMAP_TYPE_CUBE_UV\n\n#define cubeUV_textureSize (1024.0)\n\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\n\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\t// Clamp the value to the max mip level counts. hard coded to 6 mips\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\n\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\t// float powScale = exp2(roughnessLevel + mipLevel);\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\t// float scale = 1.0 / exp2(roughnessLevel + 2.0 + mipLevel);\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\t// float mipOffset = 0.75*(1.0 - 1.0/exp2(mipLevel))/exp2(roughnessLevel);\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\n\tfloat rcpPowScale = 1.0 / powScale;\n\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\n\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\n\t// round to nearest mipmap if we are not interpolating.\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\n\t// Tri linear interpolation.\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\n\tvec4 result = mix(color10, color20, t);\n\n\treturn vec4(result.rgb, 1.0);\n}\n\n#endif\n"; - exports.ShaderChunk["defaultnormal_vertex"] = "#ifdef FLIP_SIDED\n\n\tobjectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; - exports.ShaderChunk["displacementmap_pars_vertex"] = "#ifdef USE_DISPLACEMENTMAP\n\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n\n#endif\n"; - exports.ShaderChunk["displacementmap_vertex"] = "#ifdef USE_DISPLACEMENTMAP\n\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n\n#endif\n"; - exports.ShaderChunk["emissivemap_fragment"] = "#ifdef USE_EMISSIVEMAP\n\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n\n#endif\n"; - exports.ShaderChunk["emissivemap_pars_fragment"] = "#ifdef USE_EMISSIVEMAP\n\n\tuniform sampler2D emissiveMap;\n\n#endif\n"; - exports.ShaderChunk["encodings_fragment"] = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; - exports.ShaderChunk["encodings_pars_fragment"] = "// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/\n\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\n\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\n\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\n\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\n\n// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html\n\n// M matrix, for encoding\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\n\n// Inverse M matrix, for decoding\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n"; - exports.ShaderChunk["envmap_fragment"] = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n\t\t// Transforming Normal Vectors with the Inverse Transformation\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#else\n\n\t\tvec3 reflectVec = vReflect;\n\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\n\t#endif\n\n\tenvColor = envMapTexelToLinear( envColor );\n\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["envmap_pars_fragment"] = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n\n#ifdef USE_ENVMAP\n\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["envmap_pars_vertex"] = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\n\t#else\n\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["envmap_vertex"] = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\tvWorldPosition = worldPosition.xyz;\n\n\t#else\n\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["fog_fragment"] = "#ifdef USE_FOG\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n\t#else\n\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\n\t#endif\n\n\t#ifdef FOG_EXP2\n\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\n\t#else\n\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\n\t#endif\n\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\n#endif\n"; - exports.ShaderChunk["fog_pars_fragment"] = "#ifdef USE_FOG\n\n\tuniform vec3 fogColor;\n\n\t#ifdef FOG_EXP2\n\n\t\tuniform float fogDensity;\n\n\t#else\n\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n\n#endif"; - exports.ShaderChunk["lightmap_fragment"] = "#ifdef USE_LIGHTMAP\n\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\n\n#endif\n"; - exports.ShaderChunk["lightmap_pars_fragment"] = "#ifdef USE_LIGHTMAP\n\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n\n#endif"; - exports.ShaderChunk["lights_lambert_vertex"] = "vec3 diffuse = vec3( 1.0 );\n\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\n\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\n\nvLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\n\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n\n#if NUM_POINT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\n#endif\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\t}\n\n#endif\n\n#if NUM_DIR_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\n#endif\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\n\t\t#endif\n\n\t}\n\n#endif\n"; - exports.ShaderChunk["lights_pars"] = "uniform vec3 ambientLightColor;\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n\n#if NUM_DIR_LIGHTS > 0\n\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\n\t}\n\n#endif\n\n\n#if NUM_POINT_LIGHTS > 0\n\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\n\t}\n\n#endif\n\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\n\t}\n\n#endif\n\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tirradiance *= PI;\n\n\t\t#endif\n\n\t\treturn irradiance;\n\n\t}\n\n#endif\n\n\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\n\tvec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) {\n\n\t\t#include \n\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\n\t\t\t// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\n\t\t\t// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#else\n\n\t\t\t\t// force the bias high to get the last LOD level as it is the most blurred.\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\n\t\t#else\n\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\n\t\t#endif\n\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\n\t}\n\n\t// taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\n\t\t//float envMapWidth = pow( 2.0, maxMIPLevelScalar );\n\t\t//float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\n\t\t// clamp to allowable LOD ranges.\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\n\t}\n\n\tvec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\n\t\t#endif\n\n\t\t#include \n\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\n\t\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#endif\n\n\t\treturn envMapColor.rgb * envMapIntensity;\n\n\t}\n\n#endif\n"; - exports.ShaderChunk["lights_phong_fragment"] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; - exports.ShaderChunk["lights_phong_pars_fragment"] = "varying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n\nstruct BlinnPhongMaterial {\n\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n\n};\n\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n\n}\n\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n\n#define Material_LightProbeLOD( material )\t(0)\n"; - exports.ShaderChunk["lights_physical_fragment"] = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat ); // Burley clearcoat model\n\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; - exports.ShaderChunk["lights_physical_pars_fragment"] = "struct PhysicalMaterial {\n\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n\n};\n\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\n\n// Clear coat directional hemishperical reflectance (this approximation should be improved)\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n\n}\n\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n\t#ifndef STANDARD\n\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\n\t#endif\n\n}\n\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\n\t#ifndef STANDARD\n\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\n\t#endif\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\n\n// ref: http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n\n}\n"; - exports.ShaderChunk["lights_template"] = "//\n// This is a template that can be used to light a material, it uses pluggable RenderEquations (RE)\n// for specific lighting scenarios.\n//\n// Instructions for use:\n// - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined\n// - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ???\n// - Create a material parameter that is to be passed as the third parameter to your lighting functions.\n//\n// TODO:\n// - Add area light support.\n// - Add sphere light support.\n// - Add diffuse light probe (irradiance cubemap) support.\n//\n\nGeometricContext geometry;\n\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n\nIncidentLight directLight;\n\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tPointLight pointLight;\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tSpotLight spotLight;\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tDirectionalLight directionalLight;\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if defined( RE_IndirectDiffuse )\n\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n\t#ifdef USE_LIGHTMAP\n\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tlightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage\n\n\t\t#endif\n\n\t\tirradiance += lightMapIrradiance;\n\n\t#endif\n\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t}\n\n\t#endif\n\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t// TODO, replace 8 with the real maxMIPLevel\n\t \tirradiance += getLightProbeIndirectIrradiance( /*lightProbe,*/ geometry, 8 );\n\n\t#endif\n\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n\n#endif\n\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\n\t// TODO, replace 8 with the real maxMIPLevel\n\tvec3 radiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_BlinnShininessExponent( material ), 8 );\n\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n\n#endif\n"; - exports.ShaderChunk["logdepthbuf_fragment"] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif"; - exports.ShaderChunk["logdepthbuf_pars_fragment"] = "#ifdef USE_LOGDEPTHBUF\n\n\tuniform float logDepthBufFC;\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["logdepthbuf_pars_vertex"] = "#ifdef USE_LOGDEPTHBUF\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\n\t#endif\n\n\tuniform float logDepthBufFC;\n\n#endif"; - exports.ShaderChunk["logdepthbuf_vertex"] = "#ifdef USE_LOGDEPTHBUF\n\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\n\t#else\n\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["map_fragment"] = "#ifdef USE_MAP\n\n\tvec4 texelColor = texture2D( map, vUv );\n\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n\n#endif\n"; - exports.ShaderChunk["map_pars_fragment"] = "#ifdef USE_MAP\n\n\tuniform sampler2D map;\n\n#endif\n"; - exports.ShaderChunk["map_particle_fragment"] = "#ifdef USE_MAP\n\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n\n#endif\n"; - exports.ShaderChunk["map_particle_pars_fragment"] = "#ifdef USE_MAP\n\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n\n#endif\n"; - exports.ShaderChunk["metalnessmap_fragment"] = "float metalnessFactor = metalness;\n\n#ifdef USE_METALNESSMAP\n\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n\n#endif\n"; - exports.ShaderChunk["metalnessmap_pars_fragment"] = "#ifdef USE_METALNESSMAP\n\n\tuniform sampler2D metalnessMap;\n\n#endif"; - exports.ShaderChunk["morphnormal_vertex"] = "#ifdef USE_MORPHNORMALS\n\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n#endif\n"; - exports.ShaderChunk["morphtarget_pars_vertex"] = "#ifdef USE_MORPHTARGETS\n\n\t#ifndef USE_MORPHNORMALS\n\n\tuniform float morphTargetInfluences[ 8 ];\n\n\t#else\n\n\tuniform float morphTargetInfluences[ 4 ];\n\n\t#endif\n\n#endif"; - exports.ShaderChunk["morphtarget_vertex"] = "#ifdef USE_MORPHTARGETS\n\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n\t#ifndef USE_MORPHNORMALS\n\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["normal_flip"] = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n"; - exports.ShaderChunk["normal_fragment"] = "#ifdef FLAT_SHADED\n\n\t// Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ...\n\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n\n#else\n\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n\n#endif\n\n#ifdef USE_NORMALMAP\n\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n"; - exports.ShaderChunk["normalmap_pars_fragment"] = "#ifdef USE_NORMALMAP\n\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\n\t// Per-Pixel Tangent Space Normal Mapping\n\t// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\n\t}\n\n#endif\n"; - exports.ShaderChunk["packing"] = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\n\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\n\nconst float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1)\nconst float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1)\n\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\n\nconst float ShiftRight8 = 1. / 256.;\n\nvec4 packDepthToRGBA( const in float v ) {\n\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\n\treturn r * PackUpscale;\n\n}\n\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\n\treturn dot( v, UnpackFactors );\n\n}\n\n// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions\n\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\n\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; - exports.ShaderChunk["premultiplied_alpha_fragment"] = "#ifdef PREMULTIPLIED_ALPHA\n\n\t// Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation.\n\tgl_FragColor.rgb *= gl_FragColor.a;\n\n#endif\n"; - exports.ShaderChunk["project_vertex"] = "#ifdef USE_SKINNING\n\n\tvec4 mvPosition = modelViewMatrix * skinned;\n\n#else\n\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n"; - exports.ShaderChunk["roughnessmap_fragment"] = "float roughnessFactor = roughness;\n\n#ifdef USE_ROUGHNESSMAP\n\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n\n#endif\n"; - exports.ShaderChunk["roughnessmap_pars_fragment"] = "#ifdef USE_ROUGHNESSMAP\n\n\tuniform sampler2D roughnessMap;\n\n#endif"; - exports.ShaderChunk["shadowmap_pars_fragment"] = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\n\t#endif\n\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\n\t}\n\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\n\t\tvec2 f = fract( uv * size + 0.5 );\n\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\n\t\treturn c;\n\n\t}\n\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\n\t\t// if ( something && something ) breaks ATI OpenGL shader compiler\n\t\t// if ( all( something, something ) ) using this instead\n\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n\t\tbool frustumTest = all( frustumTestVec );\n\n\t\tif ( frustumTest ) {\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering:\n\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\n\t\t#endif\n\n\t\t}\n\n\t\treturn 1.0;\n\n\t}\n\n\t// cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D\n\t// vector suitable for 2D texture mapping. This code uses the following layout for the\n\t// 2D texture:\n\t//\n\t// xzXZ\n\t// y Y\n\t//\n\t// Y - Positive y direction\n\t// y - Negative y direction\n\t// X - Positive x direction\n\t// x - Negative x direction\n\t// Z - Positive z direction\n\t// z - Negative z direction\n\t//\n\t// Source and test bed:\n\t// https://gist.github.com/tschw/da10c43c467ce8afd0c4\n\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\n\t\t// Number of texels to avoid at the edge of each square\n\n\t\tvec3 absV = abs( v );\n\n\t\t// Intersect unit cube\n\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\n\t\t// Apply scale to avoid seams\n\n\t\t// two texels less per square (one texel will do for NEAREST)\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\n\t\t// Unwrap\n\n\t\t// space: -1 ... 1 range for each square\n\t\t//\n\t\t// #X##\t\tdim := ( 4 , 2 )\n\t\t// # #\t\tcenter := ( 1 , 1 )\n\n\t\tvec2 planar = v.xy;\n\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\n\t\tif ( absV.z >= almostOne ) {\n\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\n\t\t} else if ( absV.x >= almostOne ) {\n\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\n\t\t} else if ( absV.y >= almostOne ) {\n\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\n\t\t}\n\n\t\t// Transform to UV space\n\n\t\t// scale := 0.5 / dim\n\t\t// translate := ( center + 0.5 ) / dim\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\n\t}\n\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\n\t\t// for point lights, the uniform @vShadowCoord is re-purposed to hold\n\t\t// the distance from the light to the world-space position of the fragment.\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\n\t\t// bd3D = base direction 3D\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t// dp = distance from light to fragment position\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering\n\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\n\t\t#endif\n\n\t}\n\n#endif\n"; - exports.ShaderChunk["shadowmap_pars_vertex"] = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["shadowmap_vertex"] = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["shadowmask_pars_fragment"] = "float getShadowMask() {\n\n\tfloat shadow = 1.0;\n\n\t#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\tDirectionalLight directionalLight;\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\tSpotLight spotLight;\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\tPointLight pointLight;\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#endif\n\n\treturn shadow;\n\n}\n"; - exports.ShaderChunk["skinbase_vertex"] = "#ifdef USE_SKINNING\n\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif"; - exports.ShaderChunk["skinning_pars_vertex"] = "#ifdef USE_SKINNING\n\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\n\t#ifdef BONE_TEXTURE\n\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\n\t\t\ty = dy * ( y + 0.5 );\n\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\n\t\t\treturn bone;\n\n\t\t}\n\n\t#else\n\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\n\t\t}\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["skinning_vertex"] = "#ifdef USE_SKINNING\n\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n\n#endif\n"; - exports.ShaderChunk["skinnormal_vertex"] = "#ifdef USE_SKINNING\n\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\n#endif\n"; - exports.ShaderChunk["specularmap_fragment"] = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n\n#else\n\n\tspecularStrength = 1.0;\n\n#endif"; - exports.ShaderChunk["specularmap_pars_fragment"] = "#ifdef USE_SPECULARMAP\n\n\tuniform sampler2D specularMap;\n\n#endif"; - exports.ShaderChunk["tonemapping_fragment"] = "#if defined( TONE_MAPPING )\n\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n\n#endif\n"; - exports.ShaderChunk["tonemapping_pars_fragment"] = "#define saturate(a) clamp( a, 0.0, 1.0 )\n\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\n\n// exposure only\nvec3 LinearToneMapping( vec3 color ) {\n\n return toneMappingExposure * color;\n\n}\n\n// source: https://www.cs.utah.edu/~reinhard/cdrom/\nvec3 ReinhardToneMapping( vec3 color ) {\n\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n\n}\n\n// source: http://filmicgames.com/archives/75\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\n // John Hable's filmic operator from Uncharted 2 video game\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n\n}\n\n// source: http://filmicgames.com/archives/75\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n\n}\n"; - exports.ShaderChunk["uv2_pars_fragment"] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvarying vec2 vUv2;\n\n#endif"; - exports.ShaderChunk["uv2_pars_vertex"] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\n#endif"; - exports.ShaderChunk["uv2_vertex"] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvUv2 = uv2;\n\n#endif"; - exports.ShaderChunk["uv_pars_fragment"] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvarying vec2 vUv;\n\n#endif"; - exports.ShaderChunk["uv_pars_vertex"] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n\n#endif\n"; - exports.ShaderChunk["uv_vertex"] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif"; - exports.ShaderChunk["worldpos_vertex"] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n\t#ifdef USE_SKINNING\n\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\n\t#else\n\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\n\t#endif\n\n#endif\n"; - exports.ShaderChunk["cube_frag"] = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\n\nvarying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n\n}\n"; - exports.ShaderChunk["cube_vert"] = "varying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["depth_frag"] = "#if DEPTH_PACKING == 3200\n\n\tuniform float opacity;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( 1.0 );\n\n\t#if DEPTH_PACKING == 3200\n\n\t\tdiffuseColor.a = opacity;\n\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\n\t#if DEPTH_PACKING == 3200\n\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\n\t#elif DEPTH_PACKING == 3201\n\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\n\t#endif\n\n}\n"; - exports.ShaderChunk["depth_vert"] = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["distanceRGBA_frag"] = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n\n#include \n#include \n#include \n\nvoid main () {\n\n\t#include \n\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n\n}\n"; - exports.ShaderChunk["distanceRGBA_vert"] = "varying vec4 vWorldPosition;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvWorldPosition = worldPosition;\n\n}\n"; - exports.ShaderChunk["equirect_frag"] = "uniform sampler2D tEquirect;\nuniform float tFlip;\n\nvarying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\t// \tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n}\n"; - exports.ShaderChunk["equirect_vert"] = "varying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["linedashed_frag"] = "uniform vec3 diffuse;\nuniform float opacity;\n\nuniform float dashSize;\nuniform float totalSize;\n\nvarying float vLineDistance;\n\n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\n\t\tdiscard;\n\n\t}\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\n\toutgoingLight = diffuseColor.rgb; // simple shader\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["linedashed_vert"] = "uniform float scale;\nattribute float lineDistance;\n\nvarying float vLineDistance;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvLineDistance = scale * lineDistance;\n\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["meshbasic_frag"] = "uniform vec3 diffuse;\nuniform float opacity;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n\t#include \n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["meshbasic_vert"] = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#ifdef USE_ENVMAP\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["meshlambert_frag"] = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n\nvarying vec3 vLightFront;\n\n#ifdef DOUBLE_SIDED\n\n\tvarying vec3 vLightBack;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\n\t#include \n\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\n\t#ifdef DOUBLE_SIDED\n\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\n\t#else\n\n\t\treflectedLight.directDiffuse = vLightFront;\n\n\t#endif\n\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\t#include \n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["meshlambert_vert"] = "#define LAMBERT\n\nvarying vec3 vLightFront;\n\n#ifdef DOUBLE_SIDED\n\n\tvarying vec3 vLightBack;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["meshphong_frag"] = "#define PHONG\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["meshphong_vert"] = "#define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["meshphysical_frag"] = "#define PHYSICAL\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\n\nuniform float envMapIntensity; // temporary\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["meshphysical_vert"] = "#define PHYSICAL\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["normal_frag"] = "uniform float opacity;\nvarying vec3 vNormal;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\n\t#include \n\n}\n"; - exports.ShaderChunk["normal_vert"] = "varying vec3 vNormal;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\tvNormal = normalize( normalMatrix * normal );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["points_frag"] = "uniform vec3 diffuse;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\toutgoingLight = diffuseColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["points_vert"] = "uniform float size;\nuniform float scale;\n\n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - exports.ShaderChunk["shadow_frag"] = "uniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n\n}\n"; - exports.ShaderChunk["shadow_vert"] = "#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n"; + + var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\n\tuniform sampler2D alphaMap;\n\n#endif\n"; + + var alphatest_fragment = "#ifdef ALPHATEST\n\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n"; + + var ambient_pars = "uniform vec3 ambientLightColor;\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n"; + + var aomap_fragment = "#ifdef USE_AOMAP\n\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\n\t#endif\n\n#endif\n"; + + var aomap_pars_fragment = "#ifdef USE_AOMAP\n\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n\n#endif"; + + var begin_vertex = "\nvec3 transformed = vec3( position );\n"; + + var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n"; + + var bsdfs = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n\n}\n\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\n\t\tif( decayExponent > 0.0 ) {\n\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\n\t\t\t// based upon Frostbite 3 Moving to Physically-based Rendering\n\t\t\t// page 32, equation 26: E[window1]\n\t\t\t// http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\n\t\t\t// this is intended to be used on spot and point lights who are represented as luminous intensity\n\t\t\t// but who must be converted to luminous irradiance for surface lighting calculation\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n\n#else\n\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\n#endif\n\n\t\t}\n\n\t\treturn 1.0;\n}\n\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\n\treturn RECIPROCAL_PI * diffuseColor;\n\n} // validated\n\n\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\n\t// Original approximation by Christophe Schlick '94\n\t//;float fresnel = pow( 1.0 - dotLH, 5.0 );\n\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n\n} // validated\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (34)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\t// geometry term = G(l)⋅G(v) / 4(n⋅l)(n⋅v)\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\n\treturn 1.0 / ( gl * gv );\n\n} // validated\n\n// from page 12, listing 2 of http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\tfloat a2 = pow2( alpha );\n\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\n\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\n\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n\n}\n\n\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat alpha = pow2( roughness ); // UE4's roughness\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\n\tfloat D = D_GGX( alpha, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\n\tvec4 r = roughness * c0 + c1;\n\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\n\treturn specularColor * AB.x + AB.y;\n\n} // validated\n\n\nfloat G_BlinnPhong_Implicit( /* const in float dotNL, const in float dotNV */ ) {\n\n\t// geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v)\n\treturn 0.25;\n\n}\n\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n\n}\n\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\t//float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\t//float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\n\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; + + var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\n\t// Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n\t// http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n\t// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n\tvec2 dHdxy_fwd() {\n\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n\t\treturn vec2( dBx, dBy );\n\n\t}\n\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\t\t// normalized\n\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\n\t}\n\n#endif\n"; + + var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\n\tfor ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\n\t}\n\n#endif\n"; + + var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n\n#endif\n"; + + var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; + + var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n\n"; + + var color_fragment = "#ifdef USE_COLOR\n\n\tdiffuseColor.rgb *= vColor;\n\n#endif"; + + var color_pars_fragment = "#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif\n"; + + var color_pars_vertex = "#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif"; + + var color_vertex = "#ifdef USE_COLOR\n\n\tvColor.xyz = color.xyz;\n\n#endif"; + + var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\n\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\n// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range.\n// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\n\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\n\n\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n}\n\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n\n}\n\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\n\treturn - distance * planeNormal + point;\n\n}\n\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n\n}\n\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n\n}\n"; + + var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\n#define cubeUV_textureSize (1024.0)\n\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\n\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\t// Clamp the value to the max mip level counts. hard coded to 6 mips\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\n\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\t// float powScale = exp2(roughnessLevel + mipLevel);\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\t// float scale = 1.0 / exp2(roughnessLevel + 2.0 + mipLevel);\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\t// float mipOffset = 0.75*(1.0 - 1.0/exp2(mipLevel))/exp2(roughnessLevel);\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\n\tfloat rcpPowScale = 1.0 / powScale;\n\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\n\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\n\t// round to nearest mipmap if we are not interpolating.\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\n\t// Tri linear interpolation.\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\n\tvec4 result = mix(color10, color20, t);\n\n\treturn vec4(result.rgb, 1.0);\n}\n\n#endif\n"; + + var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\n\tobjectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; + + var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n\n#endif\n"; + + var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n\n#endif\n"; + + var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n\n#endif\n"; + + var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\n\tuniform sampler2D emissiveMap;\n\n#endif\n"; + + var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; + + var encodings_pars_fragment = "// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/\n\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\n\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\n\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\n\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\n\n// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html\n\n// M matrix, for encoding\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\n\n// Inverse M matrix, for decoding\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n"; + + var envmap_fragment = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n\t\t// Transforming Normal Vectors with the Inverse Transformation\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#else\n\n\t\tvec3 reflectVec = vReflect;\n\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\n\t#endif\n\n\tenvColor = envMapTexelToLinear( envColor );\n\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n\t#endif\n\n#endif\n"; + + var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n\n#ifdef USE_ENVMAP\n\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n\n#endif\n"; + + var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\n\t#else\n\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\n\t#endif\n\n#endif\n"; + + var envmap_vertex = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\tvWorldPosition = worldPosition.xyz;\n\n\t#else\n\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#endif\n\n#endif\n"; + + var fog_fragment = "#ifdef USE_FOG\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n\t#else\n\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\n\t#endif\n\n\t#ifdef FOG_EXP2\n\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\n\t#else\n\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\n\t#endif\n\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\n#endif\n"; + + var fog_pars_fragment = "#ifdef USE_FOG\n\n\tuniform vec3 fogColor;\n\n\t#ifdef FOG_EXP2\n\n\t\tuniform float fogDensity;\n\n\t#else\n\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n\n#endif"; + + var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\n\n#endif\n"; + + var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n\n#endif"; + + var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\n\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\n\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\n\nvLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\n\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n\n#if NUM_POINT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\n#endif\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\t}\n\n#endif\n\n#if NUM_DIR_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\n#endif\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\n\t\t#endif\n\n\t}\n\n#endif\n"; + + var lights_pars = "uniform vec3 ambientLightColor;\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n\n#if NUM_DIR_LIGHTS > 0\n\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\n\t}\n\n#endif\n\n\n#if NUM_POINT_LIGHTS > 0\n\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\n\t}\n\n#endif\n\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\n\t}\n\n#endif\n\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tirradiance *= PI;\n\n\t\t#endif\n\n\t\treturn irradiance;\n\n\t}\n\n#endif\n\n\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\n\tvec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) {\n\n\t\t#include \n\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\n\t\t\t// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\n\t\t\t// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#else\n\n\t\t\t\t// force the bias high to get the last LOD level as it is the most blurred.\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\n\t\t#else\n\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\n\t\t#endif\n\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\n\t}\n\n\t// taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\n\t\t//float envMapWidth = pow( 2.0, maxMIPLevelScalar );\n\t\t//float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\n\t\t// clamp to allowable LOD ranges.\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\n\t}\n\n\tvec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\n\t\t#endif\n\n\t\t#include \n\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\n\t\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#endif\n\n\t\treturn envMapColor.rgb * envMapIntensity;\n\n\t}\n\n#endif\n"; + + var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; + + var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n\nstruct BlinnPhongMaterial {\n\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n\n};\n\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n\n}\n\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n\n#define Material_LightProbeLOD( material )\t(0)\n"; + + var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat ); // Burley clearcoat model\n\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; + + var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n\n};\n\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\n\n// Clear coat directional hemishperical reflectance (this approximation should be improved)\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n\n}\n\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n\t#ifndef STANDARD\n\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\n\t#endif\n\n}\n\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\n\t#ifndef STANDARD\n\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\n\t#endif\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\n\n// ref: http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n\n}\n"; + + var lights_template = "//\n// This is a template that can be used to light a material, it uses pluggable RenderEquations (RE)\n// for specific lighting scenarios.\n//\n// Instructions for use:\n// - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined\n// - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ???\n// - Create a material parameter that is to be passed as the third parameter to your lighting functions.\n//\n// TODO:\n// - Add area light support.\n// - Add sphere light support.\n// - Add diffuse light probe (irradiance cubemap) support.\n//\n\nGeometricContext geometry;\n\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n\nIncidentLight directLight;\n\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tPointLight pointLight;\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tSpotLight spotLight;\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tDirectionalLight directionalLight;\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if defined( RE_IndirectDiffuse )\n\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n\t#ifdef USE_LIGHTMAP\n\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tlightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage\n\n\t\t#endif\n\n\t\tirradiance += lightMapIrradiance;\n\n\t#endif\n\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t}\n\n\t#endif\n\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t// TODO, replace 8 with the real maxMIPLevel\n\t \tirradiance += getLightProbeIndirectIrradiance( /*lightProbe,*/ geometry, 8 );\n\n\t#endif\n\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n\n#endif\n\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\n\t// TODO, replace 8 with the real maxMIPLevel\n\tvec3 radiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_BlinnShininessExponent( material ), 8 );\n\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n\n#endif\n"; + + var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif"; + + var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\n\tuniform float logDepthBufFC;\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\n\t#endif\n\n#endif\n"; + + var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\n\t#endif\n\n\tuniform float logDepthBufFC;\n\n#endif"; + + var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\n\t#else\n\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n\t#endif\n\n#endif\n"; + + var map_fragment = "#ifdef USE_MAP\n\n\tvec4 texelColor = texture2D( map, vUv );\n\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n\n#endif\n"; + + var map_pars_fragment = "#ifdef USE_MAP\n\n\tuniform sampler2D map;\n\n#endif\n"; + + var map_particle_fragment = "#ifdef USE_MAP\n\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n\n#endif\n"; + + var map_particle_pars_fragment = "#ifdef USE_MAP\n\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n\n#endif\n"; + + var metalnessmap_fragment = "float metalnessFactor = metalness;\n\n#ifdef USE_METALNESSMAP\n\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n\n#endif\n"; + + var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\n\tuniform sampler2D metalnessMap;\n\n#endif"; + + var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n#endif\n"; + + var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\n\t#ifndef USE_MORPHNORMALS\n\n\tuniform float morphTargetInfluences[ 8 ];\n\n\t#else\n\n\tuniform float morphTargetInfluences[ 4 ];\n\n\t#endif\n\n#endif"; + + var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n\t#ifndef USE_MORPHNORMALS\n\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n\t#endif\n\n#endif\n"; + + var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n"; + + var normal_fragment = "#ifdef FLAT_SHADED\n\n\t// Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ...\n\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n\n#else\n\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n\n#endif\n\n#ifdef USE_NORMALMAP\n\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n"; + + var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\n\t// Per-Pixel Tangent Space Normal Mapping\n\t// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\n\t}\n\n#endif\n"; + + var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\n\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\n\nconst float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1)\nconst float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1)\n\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\n\nconst float ShiftRight8 = 1. / 256.;\n\nvec4 packDepthToRGBA( const in float v ) {\n\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\n\treturn r * PackUpscale;\n\n}\n\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\n\treturn dot( v, UnpackFactors );\n\n}\n\n// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions\n\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\n\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; + + var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\n\t// Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation.\n\tgl_FragColor.rgb *= gl_FragColor.a;\n\n#endif\n"; + + var project_vertex = "#ifdef USE_SKINNING\n\n\tvec4 mvPosition = modelViewMatrix * skinned;\n\n#else\n\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n"; + + var roughnessmap_fragment = "float roughnessFactor = roughness;\n\n#ifdef USE_ROUGHNESSMAP\n\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n\n#endif\n"; + + var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\n\tuniform sampler2D roughnessMap;\n\n#endif"; + + var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\n\t#endif\n\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\n\t}\n\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\n\t\tvec2 f = fract( uv * size + 0.5 );\n\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\n\t\treturn c;\n\n\t}\n\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\n\t\t// if ( something && something ) breaks ATI OpenGL shader compiler\n\t\t// if ( all( something, something ) ) using this instead\n\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n\t\tbool frustumTest = all( frustumTestVec );\n\n\t\tif ( frustumTest ) {\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering:\n\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\n\t\t#endif\n\n\t\t}\n\n\t\treturn 1.0;\n\n\t}\n\n\t// cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D\n\t// vector suitable for 2D texture mapping. This code uses the following layout for the\n\t// 2D texture:\n\t//\n\t// xzXZ\n\t// y Y\n\t//\n\t// Y - Positive y direction\n\t// y - Negative y direction\n\t// X - Positive x direction\n\t// x - Negative x direction\n\t// Z - Positive z direction\n\t// z - Negative z direction\n\t//\n\t// Source and test bed:\n\t// https://gist.github.com/tschw/da10c43c467ce8afd0c4\n\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\n\t\t// Number of texels to avoid at the edge of each square\n\n\t\tvec3 absV = abs( v );\n\n\t\t// Intersect unit cube\n\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\n\t\t// Apply scale to avoid seams\n\n\t\t// two texels less per square (one texel will do for NEAREST)\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\n\t\t// Unwrap\n\n\t\t// space: -1 ... 1 range for each square\n\t\t//\n\t\t// #X##\t\tdim := ( 4 , 2 )\n\t\t// # #\t\tcenter := ( 1 , 1 )\n\n\t\tvec2 planar = v.xy;\n\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\n\t\tif ( absV.z >= almostOne ) {\n\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\n\t\t} else if ( absV.x >= almostOne ) {\n\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\n\t\t} else if ( absV.y >= almostOne ) {\n\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\n\t\t}\n\n\t\t// Transform to UV space\n\n\t\t// scale := 0.5 / dim\n\t\t// translate := ( center + 0.5 ) / dim\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\n\t}\n\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\n\t\t// for point lights, the uniform @vShadowCoord is re-purposed to hold\n\t\t// the distance from the light to the world-space position of the fragment.\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\n\t\t// bd3D = base direction 3D\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t// dp = distance from light to fragment position\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering\n\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\n\t\t#endif\n\n\t}\n\n#endif\n"; + + var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\n\t#endif\n\n#endif\n"; + + var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n#endif\n"; + + var shadowmask_pars_fragment = "float getShadowMask() {\n\n\tfloat shadow = 1.0;\n\n\t#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\tDirectionalLight directionalLight;\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\tSpotLight spotLight;\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\tPointLight pointLight;\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#endif\n\n\treturn shadow;\n\n}\n"; + + var skinbase_vertex = "#ifdef USE_SKINNING\n\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif"; + + var skinning_pars_vertex = "#ifdef USE_SKINNING\n\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\n\t#ifdef BONE_TEXTURE\n\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\n\t\t\ty = dy * ( y + 0.5 );\n\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\n\t\t\treturn bone;\n\n\t\t}\n\n\t#else\n\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\n\t\t}\n\n\t#endif\n\n#endif\n"; + + var skinning_vertex = "#ifdef USE_SKINNING\n\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n\n#endif\n"; + + var skinnormal_vertex = "#ifdef USE_SKINNING\n\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\n#endif\n"; + + var specularmap_fragment = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n\n#else\n\n\tspecularStrength = 1.0;\n\n#endif"; + + var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\n\tuniform sampler2D specularMap;\n\n#endif"; + + var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n\n#endif\n"; + + var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\n\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\n\n// exposure only\nvec3 LinearToneMapping( vec3 color ) {\n\n return toneMappingExposure * color;\n\n}\n\n// source: https://www.cs.utah.edu/~reinhard/cdrom/\nvec3 ReinhardToneMapping( vec3 color ) {\n\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n\n}\n\n// source: http://filmicgames.com/archives/75\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\n // John Hable's filmic operator from Uncharted 2 video game\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n\n}\n\n// source: http://filmicgames.com/archives/75\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n\n}\n"; + + var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvarying vec2 vUv;\n\n#endif"; + + var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n\n#endif\n"; + + var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif"; + + var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvarying vec2 vUv2;\n\n#endif"; + + var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\n#endif"; + + var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvUv2 = uv2;\n\n#endif"; + + var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n\t#ifdef USE_SKINNING\n\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\n\t#else\n\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\n\t#endif\n\n#endif\n"; + + var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\n\nvarying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n\n}\n"; + + var cube_vert = "varying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\n\t#include \n\t#include \n\n}\n"; + + var depth_frag = "#if DEPTH_PACKING == 3200\n\n\tuniform float opacity;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( 1.0 );\n\n\t#if DEPTH_PACKING == 3200\n\n\t\tdiffuseColor.a = opacity;\n\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\n\t#if DEPTH_PACKING == 3200\n\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\n\t#elif DEPTH_PACKING == 3201\n\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\n\t#endif\n\n}\n"; + + var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n\n#include \n#include \n#include \n\nvoid main () {\n\n\t#include \n\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n\n}\n"; + + var distanceRGBA_vert = "varying vec4 vWorldPosition;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvWorldPosition = worldPosition;\n\n}\n"; + + var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\n\nvarying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\t// \tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n}\n"; + + var equirect_vert = "varying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\n\t#include \n\t#include \n\n}\n"; + + var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\n\nuniform float dashSize;\nuniform float totalSize;\n\nvarying float vLineDistance;\n\n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\n\t\tdiscard;\n\n\t}\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\n\toutgoingLight = diffuseColor.rgb; // simple shader\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\n\nvarying float vLineDistance;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvLineDistance = scale * lineDistance;\n\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\n\t#include \n\t#include \n\n}\n"; + + var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n\t#include \n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#ifdef USE_ENVMAP\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\n}\n"; + + var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n\nvarying vec3 vLightFront;\n\n#ifdef DOUBLE_SIDED\n\n\tvarying vec3 vLightBack;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\n\t#include \n\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\n\t#ifdef DOUBLE_SIDED\n\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\n\t#else\n\n\t\treflectedLight.directDiffuse = vLightFront;\n\n\t#endif\n\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\t#include \n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var meshlambert_vert = "#define LAMBERT\n\nvarying vec3 vLightFront;\n\n#ifdef DOUBLE_SIDED\n\n\tvarying vec3 vLightBack;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var meshphong_frag = "#define PHONG\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var meshphong_vert = "#define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\t#include \n\n}\n"; + + var meshphysical_frag = "#define PHYSICAL\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\n\nuniform float envMapIntensity; // temporary\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var meshphysical_vert = "#define PHYSICAL\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\n}\n"; + + var normal_frag = "uniform float opacity;\nvarying vec3 vNormal;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\n\t#include \n\n}\n"; + + var normal_vert = "varying vec3 vNormal;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\tvNormal = normalize( normalMatrix * normal );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\toutgoingLight = diffuseColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var points_vert = "uniform float size;\nuniform float scale;\n\n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var shadow_frag = "uniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n\n}\n"; + + var shadow_vert = "#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; + + var ShaderChunk = { + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + ambient_pars: ambient_pars, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + bumpmap_pars_fragment: bumpmap_pars_fragment, + clipping_planes_fragment: clipping_planes_fragment, + clipping_planes_pars_fragment: clipping_planes_pars_fragment, + clipping_planes_pars_vertex: clipping_planes_pars_vertex, + clipping_planes_vertex: clipping_planes_vertex, + color_fragment: color_fragment, + color_pars_fragment: color_pars_fragment, + color_pars_vertex: color_pars_vertex, + color_vertex: color_vertex, + common: common, + cube_uv_reflection_fragment: cube_uv_reflection_fragment, + defaultnormal_vertex: defaultnormal_vertex, + displacementmap_pars_vertex: displacementmap_pars_vertex, + displacementmap_vertex: displacementmap_vertex, + emissivemap_fragment: emissivemap_fragment, + emissivemap_pars_fragment: emissivemap_pars_fragment, + encodings_fragment: encodings_fragment, + encodings_pars_fragment: encodings_pars_fragment, + envmap_fragment: envmap_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_vertex: envmap_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + lightmap_fragment: lightmap_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_vertex: lights_lambert_vertex, + lights_pars: lights_pars, + lights_phong_fragment: lights_phong_fragment, + lights_phong_pars_fragment: lights_phong_pars_fragment, + lights_physical_fragment: lights_physical_fragment, + lights_physical_pars_fragment: lights_physical_pars_fragment, + lights_template: lights_template, + logdepthbuf_fragment: logdepthbuf_fragment, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, + logdepthbuf_vertex: logdepthbuf_vertex, + map_fragment: map_fragment, + map_pars_fragment: map_pars_fragment, + map_particle_fragment: map_particle_fragment, + map_particle_pars_fragment: map_particle_pars_fragment, + metalnessmap_fragment: metalnessmap_fragment, + metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_flip: normal_flip, + normal_fragment: normal_fragment, + normalmap_pars_fragment: normalmap_pars_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + roughnessmap_fragment: roughnessmap_fragment, + roughnessmap_pars_fragment: roughnessmap_pars_fragment, + shadowmap_pars_fragment: shadowmap_pars_fragment, + shadowmap_pars_vertex: shadowmap_pars_vertex, + shadowmap_vertex: shadowmap_vertex, + shadowmask_pars_fragment: shadowmask_pars_fragment, + skinbase_vertex: skinbase_vertex, + skinning_pars_vertex: skinning_pars_vertex, + skinning_vertex: skinning_vertex, + skinnormal_vertex: skinnormal_vertex, + specularmap_fragment: specularmap_fragment, + specularmap_pars_fragment: specularmap_pars_fragment, + tonemapping_fragment: tonemapping_fragment, + tonemapping_pars_fragment: tonemapping_pars_fragment, + uv_pars_fragment: uv_pars_fragment, + uv_pars_vertex: uv_pars_vertex, + uv_vertex: uv_vertex, + uv2_pars_fragment: uv2_pars_fragment, + uv2_pars_vertex: uv2_pars_vertex, + uv2_vertex: uv2_vertex, + worldpos_vertex: worldpos_vertex, + + cube_frag: cube_frag, + cube_vert: cube_vert, + depth_frag: depth_frag, + depth_vert: depth_vert, + distanceRGBA_frag: distanceRGBA_frag, + distanceRGBA_vert: distanceRGBA_vert, + equirect_frag: equirect_frag, + equirect_vert: equirect_vert, + linedashed_frag: linedashed_frag, + linedashed_vert: linedashed_vert, + meshbasic_frag: meshbasic_frag, + meshbasic_vert: meshbasic_vert, + meshlambert_frag: meshlambert_frag, + meshlambert_vert: meshlambert_vert, + meshphong_frag: meshphong_frag, + meshphong_vert: meshphong_vert, + meshphysical_frag: meshphysical_frag, + meshphysical_vert: meshphysical_vert, + normal_frag: normal_frag, + normal_vert: normal_vert, + points_frag: points_frag, + points_vert: points_vert, + shadow_frag: shadow_frag, + shadow_vert: shadow_vert + }; /** * @author mrdoob / http://mrdoob.com/ @@ -8801,8 +9014,8 @@ ] ), - vertexShader: exports.ShaderChunk[ 'meshbasic_vert' ], - fragmentShader: exports.ShaderChunk[ 'meshbasic_frag' ] + vertexShader: ShaderChunk[ 'meshbasic_vert' ], + fragmentShader: ShaderChunk[ 'meshbasic_frag' ] }, @@ -8823,8 +9036,8 @@ ] ), - vertexShader: exports.ShaderChunk[ 'meshlambert_vert' ], - fragmentShader: exports.ShaderChunk[ 'meshlambert_frag' ] + vertexShader: ShaderChunk[ 'meshlambert_vert' ], + fragmentShader: ShaderChunk[ 'meshlambert_frag' ] }, @@ -8850,8 +9063,8 @@ ] ), - vertexShader: exports.ShaderChunk[ 'meshphong_vert' ], - fragmentShader: exports.ShaderChunk[ 'meshphong_frag' ] + vertexShader: ShaderChunk[ 'meshphong_vert' ], + fragmentShader: ShaderChunk[ 'meshphong_frag' ] }, @@ -8880,8 +9093,8 @@ ] ), - vertexShader: exports.ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: exports.ShaderChunk[ 'meshphysical_frag' ] + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] }, @@ -8894,8 +9107,8 @@ ] ), - vertexShader: exports.ShaderChunk[ 'points_vert' ], - fragmentShader: exports.ShaderChunk[ 'points_frag' ] + vertexShader: ShaderChunk[ 'points_vert' ], + fragmentShader: ShaderChunk[ 'points_frag' ] }, @@ -8914,8 +9127,8 @@ ] ), - vertexShader: exports.ShaderChunk[ 'linedashed_vert' ], - fragmentShader: exports.ShaderChunk[ 'linedashed_frag' ] + vertexShader: ShaderChunk[ 'linedashed_vert' ], + fragmentShader: ShaderChunk[ 'linedashed_frag' ] }, @@ -8928,8 +9141,8 @@ ] ), - vertexShader: exports.ShaderChunk[ 'depth_vert' ], - fragmentShader: exports.ShaderChunk[ 'depth_frag' ] + vertexShader: ShaderChunk[ 'depth_vert' ], + fragmentShader: ShaderChunk[ 'depth_frag' ] }, @@ -8941,8 +9154,8 @@ }, - vertexShader: exports.ShaderChunk[ 'normal_vert' ], - fragmentShader: exports.ShaderChunk[ 'normal_frag' ] + vertexShader: ShaderChunk[ 'normal_vert' ], + fragmentShader: ShaderChunk[ 'normal_frag' ] }, @@ -8958,8 +9171,8 @@ "opacity": { value: 1.0 } }, - vertexShader: exports.ShaderChunk[ 'cube_vert' ], - fragmentShader: exports.ShaderChunk[ 'cube_frag' ] + vertexShader: ShaderChunk[ 'cube_vert' ], + fragmentShader: ShaderChunk[ 'cube_frag' ] }, @@ -8974,8 +9187,8 @@ "tFlip": { value: - 1 } }, - vertexShader: exports.ShaderChunk[ 'equirect_vert' ], - fragmentShader: exports.ShaderChunk[ 'equirect_frag' ] + vertexShader: ShaderChunk[ 'equirect_vert' ], + fragmentShader: ShaderChunk[ 'equirect_frag' ] }, @@ -8987,8 +9200,8 @@ }, - vertexShader: exports.ShaderChunk[ 'distanceRGBA_vert' ], - fragmentShader: exports.ShaderChunk[ 'distanceRGBA_frag' ] + vertexShader: ShaderChunk[ 'distanceRGBA_vert' ], + fragmentShader: ShaderChunk[ 'distanceRGBA_frag' ] } @@ -9007,8 +9220,8 @@ ] ), - vertexShader: exports.ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: exports.ShaderChunk[ 'meshphysical_frag' ] + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] }; @@ -11157,7 +11370,7 @@ function replace( match, include ) { - var replace = exports.ShaderChunk[ include ]; + var replace = ShaderChunk[ include ]; if ( replace === undefined ) { @@ -11465,10 +11678,10 @@ 'uniform vec3 cameraPosition;', ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '', - ( parameters.toneMapping !== NoToneMapping ) ? exports.ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', - ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? exports.ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below + ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', @@ -23226,8 +23439,8 @@ opacity: { value: 1.0 } } ] ), - vertexShader: exports.ShaderChunk[ 'shadow_vert' ], - fragmentShader: exports.ShaderChunk[ 'shadow_frag' ] + vertexShader: ShaderChunk[ 'shadow_vert' ], + fragmentShader: ShaderChunk[ 'shadow_frag' ] } ); this.lights = true; @@ -40249,6 +40462,7 @@ exports.WebGLRenderTargetCube = WebGLRenderTargetCube; exports.WebGLRenderTarget = WebGLRenderTarget; exports.WebGLRenderer = WebGLRenderer; + exports.ShaderChunk = ShaderChunk; exports.FogExp2 = FogExp2; exports.Fog = Fog; exports.Scene = Scene; diff --git a/build/three.min.js b/build/three.min.js index 18a48b5d4fcf64..13d3df762360e1 100644 --- a/build/three.min.js +++ b/build/three.min.js @@ -1,16 +1,14 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.THREE=t.THREE||{})}(this,function(t){"use strict";function e(){this.isEventDispatcher=!0}function n(t,e){this.isVector2=!0,this.x=t||0,this.y=e||0}function i(e,a,o,s,h,c,l,u,d,p){this.isTexture=!0,Object.defineProperty(this,"id",{value:r()}),this.uuid=t.Math.generateUUID(),this.name="",this.sourceFile="",this.image=void 0!==e?e:i.DEFAULT_IMAGE,this.mipmaps=[],this.mapping=void 0!==a?a:i.DEFAULT_MAPPING,this.wrapS=void 0!==o?o:yr,this.wrapT=void 0!==s?s:yr,this.magFilter=void 0!==h?h:Mr,this.minFilter=void 0!==c?c:Sr,this.anisotropy=void 0!==d?d:1,this.format=void 0!==l?l:zr,this.type=void 0!==u?u:Tr,this.offset=new n(0,0),this.repeat=new n(1,1),this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.encoding=void 0!==p?p:ua,this.version=0,this.onUpdate=null}function r(){return _a++}function a(){this.isMatrix4=!0,this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function o(t,e,n,i){this.isQuaternion=!0,this._x=t||0,this._y=e||0,this._z=n||0,this._w=void 0!==i?i:1}function s(t,e,n){this.isVector3=!0,this.x=t||0,this.y=e||0,this.z=n||0}function h(t,e){function n(){var t=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),e=new Uint16Array([0,1,2,0,2,3]);h=f.createBuffer(),c=f.createBuffer(),f.bindBuffer(f.ARRAY_BUFFER,h),f.bufferData(f.ARRAY_BUFFER,t,f.STATIC_DRAW),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c),f.bufferData(f.ELEMENT_ARRAY_BUFFER,e,f.STATIC_DRAW),l=r(),u={position:f.getAttribLocation(l,"position"),uv:f.getAttribLocation(l,"uv")},d={uvOffset:f.getUniformLocation(l,"uvOffset"),uvScale:f.getUniformLocation(l,"uvScale"),rotation:f.getUniformLocation(l,"rotation"),scale:f.getUniformLocation(l,"scale"),color:f.getUniformLocation(l,"color"),map:f.getUniformLocation(l,"map"),opacity:f.getUniformLocation(l,"opacity"),modelViewMatrix:f.getUniformLocation(l,"modelViewMatrix"),projectionMatrix:f.getUniformLocation(l,"projectionMatrix"),fogType:f.getUniformLocation(l,"fogType"),fogDensity:f.getUniformLocation(l,"fogDensity"),fogNear:f.getUniformLocation(l,"fogNear"),fogFar:f.getUniformLocation(l,"fogFar"),fogColor:f.getUniformLocation(l,"fogColor"),alphaTest:f.getUniformLocation(l,"alphaTest")};var n=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");n.width=8,n.height=8;var a=n.getContext("2d");a.fillStyle="white",a.fillRect(0,0,8,8),p=new i(n),p.needsUpdate=!0}function r(){var e=f.createProgram(),n=f.createShader(f.VERTEX_SHADER),i=f.createShader(f.FRAGMENT_SHADER);return f.shaderSource(n,["precision "+t.getPrecision()+" float;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float rotation;","uniform vec2 scale;","uniform vec2 uvOffset;","uniform vec2 uvScale;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","void main() {","vUV = uvOffset + uv * uvScale;","vec2 alignedPosition = position * scale;","vec2 rotatedPosition;","rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;","rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;","vec4 finalPosition;","finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );","finalPosition.xy += rotatedPosition;","finalPosition = projectionMatrix * finalPosition;","gl_Position = finalPosition;","}"].join("\n")),f.shaderSource(i,["precision "+t.getPrecision()+" float;","uniform vec3 color;","uniform sampler2D map;","uniform float opacity;","uniform int fogType;","uniform vec3 fogColor;","uniform float fogDensity;","uniform float fogNear;","uniform float fogFar;","uniform float alphaTest;","varying vec2 vUV;","void main() {","vec4 texture = texture2D( map, vUV );","if ( texture.a < alphaTest ) discard;","gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );","if ( fogType > 0 ) {","float depth = gl_FragCoord.z / gl_FragCoord.w;","float fogFactor = 0.0;","if ( fogType == 1 ) {","fogFactor = smoothstep( fogNear, fogFar, depth );","} else {","const float LOG2 = 1.442695;","fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","}","gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","}","}"].join("\n")),f.compileShader(n),f.compileShader(i),f.attachShader(e,n),f.attachShader(e,i),f.linkProgram(e),e}function a(t,e){return t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:e.id-t.id}this.isSpritePlugin=!0;var h,c,l,u,d,p,f=t.context,m=t.state,g=new s,v=new o,y=new s;this.render=function(i,r){if(0!==e.length){void 0===l&&n(),f.useProgram(l),m.initAttributes(),m.enableAttribute(u.position),m.enableAttribute(u.uv),m.disableUnusedAttributes(),m.disable(f.CULL_FACE),m.enable(f.BLEND),f.bindBuffer(f.ARRAY_BUFFER,h),f.vertexAttribPointer(u.position,2,f.FLOAT,!1,16,0),f.vertexAttribPointer(u.uv,2,f.FLOAT,!1,16,8),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c),f.uniformMatrix4fv(d.projectionMatrix,!1,r.projectionMatrix.elements),m.activeTexture(f.TEXTURE0),f.uniform1i(d.map,0);var o=0,s=0,x=i.fog;x?(f.uniform3f(d.fogColor,x.color.r,x.color.g,x.color.b),x&&x.isFog?(f.uniform1f(d.fogNear,x.near),f.uniform1f(d.fogFar,x.far),f.uniform1i(d.fogType,1),o=1,s=1):x&&x.isFogExp2&&(f.uniform1f(d.fogDensity,x.density),f.uniform1i(d.fogType,2),o=2,s=2)):(f.uniform1i(d.fogType,0),o=0,s=0);for(var b=0,_=e.length;b<_;b++){var w=e[b];w.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,w.matrixWorld),w.z=-w.modelViewMatrix.elements[14]}e.sort(a);for(var M=[],b=0,_=e.length;b<_;b++){var w=e[b],E=w.material;if(E.visible!==!1){f.uniform1f(d.alphaTest,E.alphaTest),f.uniformMatrix4fv(d.modelViewMatrix,!1,w.modelViewMatrix.elements),w.matrixWorld.decompose(g,v,y),M[0]=y.x,M[1]=y.y;var S=0;i.fog&&E.fog&&(S=s),o!==S&&(f.uniform1i(d.fogType,S),o=S),null!==E.map?(f.uniform2f(d.uvOffset,E.map.offset.x,E.map.offset.y),f.uniform2f(d.uvScale,E.map.repeat.x,E.map.repeat.y)):(f.uniform2f(d.uvOffset,0,0),f.uniform2f(d.uvScale,1,1)),f.uniform1f(d.opacity,E.opacity),f.uniform3f(d.color,E.color.r,E.color.g,E.color.b),f.uniform1f(d.rotation,E.rotation),f.uniform2fv(d.scale,M),m.setBlending(E.blending,E.blendEquation,E.blendSrc,E.blendDst),m.setDepthTest(E.depthTest),m.setDepthWrite(E.depthWrite),E.map?t.setTexture2D(E.map,0):t.setTexture2D(p,0),f.drawElements(f.TRIANGLES,6,f.UNSIGNED_SHORT,0)}}m.enable(f.CULL_FACE),t.resetGLState()}}}function c(t,e){this.isBox2=!0,this.min=void 0!==t?t:new n((+(1/0)),(+(1/0))),this.max=void 0!==e?e:new n((-(1/0)),(-(1/0)))}function l(t,e){function i(){var t=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),e=new Uint16Array([0,1,2,0,2,3]);a=m.createBuffer(),o=m.createBuffer(),m.bindBuffer(m.ARRAY_BUFFER,a),m.bufferData(m.ARRAY_BUFFER,t,m.STATIC_DRAW),m.bindBuffer(m.ELEMENT_ARRAY_BUFFER,o),m.bufferData(m.ELEMENT_ARRAY_BUFFER,e,m.STATIC_DRAW),p=m.createTexture(),f=m.createTexture(),g.bindTexture(m.TEXTURE_2D,p),m.texImage2D(m.TEXTURE_2D,0,m.RGB,16,16,0,m.RGB,m.UNSIGNED_BYTE,null),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_S,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_T,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MAG_FILTER,m.NEAREST),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MIN_FILTER,m.NEAREST),g.bindTexture(m.TEXTURE_2D,f),m.texImage2D(m.TEXTURE_2D,0,m.RGBA,16,16,0,m.RGBA,m.UNSIGNED_BYTE,null),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_S,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_T,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MAG_FILTER,m.NEAREST),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MIN_FILTER,m.NEAREST),h={vertexShader:["uniform lowp int renderType;","uniform vec3 screenPosition;","uniform vec2 scale;","uniform float rotation;","uniform sampler2D occlusionMap;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","varying float vVisibility;","void main() {","vUV = uv;","vec2 pos = position;","if ( renderType == 2 ) {","vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );","vVisibility = visibility.r / 9.0;","vVisibility *= 1.0 - visibility.g / 9.0;","vVisibility *= visibility.b / 9.0;","vVisibility *= 1.0 - visibility.a / 9.0;","pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;","pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;","}","gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );","}"].join("\n"),fragmentShader:["uniform lowp int renderType;","uniform sampler2D map;","uniform float opacity;","uniform vec3 color;","varying vec2 vUV;","varying float vVisibility;","void main() {","if ( renderType == 0 ) {","gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );","} else if ( renderType == 1 ) {","gl_FragColor = texture2D( map, vUV );","} else {","vec4 texture = texture2D( map, vUV );","texture.a *= opacity * vVisibility;","gl_FragColor = texture;","gl_FragColor.rgb *= color;","}","}"].join("\n")},l=r(h),u={vertex:m.getAttribLocation(l,"position"),uv:m.getAttribLocation(l,"uv")},d={renderType:m.getUniformLocation(l,"renderType"),map:m.getUniformLocation(l,"map"),occlusionMap:m.getUniformLocation(l,"occlusionMap"),opacity:m.getUniformLocation(l,"opacity"),color:m.getUniformLocation(l,"color"),scale:m.getUniformLocation(l,"scale"),rotation:m.getUniformLocation(l,"rotation"),screenPosition:m.getUniformLocation(l,"screenPosition")}}function r(e){var n=m.createProgram(),i=m.createShader(m.FRAGMENT_SHADER),r=m.createShader(m.VERTEX_SHADER),a="precision "+t.getPrecision()+" float;\n";return m.shaderSource(i,a+e.fragmentShader),m.shaderSource(r,a+e.vertexShader),m.compileShader(i),m.compileShader(r),m.attachShader(n,i),m.attachShader(n,r),m.linkProgram(n),n}this.isLensFlarePlugin=!0;var a,o,h,l,u,d,p,f,m=t.context,g=t.state;this.render=function(r,h,v){if(0!==e.length){var y=new s,x=v.w/v.z,b=.5*v.z,_=.5*v.w,w=16/v.w,M=new n(w*x,w),E=new s(1,1,0),S=new n(1,1),T=new c;T.min.set(0,0),T.max.set(v.z-16,v.w-16),void 0===l&&i(),m.useProgram(l),g.initAttributes(),g.enableAttribute(u.vertex),g.enableAttribute(u.uv),g.disableUnusedAttributes(),m.uniform1i(d.occlusionMap,0),m.uniform1i(d.map,1),m.bindBuffer(m.ARRAY_BUFFER,a),m.vertexAttribPointer(u.vertex,2,m.FLOAT,!1,16,0),m.vertexAttribPointer(u.uv,2,m.FLOAT,!1,16,8),m.bindBuffer(m.ELEMENT_ARRAY_BUFFER,o),g.disable(m.CULL_FACE),g.setDepthWrite(!1);for(var A=0,L=e.length;A.001&&U.scale>.001&&(E.x=U.x,E.y=U.y,E.z=U.z,w=U.size*U.scale/v.w,M.x=w*x,M.y=w,m.uniform3f(d.screenPosition,E.x,E.y,E.z),m.uniform2f(d.scale,M.x,M.y),m.uniform1f(d.rotation,U.rotation),m.uniform1f(d.opacity,U.opacity),m.uniform3f(d.color,U.color.r,U.color.g,U.color.b),g.setBlending(U.blending,U.blendEquation,U.blendSrc,U.blendDst),t.setTexture2D(U.texture,1),m.drawElements(m.TRIANGLES,6,m.UNSIGNED_SHORT,0))}}}g.enable(m.CULL_FACE),g.enable(m.DEPTH_TEST),g.setDepthWrite(!0),t.resetGLState()}}}function u(t,e,n,r,a,o,s,h,c,l){this.isCubeTexture=this.isTexture=!0,t=void 0!==t?t:[],e=void 0!==e?e:lr,i.call(this,t,e,n,r,a,o,s,h,c,l),this.flipY=!1}function d(e,n,i,r,a,o,s){function h(t,e){if(t.width>e||t.height>e){var n=e/Math.max(t.width,t.height),i=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");i.width=Math.floor(t.width*n),i.height=Math.floor(t.height*n);var r=i.getContext("2d");return r.drawImage(t,0,0,t.width,t.height,0,0,i.width,i.height),console.warn("THREE.WebGLRenderer: image is too big ("+t.width+"x"+t.height+"). Resized to "+i.width+"x"+i.height,t),i}return t}function c(e){return t.Math.isPowerOfTwo(e.width)&&t.Math.isPowerOfTwo(e.height)}function l(e){if(e instanceof HTMLImageElement||e instanceof HTMLCanvasElement){var n=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");n.width=t.Math.nearestPowerOfTwo(e.width),n.height=t.Math.nearestPowerOfTwo(e.height);var i=n.getContext("2d");return i.drawImage(e,0,0,n.width,n.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+e.width+"x"+e.height+"). Resized to "+n.width+"x"+n.height,e),n}return e}function u(t){return t.wrapS!==yr||t.wrapT!==yr||t.minFilter!==br&&t.minFilter!==Mr}function d(t){return t===br||t===_r||t===wr?e.NEAREST:e.LINEAR}function p(t){var e=t.target;e.removeEventListener("dispose",p),m(e),L.textures--}function f(t){var e=t.target;e.removeEventListener("dispose",f),g(e),L.textures--}function m(t){var n=r.get(t);if(t.image&&n.__image__webglTextureCube)e.deleteTexture(n.__image__webglTextureCube);else{if(void 0===n.__webglInit)return;e.deleteTexture(n.__webglTexture)}r.delete(t)}function g(t){var n=r.get(t),i=r.get(t.texture);if(t){if(void 0!==i.__webglTexture&&e.deleteTexture(i.__webglTexture),t.depthTexture&&t.depthTexture.dispose(),t&&t.isWebGLRenderTargetCube)for(var a=0;a<6;a++)e.deleteFramebuffer(n.__webglFramebuffer[a]),n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[a]);else e.deleteFramebuffer(n.__webglFramebuffer),n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer);r.delete(t.texture),r.delete(t)}}function v(t,n){var a=r.get(t);if(t.version>0&&a.__version!==t.version){var o=t.image;if(void 0===o)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",t);else{if(o.complete!==!1)return void _(a,t,n);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",t)}}i.activeTexture(e.TEXTURE0+n),i.bindTexture(e.TEXTURE_2D,a.__webglTexture)}function y(t,n){var s=r.get(t);if(6===t.image.length)if(t.version>0&&s.__version!==t.version){s.__image__webglTextureCube||(t.addEventListener("dispose",p),s.__image__webglTextureCube=e.createTexture(),L.textures++),i.activeTexture(e.TEXTURE0+n),i.bindTexture(e.TEXTURE_CUBE_MAP,s.__image__webglTextureCube),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,t.flipY);for(var l=t&&t.isCompressedTexture,u=t.image[0]&&t.image[0].isDataTexture,d=[],f=0;f<6;f++)l||u?d[f]=u?t.image[f].image:t.image[f]:d[f]=h(t.image[f],a.maxCubemapSize);var m=d[0],g=c(m),v=o(t.format),y=o(t.type);b(e.TEXTURE_CUBE_MAP,t,g);for(var f=0;f<6;f++)if(l)for(var x,_=d[f].mipmaps,w=0,M=_.length;w-1?i.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,w,v,x.width,x.height,0,x.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,w,v,x.width,x.height,0,v,y,x.data);else u?i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,v,d[f].width,d[f].height,0,v,y,d[f].data):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,v,v,y,d[f]);t.generateMipmaps&&g&&e.generateMipmap(e.TEXTURE_CUBE_MAP),s.__version=t.version,t.onUpdate&&t.onUpdate(t)}else i.activeTexture(e.TEXTURE0+n),i.bindTexture(e.TEXTURE_CUBE_MAP,s.__image__webglTextureCube)}function x(t,n){i.activeTexture(e.TEXTURE0+n),i.bindTexture(e.TEXTURE_CUBE_MAP,r.get(t).__webglTexture)}function b(t,i,s){var h;if(s?(e.texParameteri(t,e.TEXTURE_WRAP_S,o(i.wrapS)),e.texParameteri(t,e.TEXTURE_WRAP_T,o(i.wrapT)),e.texParameteri(t,e.TEXTURE_MAG_FILTER,o(i.magFilter)),e.texParameteri(t,e.TEXTURE_MIN_FILTER,o(i.minFilter))):(e.texParameteri(t,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(t,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),i.wrapS===yr&&i.wrapT===yr||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",i),e.texParameteri(t,e.TEXTURE_MAG_FILTER,d(i.magFilter)),e.texParameteri(t,e.TEXTURE_MIN_FILTER,d(i.minFilter)),i.minFilter!==br&&i.minFilter!==Mr&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",i)),h=n.get("EXT_texture_filter_anisotropic")){if(i.type===Ur&&null===n.get("OES_texture_float_linear"))return;if(i.type===Ir&&null===n.get("OES_texture_half_float_linear"))return;(i.anisotropy>1||r.get(i).__currentAnisotropy)&&(e.texParameterf(t,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i.anisotropy,a.getMaxAnisotropy())),r.get(i).__currentAnisotropy=i.anisotropy)}}function _(t,n,r){void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",p),t.__webglTexture=e.createTexture(),L.textures++),i.activeTexture(e.TEXTURE0+r),i.bindTexture(e.TEXTURE_2D,t.__webglTexture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,n.unpackAlignment);var s=h(n.image,a.maxTextureSize);u(n)&&c(s)===!1&&(s=l(s));var d=c(s),f=o(n.format),m=o(n.type);b(e.TEXTURE_2D,n,d);var g,v=n.mipmaps;if(n&&n.isDepthTexture){var y=e.DEPTH_COMPONENT;if(n.type===Ur){if(!R)throw new Error("Float Depth Texture only supported in WebGL2.0");y=e.DEPTH_COMPONENT32F}else R&&(y=e.DEPTH_COMPONENT16);i.texImage2D(e.TEXTURE_2D,0,y,s.width,s.height,0,f,m,null)}else if(n&&n.isDataTexture)if(v.length>0&&d){for(var x=0,_=v.length;x<_;x++)g=v[x],i.texImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,f,m,g.data);n.generateMipmaps=!1}else i.texImage2D(e.TEXTURE_2D,0,f,s.width,s.height,0,f,m,s.data);else if(n&&n.isCompressedTexture)for(var x=0,_=v.length;x<_;x++)g=v[x],n.format!==zr&&n.format!==Br?i.getCompressedTextureFormats().indexOf(f)>-1?i.compressedTexImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,g.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):i.texImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,f,m,g.data);else if(v.length>0&&d){for(var x=0,_=v.length;x<_;x++)g=v[x],i.texImage2D(e.TEXTURE_2D,x,f,f,m,g);n.generateMipmaps=!1}else i.texImage2D(e.TEXTURE_2D,0,f,f,m,s);n.generateMipmaps&&d&&e.generateMipmap(e.TEXTURE_2D),t.__version=n.version,n.onUpdate&&n.onUpdate(n)}function w(t,n,a,s){var h=o(n.texture.format),c=o(n.texture.type);i.texImage2D(s,0,h,n.width,n.height,0,h,c,null),e.bindFramebuffer(e.FRAMEBUFFER,t),e.framebufferTexture2D(e.FRAMEBUFFER,a,s,r.get(n.texture).__webglTexture,0),e.bindFramebuffer(e.FRAMEBUFFER,null)}function M(t,n){e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer&&!n.stencilBuffer?(e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t)):n.depthBuffer&&n.stencilBuffer?(e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_STENCIL,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,t)):e.renderbufferStorage(e.RENDERBUFFER,e.RGBA4,n.width,n.height),e.bindRenderbuffer(e.RENDERBUFFER,null)}function E(t,n){var i=n&&n.isWebGLRenderTargetCube;if(i)throw new Error("Depth Texture with cube render targets is not supported!");if(e.bindFramebuffer(e.FRAMEBUFFER,t),!n.depthTexture||!n.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");r.get(n.depthTexture).__webglTexture&&n.depthTexture.image.width===n.width&&n.depthTexture.image.height===n.height||(n.depthTexture.image.width=n.width,n.depthTexture.image.height=n.height,n.depthTexture.needsUpdate=!0),v(n.depthTexture,0);var a=r.get(n.depthTexture).__webglTexture;e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0)}function S(t){var n=r.get(t),i=t&&t.isWebGLRenderTargetCube;if(t.depthTexture){if(i)throw new Error("target.depthTexture not supported in Cube render targets");E(n.__webglFramebuffer,t)}else if(i){n.__webglDepthbuffer=[];for(var a=0;a<6;a++)e.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer[a]),n.__webglDepthbuffer[a]=e.createRenderbuffer(),M(n.__webglDepthbuffer[a],t)}else e.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer),n.__webglDepthbuffer=e.createRenderbuffer(),M(n.__webglDepthbuffer,t);e.bindFramebuffer(e.FRAMEBUFFER,null)}function T(t){var n=r.get(t),a=r.get(t.texture);t.addEventListener("dispose",f),a.__webglTexture=e.createTexture(),L.textures++;var o=t&&t.isWebGLRenderTargetCube,s=c(t);if(o){n.__webglFramebuffer=[];for(var h=0;h<6;h++)n.__webglFramebuffer[h]=e.createFramebuffer()}else n.__webglFramebuffer=e.createFramebuffer();if(o){i.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture),b(e.TEXTURE_CUBE_MAP,t.texture,s);for(var h=0;h<6;h++)w(n.__webglFramebuffer[h],t,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+h);t.texture.generateMipmaps&&s&&e.generateMipmap(e.TEXTURE_CUBE_MAP),i.bindTexture(e.TEXTURE_CUBE_MAP,null)}else i.bindTexture(e.TEXTURE_2D,a.__webglTexture),b(e.TEXTURE_2D,t.texture,s),w(n.__webglFramebuffer,t,e.COLOR_ATTACHMENT0,e.TEXTURE_2D),t.texture.generateMipmaps&&s&&e.generateMipmap(e.TEXTURE_2D),i.bindTexture(e.TEXTURE_2D,null);t.depthBuffer&&S(t)}function A(t){var n=t.texture;if(n.generateMipmaps&&c(t)&&n.minFilter!==br&&n.minFilter!==Mr){var a=t&&t.isWebGLRenderTargetCube?e.TEXTURE_CUBE_MAP:e.TEXTURE_2D,o=r.get(n).__webglTexture;i.bindTexture(a,o),e.generateMipmap(a),i.bindTexture(a,null)}}this.isWebGLTextures=!0;var L=s.memory,R="undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext;this.setTexture2D=v,this.setTextureCube=y,this.setTextureCubeDynamic=x,this.setupRenderTarget=T,this.updateRenderTargetMipmap=A}function p(t,e,n,i){this.isVector4=!0,this.x=t||0,this.y=e||0,this.z=n||0,this.w=void 0!==i?i:1}function f(t,e,n){function i(e,n,i){var r=new Uint8Array(4),a=t.createTexture();t.bindTexture(e,a),t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST);for(var o=0;o0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function A(t,e){this.isPlane=!0,this.normal=void 0!==t?t:new s(1,0,0),this.constant=void 0!==e?e:0}function L(t,e,n,i,r,a){this.isFrustum=!0,this.planes=[void 0!==t?t:new A,void 0!==e?e:new A,void 0!==n?n:new A,void 0!==i?i:new A,void 0!==r?r:new A,void 0!==a?a:new A]}function R(e,i,r,o){function h(t,n,i,r){var a=t.geometry,o=null,s=A,h=t.customDepthMaterial;if(i&&(s=R,h=t.customDistanceMaterial),h)o=h;else{var c=!1;n.morphTargets&&(a&&a.isBufferGeometry?c=a.morphAttributes&&a.morphAttributes.position&&a.morphAttributes.position.length>0:a&&a.isGeometry&&(c=a.morphTargets&&a.morphTargets.length>0));var l=t&&t.isSkinnedMesh&&n.skinning,u=0;c&&(u|=E),l&&(u|=S),o=s[u]}if(e.localClippingEnabled&&n.clipShadows===!0&&0!==n.clippingPlanes.length){var d=o.uuid,p=n.uuid,f=C[d];void 0===f&&(f={},C[d]=f);var m=f[p];void 0===m&&(m=o.clone(),f[p]=m),o=m}o.visible=n.visible,o.wireframe=n.wireframe;var g=n.side;return H.renderSingleSided&&g==xi&&(g=vi),H.renderReverseSided&&(g===vi?g=yi:g===yi&&(g=vi)),o.side=g,o.clipShadows=n.clipShadows,o.clippingPlanes=n.clippingPlanes,o.wireframeLinewidth=n.wireframeLinewidth,o.linewidth=n.linewidth,i&&void 0!==o.uniforms.lightPos&&o.uniforms.lightPos.value.copy(r),o}function c(t,e,n){if(t.visible!==!1){if(t.layers.test(e.layers)&&(t&&t.isMesh||t&&t.isLine||t&&t.isPoints)&&t.castShadow&&(t.frustumCulled===!1||d.intersectsObject(t)===!0)){var i=t.material;i.visible===!0&&(t.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,t.matrixWorld),w.push(t))}for(var r=t.children,a=0,o=r.length;a0,shadowMapType:e.shadowMap.type,toneMapping:e.toneMapping,physicallyCorrectLights:e.physicallyCorrectLights,premultipliedAlpha:t.premultipliedAlpha,alphaTest:t.alphaTest,doubleSided:t.side===xi,flipSided:t.side===yi,depthPacking:void 0!==t.depthPacking&&t.depthPacking};return f},this.getProgramCode=function(t,e){var n=[];if(e.shaderID?n.push(e.shaderID):(n.push(t.fragmentShader),n.push(t.vertexShader)),void 0!==t.defines)for(var i in t.defines)n.push(i),n.push(t.defines[i]);for(var r=0;r65535?Uint32Array:Uint16Array,y=new U(new v(a),1);return r(y,t.ELEMENT_ARRAY_BUFFER),i.wireframe=y,y}function c(t,e,n){if(e>n){var i=e;e=n,n=i}var r=t[e];return void 0===r?(t[e]=[n],!0):r.indexOf(n)===-1&&(r.push(n),!0)}this.isWebGLObjects=!0;var l=new K(t,e,n);this.getAttributeBuffer=s,this.getWireframeAttribute=h,this.update=i}function tt(){this.isWebGLLights=!0;var t={};this.get=function(e){if(void 0!==t[e.id])return t[e.id];var i;switch(e.type){case"DirectionalLight":i={direction:new s,color:new w,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new n};break;case"SpotLight":i={position:new s,direction:new s,color:new w,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new n};break;case"PointLight":i={position:new s,color:new w,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new n};break;case"HemisphereLight":i={direction:new s,skyColor:new w,groundColor:new w}}return t[e.id]=i,i}}function et(t,e,n){function i(){if(void 0!==a)return a;var n=e.get("EXT_texture_filter_anisotropic");return a=null!==n?t.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}function r(e){if("highp"===e){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}this.isWebGLCapabilities=!0;var a;this.getMaxAnisotropy=i,this.getMaxPrecision=r,this.precision=void 0!==n.precision?n.precision:"highp",this.logarithmicDepthBuffer=void 0!==n.logarithmicDepthBuffer&&n.logarithmicDepthBuffer,this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubemapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxAttributes=t.getParameter(t.MAX_VERTEX_ATTRIBS),this.maxVertexUniforms=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.maxVaryings=t.getParameter(t.MAX_VARYING_VECTORS),this.maxFragmentUniforms=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.vertexTextures=this.maxVertexTextures>0,this.floatFragmentTextures=!!e.get("OES_texture_float"),this.floatVertexTextures=this.vertexTextures&&this.floatFragmentTextures;var o=r(this.precision);o!==this.precision&&(console.warn("THREE.WebGLRenderer:",this.precision,"not supported, using",o,"instead."),this.precision=o),this.logarithmicDepthBuffer&&(this.logarithmicDepthBuffer=!!e.get("EXT_frag_depth"))}function nt(t){this.isWebGLExtensions=!0;var e={};this.get=function(n){if(void 0!==e[n])return e[n];var i;switch(n){case"WEBGL_depth_texture":i=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case"WEBGL_compressed_texture_etc1":i=t.getExtension("WEBGL_compressed_texture_etc1");break;default:i=t.getExtension(n)}return null===i&&console.warn("THREE.WebGLRenderer: "+n+" extension not supported."),e[n]=i,i}}function it(t,e,n){function i(t){s=t}function r(n){n.array instanceof Uint32Array&&e.get("OES_element_index_uint")?(h=t.UNSIGNED_INT,c=4):(h=t.UNSIGNED_SHORT,c=2)}function a(e,i){t.drawElements(s,i,h,e*c),n.calls++,n.vertices+=i,s===t.TRIANGLES&&(n.faces+=i/3)}function o(i,r,a){var o=e.get("ANGLE_instanced_arrays");return null===o?void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(o.drawElementsInstancedANGLE(s,a,h,r*c,i.maxInstancedCount),n.calls++,n.vertices+=a*i.maxInstancedCount,void(s===t.TRIANGLES&&(n.faces+=i.maxInstancedCount*a/3)))}this.isWebGLIndexedBufferRenderer=!0;var s,h,c;this.setMode=i,this.setIndex=r,this.render=a,this.renderInstances=o}function rt(){function t(){c.value!==i&&(c.value=i,c.needsUpdate=r>0),n.numPlanes=r}function e(t,e,i,r){var a=null!==t?t.length:0,o=null;if(0!==a){if(o=c.value,r!==!0||null===o){var l=i+4*a,u=e.matrixWorldInverse;h.getNormalMatrix(u),(null===o||o.length0?1:-1,m[v]=P.x,m[v+1]=P.y,m[v+2]=P.z,g[y]=D/c,g[y+1]=1-U/u,v+=3,y+=2,R+=1}for(U=0;U65535?Uint32Array:Uint16Array)(d),f=new Float32Array(3*u),m=new Float32Array(3*u),g=new Float32Array(2*u),v=0,y=0,x=0,b=0,_=0;c("z","y","x",-1,-1,n,e,t,a,r,0),c("z","y","x",1,-1,n,e,-t,a,r,1),c("x","z","y",1,1,t,n,e,i,a,2),c("x","z","y",1,-1,t,n,-e,i,a,3),c("x","y","z",1,-1,t,e,n,i,r,4),c("x","y","z",-1,-1,t,e,-n,i,r,5),this.setIndex(new U(p,1)),this.addAttribute("position",new U(f,3)),this.addAttribute("normal",new U(m,3)),this.addAttribute("uv",new U(g,2))}function ht(t,e){this.isRay=!0,this.origin=void 0!==t?t:new s,this.direction=void 0!==e?e:new s}function ct(t,e){this.isLine3=!0,this.start=void 0!==t?t:new s,this.end=void 0!==e?e:new s}function lt(t,e,n){this.isTriangle=!0,this.a=void 0!==t?t:new s,this.b=void 0!==e?e:new s,this.c=void 0!==n?n:new s}function ut(t){this.isMeshBasicMaterial=this.isMaterial=!0,x.call(this),this.type="MeshBasicMaterial",this.color=new w(16777215),this.map=null,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.lights=!1,this.setValues(t)}function dt(t,e){this.isMesh=!0,X.call(this),this.type="Mesh",this.geometry=void 0!==t?t:new Q,this.material=void 0!==e?e:new ut({color:16777215*Math.random()}),this.drawMode=ha,this.updateMorphTargets()}function pt(t,e,n,i){this.isPlaneBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="PlaneBufferGeometry",this.parameters={width:t,height:e,widthSegments:n,heightSegments:i};for(var r=t/2,a=e/2,o=Math.floor(n)||1,s=Math.floor(i)||1,h=o+1,c=s+1,l=t/o,u=e/s,d=new Float32Array(h*c*3),p=new Float32Array(h*c*3),f=new Float32Array(h*c*2),m=0,g=0,v=0;v65535?Uint32Array:Uint16Array)(o*s*6),v=0;v=0){var l=a[h];if(void 0!==l){var u=ee.FLOAT,d=l.array,p=l.normalized;d instanceof Float32Array?u=ee.FLOAT:d instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):d instanceof Uint16Array?u=ee.UNSIGNED_SHORT:d instanceof Int16Array?u=ee.SHORT:d instanceof Uint32Array?u=ee.UNSIGNED_INT:d instanceof Int32Array?u=ee.INT:d instanceof Int8Array?u=ee.BYTE:d instanceof Uint8Array&&(u=ee.UNSIGNED_BYTE);var f=l.itemSize,m=he.getAttributeBuffer(l);if(l&&l.isInterleavedBufferAttribute){var g=l.data,v=g.stride,y=l.offset;g&&g.isInstancedInterleavedBuffer?(ae.enableAttributeAndDivisor(c,g.meshPerAttribute,r),void 0===n.maxInstancedCount&&(n.maxInstancedCount=g.meshPerAttribute*g.count)):ae.enableAttribute(c),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(c,f,u,p,v*g.array.BYTES_PER_ELEMENT,(i*v+y)*g.array.BYTES_PER_ELEMENT)}else l&&l.isInstancedBufferAttribute?(ae.enableAttributeAndDivisor(c,l.meshPerAttribute,r),void 0===n.maxInstancedCount&&(n.maxInstancedCount=l.meshPerAttribute*l.count)):ae.enableAttribute(c),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(c,f,u,p,0,i*f*l.array.BYTES_PER_ELEMENT)}else if(void 0!==s){var x=s[h];if(void 0!==x)switch(x.length){case 2:ee.vertexAttrib2fv(c,x);break;case 3:ee.vertexAttrib3fv(c,x);break;case 4:ee.vertexAttrib4fv(c,x);break;default:ee.vertexAttrib1fv(c,x)}}}}ae.disableUnusedAttributes()}function y(t,e){return Math.abs(e[0])-Math.abs(t[0])}function x(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.material.program&&e.material.program&&t.material.program!==e.material.program?t.material.program.id-e.material.program.id:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function b(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function M(t,e,n,i,r){var a,o;n.transparent?(a=wt,o=++Mt):(a=bt,o=++_t);var s=a[o];void 0!==s?(s.id=t.id,s.object=t,s.geometry=e,s.material=n,s.z=Kt.z,s.group=r):(s={id:t.id,object:t,geometry:e,material:n,z:Kt.z,group:r},a.push(s))}function E(t){var e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),Jt.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),A(Jt)}function T(t){return Jt.center.set(0,0,0),Jt.radius=.7071067811865476,Jt.applyMatrix4(t.matrixWorld),A(Jt)}function A(t){if(!Xt.intersectsSphere(t))return!1;var e=Yt.numPlanes;if(0===e)return!0;var n=At.clippingPlanes,i=t.center,r=-t.radius,a=0;do if(n[a].distanceToPoint(i)=0&&e.numSupportedMorphTargets++}if(e.morphNormals){e.numSupportedMorphNormals=0;for(var d=0;d=0&&e.numSupportedMorphNormals++}var p=r.__webglShader.uniforms;(e&&e.isShaderMaterial||e&&e.isRawShaderMaterial)&&e.clipping!==!0||(r.numClippingPlanes=Yt.numPlanes,p.clippingPlanes=Yt.uniform),e.lights&&(r.lightsHash=$t.hash,p.ambientLightColor.value=$t.ambient,p.directionalLights.value=$t.directional,p.spotLights.value=$t.spot,p.pointLights.value=$t.point,p.hemisphereLights.value=$t.hemi,p.directionalShadowMap.value=$t.directionalShadowMap,p.directionalShadowMatrix.value=$t.directionalShadowMatrix,p.spotShadowMap.value=$t.spotShadowMap, -p.spotShadowMatrix.value=$t.spotShadowMatrix,p.pointShadowMap.value=$t.pointShadowMap,p.pointShadowMatrix.value=$t.pointShadowMatrix);var f=r.program.getUniforms(),m=t.WebGLUniforms.seqWithValue(f.seq,p);r.uniformsList=m,r.dynamicUniforms=t.WebGLUniforms.splitDynamic(m,p)}function N(t){t.side!==xi?ae.enable(ee.CULL_FACE):ae.disable(ee.CULL_FACE),ae.setFlipSided(t.side===yi),t.transparent===!0?ae.setBlending(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.premultipliedAlpha):ae.setBlending(Si),ae.setDepthFunc(t.depthFunc),ae.setDepthTest(t.depthTest),ae.setDepthWrite(t.depthWrite),ae.setColorWrite(t.colorWrite),ae.setPolygonOffset(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits)}function O(e,n,i,r){Ft=0;var a=oe.get(i);if(qt){if(Zt||e!==It){var o=e===It&&i.id===Pt;Yt.setState(i.clippingPlanes,i.clipShadows,e,a,o)}void 0!==a.numClippingPlanes&&a.numClippingPlanes!==Yt.numPlanes&&(i.needsUpdate=!0)}void 0===a.program&&(i.needsUpdate=!0),void 0!==a.lightsHash&&a.lightsHash!==$t.hash&&(i.needsUpdate=!0),i.needsUpdate&&(D(i,n,r),i.needsUpdate=!1);var s=!1,h=!1,c=!1,l=a.program,u=l.getUniforms(),d=a.__webglShader.uniforms;if(l.id!==Lt&&(ee.useProgram(l.program),Lt=l.id,s=!0,h=!0,c=!0),i.id!==Pt&&(Pt=i.id,h=!0),s||e!==It){if(u.set(ee,e,"projectionMatrix"),re.logarithmicDepthBuffer&&u.setValue(ee,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),e!==It&&(It=e,h=!0,c=!0),i&&i.isShaderMaterial||i&&i.isMeshPhongMaterial||i&&i.isMeshStandardMaterial||i.envMap){var p=u.map.cameraPosition;void 0!==p&&p.setValue(ee,Kt.setFromMatrixPosition(e.matrixWorld))}(i&&i.isMeshPhongMaterial||i&&i.isMeshLambertMaterial||i&&i.isMeshBasicMaterial||i&&i.isMeshStandardMaterial||i&&i.isShaderMaterial||i.skinning)&&u.setValue(ee,"viewMatrix",e.matrixWorldInverse),u.set(ee,At,"toneMappingExposure"),u.set(ee,At,"toneMappingWhitePoint")}if(i.skinning){u.setOptional(ee,r,"bindMatrix"),u.setOptional(ee,r,"bindMatrixInverse");var f=r.skeleton;f&&(re.floatVertexTextures&&f.useVertexTexture?(u.set(ee,f,"boneTexture"),u.set(ee,f,"boneTextureWidth"),u.set(ee,f,"boneTextureHeight")):u.setOptional(ee,f,"boneMatrices"))}h&&(i.lights&&X(d,c),n&&i.fog&&k(d,n),(i&&i.isMeshBasicMaterial||i&&i.isMeshLambertMaterial||i&&i.isMeshPhongMaterial||i&&i.isMeshStandardMaterial||i&&i.isMeshDepthMaterial)&&F(d,i),i&&i.isLineBasicMaterial?B(d,i):i&&i.isLineDashedMaterial?(B(d,i),z(d,i)):i&&i.isPointsMaterial?G(d,i):i&&i.isMeshLambertMaterial?H(d,i):i&&i.isMeshPhongMaterial?V(d,i):i&&i.isMeshPhysicalMaterial?W(d,i):i&&i.isMeshStandardMaterial?j(d,i):i&&i.isMeshDepthMaterial?i.displacementMap&&(d.displacementMap.value=i.displacementMap,d.displacementScale.value=i.displacementScale,d.displacementBias.value=i.displacementBias):i&&i.isMeshNormalMaterial&&(d.opacity.value=i.opacity),t.WebGLUniforms.upload(ee,a.uniformsList,d,At)),u.set(ee,r,"modelViewMatrix"),u.set(ee,r,"normalMatrix"),u.setValue(ee,"modelMatrix",r.matrixWorld);var m=a.dynamicUniforms;return null!==m&&(t.WebGLUniforms.evalDynamic(m,d,r,e),t.WebGLUniforms.upload(ee,m,d,At)),l}function F(t,e){t.opacity.value=e.opacity,t.diffuse.value=e.color,e.emissive&&t.emissive.value.copy(e.emissive).multiplyScalar(e.emissiveIntensity),t.map.value=e.map,t.specularMap.value=e.specularMap,t.alphaMap.value=e.alphaMap,e.aoMap&&(t.aoMap.value=e.aoMap,t.aoMapIntensity.value=e.aoMapIntensity);var n;if(e.map?n=e.map:e.specularMap?n=e.specularMap:e.displacementMap?n=e.displacementMap:e.normalMap?n=e.normalMap:e.bumpMap?n=e.bumpMap:e.roughnessMap?n=e.roughnessMap:e.metalnessMap?n=e.metalnessMap:e.alphaMap?n=e.alphaMap:e.emissiveMap&&(n=e.emissiveMap),void 0!==n){n&&n.isWebGLRenderTarget&&(n=n.texture);var i=n.offset,r=n.repeat;t.offsetRepeat.value.set(i.x,i.y,r.x,r.y)}t.envMap.value=e.envMap,t.flipEnvMap.value=e.envMap&&e.envMap.isCubeTexture?-1:1,t.reflectivity.value=e.reflectivity,t.refractionRatio.value=e.refractionRatio}function B(t,e){t.diffuse.value=e.color,t.opacity.value=e.opacity}function z(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}function G(t,e){if(t.diffuse.value=e.color,t.opacity.value=e.opacity,t.size.value=e.size*Ht,t.scale.value=.5*K.clientHeight,t.map.value=e.map,null!==e.map){var n=e.map.offset,i=e.map.repeat;t.offsetRepeat.value.set(n.x,n.y,i.x,i.y)}}function k(t,e){t.fogColor.value=e.color,e&&e.isFog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e&&e.isFogExp2&&(t.fogDensity.value=e.density)}function H(t,e){e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap)}function V(t,e){t.specular.value=e.specular,t.shininess.value=Math.max(e.shininess,1e-4),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}function j(t,e){t.roughness.value=e.roughness,t.metalness.value=e.metalness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap),e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias),e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}function W(t,e){t.clearCoat.value=e.clearCoat,t.clearCoatRoughness.value=e.clearCoatRoughness,j(t,e)}function X(t,e){t.ambientLightColor.needsUpdate=e,t.directionalLights.needsUpdate=e,t.pointLights.needsUpdate=e,t.spotLights.needsUpdate=e,t.hemisphereLights.needsUpdate=e}function Y(t){for(var e=0,n=0,i=t.length;n=re.maxTextures&&console.warn("WebGLRenderer: trying to use "+t+" texture units while this GPU supports only "+re.maxTextures),Ft+=1,t}function J(t){var e;if(t===vr)return ee.REPEAT;if(t===yr)return ee.CLAMP_TO_EDGE;if(t===xr)return ee.MIRRORED_REPEAT;if(t===br)return ee.NEAREST;if(t===_r)return ee.NEAREST_MIPMAP_NEAREST;if(t===wr)return ee.NEAREST_MIPMAP_LINEAR;if(t===Mr)return ee.LINEAR;if(t===Er)return ee.LINEAR_MIPMAP_NEAREST;if(t===Sr)return ee.LINEAR_MIPMAP_LINEAR;if(t===Tr)return ee.UNSIGNED_BYTE;if(t===Dr)return ee.UNSIGNED_SHORT_4_4_4_4;if(t===Nr)return ee.UNSIGNED_SHORT_5_5_5_1;if(t===Or)return ee.UNSIGNED_SHORT_5_6_5;if(t===Ar)return ee.BYTE;if(t===Lr)return ee.SHORT;if(t===Rr)return ee.UNSIGNED_SHORT;if(t===Cr)return ee.INT;if(t===Pr)return ee.UNSIGNED_INT;if(t===Ur)return ee.FLOAT;if(e=ie.get("OES_texture_half_float"),null!==e&&t===Ir)return e.HALF_FLOAT_OES;if(t===Fr)return ee.ALPHA;if(t===Br)return ee.RGB;if(t===zr)return ee.RGBA;if(t===Gr)return ee.LUMINANCE;if(t===kr)return ee.LUMINANCE_ALPHA;if(t===Vr)return ee.DEPTH_COMPONENT;if(t===Pi)return ee.FUNC_ADD;if(t===Ui)return ee.FUNC_SUBTRACT;if(t===Ii)return ee.FUNC_REVERSE_SUBTRACT;if(t===Oi)return ee.ZERO;if(t===Fi)return ee.ONE;if(t===Bi)return ee.SRC_COLOR;if(t===zi)return ee.ONE_MINUS_SRC_COLOR;if(t===Gi)return ee.SRC_ALPHA;if(t===ki)return ee.ONE_MINUS_SRC_ALPHA;if(t===Hi)return ee.DST_ALPHA;if(t===Vi)return ee.ONE_MINUS_DST_ALPHA;if(t===ji)return ee.DST_COLOR;if(t===Wi)return ee.ONE_MINUS_DST_COLOR;if(t===Xi)return ee.SRC_ALPHA_SATURATE;if(e=ie.get("WEBGL_compressed_texture_s3tc"),null!==e){if(t===jr)return e.COMPRESSED_RGB_S3TC_DXT1_EXT;if(t===Wr)return e.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(t===Xr)return e.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(t===Yr)return e.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e=ie.get("WEBGL_compressed_texture_pvrtc"),null!==e){if(t===qr)return e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(t===Zr)return e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(t===Jr)return e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(t===Qr)return e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e=ie.get("WEBGL_compressed_texture_etc1"),null!==e&&t===Kr)return e.COMPRESSED_RGB_ETC1_WEBGL;if(e=ie.get("EXT_blend_minmax"),null!==e){if(t===Di)return e.MIN_EXT;if(t===Ni)return e.MAX_EXT}return 0}this.isWebGLRenderer=!0,console.log("THREE.WebGLRenderer","jsnext"),e=e||{};var K=void 0!==e.canvas?e.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),ot=void 0!==e.context?e.context:null,ht=void 0!==e.alpha&&e.alpha,ct=void 0===e.depth||e.depth,lt=void 0===e.stencil||e.stencil,ft=void 0!==e.antialias&&e.antialias,vt=void 0===e.premultipliedAlpha||e.premultipliedAlpha,yt=void 0!==e.preserveDrawingBuffer&&e.preserveDrawingBuffer,xt=[],bt=[],_t=-1,wt=[],Mt=-1,Et=new Float32Array(8),St=[],Tt=[];this.domElement=K,this.context=null,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.gammaFactor=2,this.gammaInput=!1,this.gammaOutput=!1,this.physicallyCorrectLights=!1,this.toneMapping=ar,this.toneMappingExposure=1,this.toneMappingWhitePoint=1,this.maxMorphTargets=8,this.maxMorphNormals=4;var At=this,Lt=null,Rt=null,Ct=null,Pt=-1,Ut="",It=null,Dt=new p,Nt=null,Ot=new p,Ft=0,Bt=new w(0),zt=0,Gt=K.width,kt=K.height,Ht=1,Vt=new p(0,0,Gt,kt),jt=!1,Wt=new p(0,0,Gt,kt),Xt=new L,Yt=new rt,qt=!1,Zt=!1,Jt=new S,Qt=new a,Kt=new s,$t={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},te={calls:0,vertices:0,faces:0,points:0};this.info={render:te,memory:{geometries:0,textures:0},programs:null};var ee;try{var ne={alpha:ht,depth:ct,stencil:lt,antialias:ft,premultipliedAlpha:vt,preserveDrawingBuffer:yt};if(ee=ot||K.getContext("webgl",ne)||K.getContext("experimental-webgl",ne),null===ee)throw null!==K.getContext("webgl")?"Error creating WebGL context with your selected attributes.":"Error creating WebGL context.";void 0===ee.getShaderPrecisionFormat&&(ee.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}}),K.addEventListener("webglcontextlost",c,!1)}catch(t){console.error("THREE.WebGLRenderer: "+t)}var ie=new nt(ee);ie.get("WEBGL_depth_texture"),ie.get("OES_texture_float"),ie.get("OES_texture_float_linear"),ie.get("OES_texture_half_float"),ie.get("OES_texture_half_float_linear"),ie.get("OES_standard_derivatives"),ie.get("ANGLE_instanced_arrays"),ie.get("OES_element_index_uint")&&(Q.MaxIndex=4294967296);var re=new et(ee,ie,e),ae=new f(ee,ie,J),oe=new C,se=new d(ee,ie,ae,oe,re,J,this.info),he=new $(ee,oe,this.info),ce=new P(this,re),le=new tt;this.info.programs=ce.programs;var ue=new at(ee,ie,te),de=new it(ee,ie,te),pe=new gt((-1),1,1,(-1),0,1),fe=new mt,me=new dt(new pt(2,2),new ut({depthTest:!1,depthWrite:!1,fog:!1})),ge=t.ShaderLib.cube,ve=new dt(new st(5,5,5),new _({uniforms:ge.uniforms,vertexShader:ge.vertexShader,fragmentShader:ge.fragmentShader,side:yi,depthTest:!1,depthWrite:!1,fog:!1}));r(),this.context=ee,this.capabilities=re,this.extensions=ie,this.properties=oe,this.state=ae;var ye=new R(this,$t,he,re);this.shadowMap=ye;var xe=new h(this,St),be=new l(this,Tt);this.getContext=function(){return ee},this.getContextAttributes=function(){return ee.getContextAttributes()},this.forceContextLoss=function(){ie.get("WEBGL_lose_context").loseContext()},this.getMaxAnisotropy=function(){return re.getMaxAnisotropy()},this.getPrecision=function(){return re.precision},this.getPixelRatio=function(){return Ht},this.setPixelRatio=function(t){void 0!==t&&(Ht=t,this.setSize(Wt.z,Wt.w,!1))},this.getSize=function(){return{width:Gt,height:kt}},this.setSize=function(t,e,n){Gt=t,kt=e,K.width=t*Ht,K.height=e*Ht,n!==!1&&(K.style.width=t+"px",K.style.height=e+"px"),this.setViewport(0,0,t,e)},this.setViewport=function(t,e,n,i){ae.viewport(Wt.set(t,e,n,i))},this.setScissor=function(t,e,n,i){ae.scissor(Vt.set(t,e,n,i))},this.setScissorTest=function(t){ae.setScissorTest(jt=t)},this.getClearColor=function(){return Bt},this.setClearColor=function(t,e){Bt.set(t),zt=void 0!==e?e:1,i(Bt.r,Bt.g,Bt.b,zt)},this.getClearAlpha=function(){return zt},this.setClearAlpha=function(t){zt=t,i(Bt.r,Bt.g,Bt.b,zt)},this.clear=function(t,e,n){var i=0;(void 0===t||t)&&(i|=ee.COLOR_BUFFER_BIT),(void 0===e||e)&&(i|=ee.DEPTH_BUFFER_BIT),(void 0===n||n)&&(i|=ee.STENCIL_BUFFER_BIT),ee.clear(i)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.clearTarget=function(t,e,n,i){this.setRenderTarget(t),this.clear(e,n,i)},this.resetGLState=o,this.dispose=function(){wt=[],Mt=-1,bt=[],_t=-1,K.removeEventListener("webglcontextlost",c,!1)},this.renderBufferImmediate=function(t,e,n){ae.initAttributes();var i=oe.get(t);t.hasPositions&&!i.position&&(i.position=ee.createBuffer()),t.hasNormals&&!i.normal&&(i.normal=ee.createBuffer()),t.hasUvs&&!i.uv&&(i.uv=ee.createBuffer()),t.hasColors&&!i.color&&(i.color=ee.createBuffer());var r=e.getAttributes();if(t.hasPositions&&(ee.bindBuffer(ee.ARRAY_BUFFER,i.position),ee.bufferData(ee.ARRAY_BUFFER,t.positionArray,ee.DYNAMIC_DRAW),ae.enableAttribute(r.position),ee.vertexAttribPointer(r.position,3,ee.FLOAT,!1,0,0)),t.hasNormals){if(ee.bindBuffer(ee.ARRAY_BUFFER,i.normal),"MeshPhongMaterial"!==n.type&&"MeshStandardMaterial"!==n.type&&"MeshPhysicalMaterial"!==n.type&&n.shading===bi)for(var a=0,o=3*t.count;a8&&(u.length=8);for(var m=i.morphAttributes,d=0,p=u.length;d0&&b.renderInstances(i,A,R):b.render(A,R)},this.render=function(t,e,n,r){if((e&&e.isCamera)===!1)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");var a=t.fog;Ut="",Pt=-1,It=null,t.autoUpdate===!0&&t.updateMatrixWorld(),null===e.parent&&e.updateMatrixWorld(),e.matrixWorldInverse.getInverse(e.matrixWorld),Qt.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Xt.setFromMatrix(Qt),xt.length=0,_t=-1,Mt=-1,St.length=0,Tt.length=0,Zt=this.localClippingEnabled,qt=Yt.init(this.clippingPlanes,Zt,e),U(t,e),bt.length=_t+1,wt.length=Mt+1,At.sortObjects===!0&&(bt.sort(x),wt.sort(b)),qt&&Yt.beginShadows(),Y(xt),ye.render(t,e),q(xt,e),qt&&Yt.endShadows(),te.calls=0,te.vertices=0,te.faces=0,te.points=0,void 0===n&&(n=null),this.setRenderTarget(n);var o=t.background;if(null===o?i(Bt.r,Bt.g,Bt.b,zt):o&&o.isColor&&i(o.r,o.g,o.b,1),(this.autoClear||r)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil),o&&o.isCubeTexture?(fe.projectionMatrix.copy(e.projectionMatrix),fe.matrixWorld.extractRotation(e.matrixWorld),fe.matrixWorldInverse.getInverse(fe.matrixWorld),ve.material.uniforms.tCube.value=o,ve.modelViewMatrix.multiplyMatrices(fe.matrixWorldInverse,ve.matrixWorld),he.update(ve),At.renderBufferDirect(fe,null,ve.geometry,ve.material,ve,null)):o&&o.isTexture&&(me.material.map=o,he.update(me),At.renderBufferDirect(pe,null,me.geometry,me.material,me,null)),t.overrideMaterial){var s=t.overrideMaterial;I(bt,e,a,s),I(wt,e,a,s)}else ae.setBlending(Si),I(bt,e,a),I(wt,e,a);xe.render(t,e),be.render(t,e,Ot),n&&se.updateRenderTargetMipmap(n),ae.setDepthTest(!0),ae.setDepthWrite(!0),ae.setColorWrite(!0)},this.setFaceCulling=function(t,e){ae.setCullFace(t),ae.setFlipSided(e===di)},this.allocTextureUnit=Z,this.setTexture2D=function(){var t=!1;return function(e,n){e&&e.isWebGLRenderTarget&&(t||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),se.setTexture2D(e,n)}}(),this.setTexture=function(){var t=!1;return function(e,n){t||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),t=!0),se.setTexture2D(e,n)}}(),this.setTextureCube=function(){var t=!1;return function(e,n){e&&e.isWebGLRenderTargetCube&&(t||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),e&&e.isCubeTexture||Array.isArray(e.image)&&6===e.image.length?se.setTextureCube(e,n):se.setTextureCubeDynamic(e,n)}}(),this.getCurrentRenderTarget=function(){return Rt},this.setRenderTarget=function(t){Rt=t,t&&void 0===oe.get(t).__webglFramebuffer&&se.setupRenderTarget(t);var e,n=t&&t.isWebGLRenderTargetCube;if(t){var i=oe.get(t);e=n?i.__webglFramebuffer[t.activeCubeFace]:i.__webglFramebuffer,Dt.copy(t.scissor),Nt=t.scissorTest,Ot.copy(t.viewport)}else e=null,Dt.copy(Vt).multiplyScalar(Ht),Nt=jt,Ot.copy(Wt).multiplyScalar(Ht);if(Ct!==e&&(ee.bindFramebuffer(ee.FRAMEBUFFER,e),Ct=e),ae.scissor(Dt),ae.setScissorTest(Nt),ae.viewport(Ot),n){var r=oe.get(t.texture);ee.framebufferTexture2D(ee.FRAMEBUFFER,ee.COLOR_ATTACHMENT0,ee.TEXTURE_CUBE_MAP_POSITIVE_X+t.activeCubeFace,r.__webglTexture,t.activeMipMapLevel)}},this.readRenderTargetPixels=function(t,e,n,i,r,a){if((t&&t.isWebGLRenderTarget)===!1)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");var o=oe.get(t).__webglFramebuffer;if(o){var s=!1;o!==Ct&&(ee.bindFramebuffer(ee.FRAMEBUFFER,o),s=!0);try{var h=t.texture;if(h.format!==zr&&J(h.format)!==ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!(h.type===Tr||J(h.type)===ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_TYPE)||h.type===Ur&&ie.get("WEBGL_color_buffer_float")||h.type===Ir&&ie.get("EXT_color_buffer_half_float")))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");ee.checkFramebufferStatus(ee.FRAMEBUFFER)===ee.FRAMEBUFFER_COMPLETE?e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r&&ee.readPixels(e,n,i,r,J(h.format),J(h.type),a):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{s&&ee.bindFramebuffer(ee.FRAMEBUFFER,Ct)}}}}function yt(t,e){this.isFogExp2=!0,this.name="",this.color=new w(t),this.density=void 0!==e?e:25e-5}function xt(t,e,n){this.isFog=!0,this.name="",this.color=new w(t),this.near=void 0!==e?e:1,this.far=void 0!==n?n:1e3}function bt(){this.isScene=this.isObject3D=!0,X.call(this),this.type="Scene",this.background=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0}function _t(t,e,n,i,r){this.isLensFlare=!0,X.call(this),this.lensFlares=[],this.positionScreen=new s,this.customUpdateCallback=void 0,void 0!==t&&this.add(t,e,n,i,r)}function wt(t){this.isSpriteMaterial=this.isMaterial=!0,x.call(this),this.type="SpriteMaterial",this.color=new w(16777215),this.map=null,this.rotation=0,this.fog=!1,this.lights=!1,this.setValues(t)}function Mt(t){this.isSprite=!0,X.call(this),this.type="Sprite",this.material=void 0!==t?t:new wt}function Et(){this.isLOD=!0,X.call(this),this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function St(t,e,n,r,a,o,s,h,c,l,u,d){this.isDataTexture=this.isTexture=!0,i.call(this,null,o,s,h,c,l,r,a,u,d),this.image={data:t,width:e,height:n},this.magFilter=void 0!==c?c:br,this.minFilter=void 0!==l?l:br,this.flipY=!1,this.generateMipmaps=!1}function Tt(e,n,i){if(this.isSkeleton=!0,this.useVertexTexture=void 0===i||i,this.identityMatrix=new a,e=e||[],this.bones=e.slice(0),this.useVertexTexture){var r=Math.sqrt(4*this.bones.length);r=t.Math.nextPowerOfTwo(Math.ceil(r)),r=Math.max(r,4),this.boneTextureWidth=r,this.boneTextureHeight=r,this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new St(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,zr,Ur)}else this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===n)this.calculateInverses();else if(this.bones.length===n.length)this.boneInverses=n.slice(0);else{console.warn("THREE.Skeleton bonInverses is the wrong length."),this.boneInverses=[];for(var o=0,s=this.bones.length;o=t.HAVE_CURRENT_DATA&&(u.needsUpdate=!0)}this.isVideoTexture=this.isTexture=!0,i.call(this,t,e,n,r,a,o,s,h,c),this.generateMipmaps=!1;var u=this;l()}function Ot(t,e,n,r,a,o,s,h,c,l,u,d){this.isCompressedTexture=this.isTexture=!0,i.call(this,null,o,s,h,c,l,r,a,u,d),this.image={width:e,height:n},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}function Ft(t,e,n,r,a,o,s,h,c){this.isCanvasTexture=this.isTexture=!0,i.call(this,t,e,n,r,a,o,s,h,c),this.needsUpdate=!0}function Bt(t,e,n,r,a,o,s,h,c){this.isDepthTexture=this.isTexture=!0,i.call(this,null,r,a,o,s,h,Vr,n,c),this.image={width:t,height:e},this.type=void 0!==n?n:Rr,this.magFilter=void 0!==s?s:br,this.minFilter=void 0!==h?h:br,this.flipY=!1,this.generateMipmaps=!1}function zt(){this.isShadowMaterial=this.isShaderMaterial=this.isMaterial=!0,_.call(this,{uniforms:t.UniformsUtils.merge([t.UniformsLib.lights,{opacity:{value:1}}]),vertexShader:t.ShaderChunk.shadow_vert,fragmentShader:t.ShaderChunk.shadow_frag}),this.lights=!0,this.transparent=!0,Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(t){this.uniforms.opacity.value=t}}})}function Gt(t){this.isRawShaderMaterial=this.isShaderMaterial=this.isMaterial=!0,_.call(this,t),this.type="RawShaderMaterial"}function kt(e){this.isMultiMaterial=!0,this.uuid=t.Math.generateUUID(),this.type="MultiMaterial",this.materials=e instanceof Array?e:[],this.visible=!0}function Ht(t){this.isMeshStandardMaterial=this.isMaterial=!0,x.call(this),this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new w(16777215),this.roughness=.5,this.metalness=.5,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new n(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Vt(t){this.isMeshPhysicalMaterial=this.isMeshStandardMaterial=this.isMaterial=!0,Ht.call(this),this.defines={PHYSICAL:""},this.type="MeshPhysicalMaterial",this.reflectivity=.5,this.clearCoat=0,this.clearCoatRoughness=0,this.setValues(t)}function jt(t){this.isMeshPhongMaterial=this.isMaterial=!0,x.call(this),this.type="MeshPhongMaterial",this.color=new w(16777215),this.specular=new w(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new n(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Wt(t){this.isMeshNormalMaterial=this.isMaterial=!0,x.call(this,t),this.type="MeshNormalMaterial",this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.morphTargets=!1,this.setValues(t)}function Xt(t){this.isMeshLambertMaterial=this.isMaterial=!0,x.call(this),this.type="MeshLambertMaterial",this.color=new w(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Yt(t){this.isLineDashedMaterial=this.isMaterial=!0,x.call(this),this.type="LineDashedMaterial",this.color=new w(16777215),this.linewidth=1,this.scale=1,this.dashSize=3,this.gapSize=1,this.lights=!1,this.setValues(t)}function qt(t,e,n){this.isLoadingManager=!0;var i=this,r=!1,a=0,o=0;this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=n,this.itemStart=function(t){o++,r===!1&&void 0!==i.onStart&&i.onStart(t,a,o),r=!0},this.itemEnd=function(t){a++,void 0!==i.onProgress&&i.onProgress(t,a,o),a===o&&(r=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(t){void 0!==i.onError&&i.onError(t)}}function Zt(e){this.isXHRLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function Jt(e){this.isCompressedTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Qt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Kt(e){ -this.isImageLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function $t(e){this.isCubeTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function te(e){this.isTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function ee(t,e){this.isLight=!0,X.call(this),this.type="Light",this.color=new w(t),this.intensity=void 0!==e?e:1,this.receiveShadow=void 0}function ne(t,e,n){this.isHemisphereLight=!0,ee.call(this,t,n),this.type="HemisphereLight",this.castShadow=void 0,this.position.copy(X.DefaultUp),this.updateMatrix(),this.groundColor=new w(e)}function ie(t){this.isLightShadow=!0,this.camera=t,this.bias=0,this.radius=1,this.mapSize=new n(512,512),this.map=null,this.matrix=new a}function re(){this.isSpotLightShadow=!0,ie.call(this,new mt(50,1,.5,500))}function ae(t,e,n,i,r,a){this.isSpotLight=!0,ee.call(this,t,e),this.type="SpotLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(t){this.intensity=t/Math.PI}}),this.distance=void 0!==n?n:0,this.angle=void 0!==i?i:Math.PI/3,this.penumbra=void 0!==r?r:0,this.decay=void 0!==a?a:1,this.shadow=new re}function oe(t,e,n,i){this.isPointLight=!0,ee.call(this,t,e),this.type="PointLight",Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(t){this.intensity=t/(4*Math.PI)}}),this.distance=void 0!==n?n:0,this.decay=void 0!==i?i:1,this.shadow=new ie(new mt(90,1,.5,500))}function se(t){this.isDirectionalLightShadow=!0,ie.call(this,new gt((-5),5,5,(-5),.5,500))}function he(t,e){this.isDirectionalLight=!0,ee.call(this,t,e),this.type="DirectionalLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,this.shadow=new se}function ce(t,e){this.isAmbientLight=!0,ee.call(this,t,e),this.type="AmbientLight",this.castShadow=void 0}function le(t,e,n,i){this.isInterpolant=!0,this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==i?i:new e.constructor(n),this.sampleValues=e,this.valueSize=n}function ue(t,e,n,i){this.isCubicInterpolant=!0,le.call(this,t,e,n,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0}function de(t,e,n,i){this.isLinearInterpolant=!0,le.call(this,t,e,n,i)}function pe(t,e,n,i){this.isDiscreteInterpolant=!0,le.call(this,t,e,n,i)}function fe(e,n,i,r){if(this.isKeyframeTrack=!0,void 0===e)throw new Error("track name is undefined");if(void 0===n||0===n.length)throw new Error("no keyframes in track named "+e);this.name=e,this.times=t.AnimationUtils.convertArray(n,this.TimeBufferType),this.values=t.AnimationUtils.convertArray(i,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation),this.validate(),this.optimize()}function me(t,e,n,i){this.isVectorKeyframeTrack=!0,fe.call(this,t,e,n,i)}function ge(t,e,n,i){this.isQuaternionLinearInterpolant=!0,le.call(this,t,e,n,i)}function ve(t,e,n,i){this.isQuaternionKeyframeTrack=!0,fe.call(this,t,e,n,i)}function ye(t,e,n,i){this.isNumberKeyframeTrack=!0,fe.call(this,t,e,n,i)}function xe(t,e,n,i){this.isStringKeyframeTrack=!0,fe.call(this,t,e,n,i)}function be(t,e,n){this.isBooleanKeyframeTrack=!0,fe.call(this,t,e,n)}function _e(t,e,n,i){this.isColorKeyframeTrack=!0,fe.call(this,t,e,n,i)}function we(t,e,n,i){fe.apply(this,arguments)}function Me(e,n,i){this.isAnimationClip=!0,this.name=e,this.tracks=i,this.duration=void 0!==n?n:-1,this.uuid=t.Math.generateUUID(),this.duration<0&&this.resetDuration(),this.trim(),this.optimize()}function Ee(e){this.isMaterialLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this.textures={}}function Se(e){this.isBufferGeometryLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function Te(){this.isLoader=!0,this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){}}function Ae(e){this.isJSONLoader=!0,"boolean"==typeof e&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),e=void 0),this.manager=void 0!==e?e:t.DefaultLoadingManager,this.withCredentials=!1}function Le(e){this.isObjectLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this.texturePath=""}function Re(){this.isCurve=!0}function Ce(t,e){this.isLineCurve=this.isCurve=!0,this.v1=t,this.v2=e}function Pe(){this.isCurvePath=!0,this.curves=[],this.autoClose=!1}function Ue(t,e,n,i,r,a,o,s){this.isEllipseCurve=this.isCurve=!0,this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s||0}function Ie(t){this.isSplineCurve=this.isCurve=!0,this.points=void 0==t?[]:t}function De(t,e,n,i){this.isCubicBezierCurve=this.isCurve=!0,this.v0=t,this.v1=e,this.v2=n,this.v3=i}function Ne(t,e,n){this.isQuadraticBezierCurve=this.isCurve=!0,this.v0=t,this.v1=e,this.v2=n}function Oe(t,e,i,r,a,o){function h(t,e,n){return P.vertices.push(new s(t,e,n))-1}this.isTubeGeometry=this.isGeometry=!0,q.call(this),this.type="TubeGeometry",this.parameters={path:t,segments:e,radius:i,radialSegments:r,closed:a,taper:o},e=e||64,i=i||1,r=r||8,a=a||!1,o=o||Oe.NoTaper;var c,l,u,d,p,f,m,g,v,y,x,b,_,w,M,E,S,T,A,L,R,C=[],P=this,U=e+1,I=new s,D=new Oe.FrenetFrames(t,e,a),N=D.tangents,O=D.normals,F=D.binormals;for(this.tangents=N,this.normals=O,this.binormals=F,y=0;ythis.points.length-2?this.points.length-1:i+1,d[3]=i>this.points.length-3?this.points.length-1:i+2,h=this.points[d[0]],c=this.points[d[1]],l=this.points[d[2]],u=this.points[d[3]],a=r*r,o=r*a,p.x=e(h.x,c.x,l.x,u.x,r,a,o),p.y=e(h.y,c.y,l.y,u.y,r,a,o),p.z=e(h.z,c.z,l.z,u.z,r,a,o),p},this.getControlPointsArray=function(){var t,e,n=this.points.length,i=[];for(t=0;t0)&&E.push(T,A,R),(g!==n-1||h65535?z:F)(E,1)),this.addAttribute("position",l),this.addAttribute("normal",u),this.addAttribute("uv",d),this.boundingSphere=new S(new s,t)}function En(t,e){this.isPointLightHelper=this.isMesh=!0,this.light=t,this.light.updateMatrixWorld();var n=new Mn(e,4,2),i=new ut({wireframe:!0,fog:!1});i.color.copy(this.light.color).multiplyScalar(this.light.intensity),dt.call(this,n,i),this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1}function Sn(t,e,n,i,r,a,o){this.isSphereGeometry=this.isGeometry=!0,q.call(this),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:n,phiStart:i,phiLength:r,thetaStart:a,thetaLength:o},this.fromBufferGeometry(new Mn(t,e,n,i,r,a,o))}function Tn(t,e){this.isHemisphereLightHelper=this.isObject3D=!0,X.call(this),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.colors=[new w,new w];var n=new Sn(e,4,2);n.rotateX(-Math.PI/2);for(var i=0,r=8;i0&&m++,e>0&&m++);var g=l(),v=u(),y=new U(new(v>65535?Uint32Array:Uint16Array)(v),1),x=new U(new Float32Array(3*g),3),b=new U(new Float32Array(3*g),3),_=new U(new Float32Array(2*g),2),w=0,M=0,E=[],S=i/2,T=0;d(),o===!1&&(t>0&&p(!0),e>0&&p(!1)),this.setIndex(y),this.addAttribute("position",x),this.addAttribute("normal",b),this.addAttribute("uv",_)}function Fn(t){this.isAxisHelper=this.isLineSegments=!0,t=t||1;var e=new Float32Array([0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t]),n=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]),i=new Q;i.addAttribute("position",new U(e,3)),i.addAttribute("color",new U(n,3));var r=new Rt({vertexColors:Ei});Pt.call(this,i,r)}function Bn(t,e,i){this.isParametricGeometry=this.isGeometry=!0,q.call(this),this.type="ParametricGeometry",this.parameters={func:t,slices:e,stacks:i};var r,a,o,s,h,c=this.vertices,l=this.faces,u=this.faceVertexUvs[0],d=e+1;for(r=0;r<=i;r++)for(h=r/i,a=0;a<=e;a++)s=a/e,o=t(s,h),c.push(o);var p,f,m,g,v,y,x,b;for(r=0;r.9&&L<.1&&(M<.2&&(w[0].x+=1),E<.2&&(w[1].x+=1),T<.2&&(w[2].x+=1))}for(var p=0,f=this.vertices.length;p65535?Uint32Array:Uint16Array)(d),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=new s,b=new s,_=new n,w=new s,M=new s,E=new s,S=new s,T=new s;for(c=0;c<=i;++c){var A=c/i*a*Math.PI*2;for(h(A,a,o,t,w),h(A+.01,a,o,t,M),S.subVectors(M,w),T.addVectors(M,w),E.crossVectors(S,T),T.crossVectors(E,S),E.normalize(),T.normalize(),l=0;l<=r;++l){var L=l/r*Math.PI*2,R=-e*Math.cos(L),C=e*Math.sin(L);x.x=w.x+(R*T.x+C*E.x),x.y=w.y+(R*T.y+C*E.y),x.z=w.z+(R*T.z+C*E.z),f.setXYZ(v,x.x,x.y,x.z),b.subVectors(x,w).normalize(),m.setXYZ(v,b.x,b.y,b.z),_.x=c/i,_.y=l/r,g.setXY(v,_.x,_.y),v++}}for(l=1;l<=i;l++)for(c=1;c<=r;c++){var P=(r+1)*(l-1)+(c-1),I=(r+1)*l+(c-1),D=(r+1)*l+c,N=(r+1)*(l-1)+c;p.setX(y,P),y++,p.setX(y,I),y++,p.setX(y,N),y++,p.setX(y,I),y++,p.setX(y,D),y++,p.setX(y,N),y++}this.setIndex(p),this.addAttribute("position",f),this.addAttribute("normal",m),this.addAttribute("uv",g)}function Wn(t,e,n,i,r,a,o){this.isTorusKnotGeometry=this.isGeometry=!0,q.call(this),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,tubularSegments:n,radialSegments:i,p:r,q:a},void 0!==o&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead."),this.fromBufferGeometry(new jn(t,e,n,i,r,a)),this.mergeVertices()}function Xn(t,e,n,i,r){this.isTorusBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="TorusBufferGeometry",this.parameters={radius:t,tube:e,radialSegments:n,tubularSegments:i,arc:r},t=t||100,e=e||40,n=Math.floor(n)||8,i=Math.floor(i)||6,r=r||2*Math.PI;var a,o,h=(n+1)*(i+1),c=n*i*2*3,l=new(c>65535?Uint32Array:Uint16Array)(c),u=new Float32Array(3*h),d=new Float32Array(3*h),p=new Float32Array(2*h),f=0,m=0,g=0,v=new s,y=new s,x=new s;for(a=0;a<=n;a++)for(o=0;o<=i;o++){var b=o/i*r,_=a/n*Math.PI*2;y.x=(t+e*Math.cos(_))*Math.cos(b),y.y=(t+e*Math.cos(_))*Math.sin(b),y.z=e*Math.sin(_),u[f]=y.x,u[f+1]=y.y,u[f+2]=y.z,v.x=t*Math.cos(b),v.y=t*Math.sin(b),x.subVectors(y,v).normalize(),d[f]=x.x,d[f+1]=x.y,d[f+2]=x.z,p[m]=o/i,p[m+1]=a/n,f+=3,m+=2}for(a=1;a<=n;a++)for(o=1;o<=i;o++){var w=(i+1)*a+o-1,M=(i+1)*(a-1)+o-1,E=(i+1)*(a-1)+o,S=(i+1)*a+o;l[g]=w,l[g+1]=M,l[g+2]=S,l[g+3]=M,l[g+4]=E,l[g+5]=S, -g+=6}this.setIndex(new U(l,1)),this.addAttribute("position",new U(u,3)),this.addAttribute("normal",new U(d,3)),this.addAttribute("uv",new U(p,2))}function Yn(t,e,n,i,r){this.isTorusGeometry=this.isGeometry=!0,q.call(this),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:n,tubularSegments:i,arc:r},this.fromBufferGeometry(new Xn(t,e,n,i,r))}function qn(t,e){this.isTextGeometry=this.isExtrudeGeometry=this.isGeometry=!0,e=e||{};var n=e.font;if((n&&n.isFont)===!1)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new q;var i=n.generateShapes(t,e.size,e.curveSegments);e.amount=void 0!==e.height?e.height:50,void 0===e.bevelThickness&&(e.bevelThickness=10),void 0===e.bevelSize&&(e.bevelSize=8),void 0===e.bevelEnabled&&(e.bevelEnabled=!1),Fe.call(this,i,e),this.type="TextGeometry"}function Zn(t,e,i,r,a,o){this.isRingBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="RingBufferGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:i,phiSegments:r,thetaStart:a,thetaLength:o},t=t||20,e=e||50,a=void 0!==a?a:0,o=void 0!==o?o:2*Math.PI,i=void 0!==i?Math.max(3,i):8,r=void 0!==r?Math.max(1,r):1;var h,c,l,u=(i+1)*(r+1),d=i*r*2*3,p=new U(new(d>65535?Uint32Array:Uint16Array)(d),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=t,b=(e-t)/r,_=new s,w=new n;for(c=0;c<=r;c++){for(l=0;l<=i;l++)h=a+l/i*o,_.x=x*Math.cos(h),_.y=x*Math.sin(h),f.setXYZ(v,_.x,_.y,_.z),m.setXYZ(v,0,0,1),w.x=(_.x/e+1)/2,w.y=(_.y/e+1)/2,g.setXY(v,w.x,w.y),v++;x+=b}for(c=0;c65535?Uint32Array:Uint16Array)(u),1),p=new U(new Float32Array(3*l),3),f=new U(new Float32Array(2*l),2),m=0,g=0,v=(1/(e.length-1),1/i),y=new s,x=new n;for(h=0;h<=i;h++){var b=r+h*v*a,_=Math.sin(b),w=Math.cos(b);for(c=0;c<=e.length-1;c++)y.x=e[c].x*_,y.y=e[c].y,y.z=e[c].x*w,p.setXYZ(m,y.x,y.y,y.z),x.x=h/i,x.y=c/(e.length-1),f.setXY(m,x.x,x.y),m++}for(h=0;h>=4,n[r]=e[19===r?3&t|8:t]);return n.join("")}}(),clamp:function(t,e,n){return Math.max(e,Math.min(n,t))},euclideanModulo:function(t,e){return(t%e+e)%e},mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*(3-2*t))},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*t*(t*(6*t-15)+10))},random16:function(){return console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead."),Math.random()},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},degToRad:function(e){return e*t.Math.DEG2RAD},radToDeg:function(e){return e*t.Math.RAD2DEG},isPowerOfTwo:function(t){return 0===(t&t-1)&&0!==t},nearestPowerOfTwo:function(t){return Math.pow(2,Math.round(Math.log(t)/Math.LN2))},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}},n.prototype={constructor:n,get width(){return this.x},set width(t){this.x=t},get height(){return this.y},set height(t){this.y=t},set:function(t,e){return this.x=t,this.y=e,this},setScalar:function(t){return this.x=t,this.y=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(t){return this.x=t.x,this.y=t.y,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)},addScalar:function(t){return this.x+=t,this.y+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)},subScalar:function(t){return this.x-=t,this.y-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t):(this.x=0,this.y=0),this},divide:function(t){return this.x/=t.x,this.y/=t.y,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this},clampScalar:function(){var t,e;return function(i,r){return void 0===t&&(t=new n,e=new n),t.set(i,i),e.set(r,r),this.clamp(t,e)}}(),clampLength:function(t,e){var n=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,n))/n)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(t){return this.x*t.x+this.y*t.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var t=Math.atan2(this.y,this.x);return t<0&&(t+=2*Math.PI),t},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,n=this.y-t.y;return e*e+n*n},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this},lerpVectors:function(t,e,n){return this.subVectors(e,t).multiplyScalar(n).add(t)},equals:function(t){return t.x===this.x&&t.y===this.y},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t},fromAttribute:function(t,e,n){return void 0===n&&(n=0),e=e*t.itemSize+n,this.x=t.array[e],this.y=t.array[e+1],this},rotateAround:function(t,e){var n=Math.cos(e),i=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*n-a*i+t.x,this.y=r*i+a*n+t.y,this}},i.DEFAULT_IMAGE=void 0,i.DEFAULT_MAPPING=cr,i.prototype={constructor:i,set needsUpdate(t){t===!0&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.encoding=t.encoding,this},toJSON:function(e){function n(t){var e;return void 0!==t.toDataURL?e=t:(e=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0,t.width,t.height)),e.width>2048||e.height>2048?e.toDataURL("image/jpeg",.6):e.toDataURL("image/png")}if(void 0!==e.textures[this.uuid])return e.textures[this.uuid];var i={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var r=this.image;void 0===r.uuid&&(r.uuid=t.Math.generateUUID()),void 0===e.images[r.uuid]&&(e.images[r.uuid]={uuid:r.uuid,url:n(r)}),i.image=r.uuid}return e.textures[this.uuid]=i,i},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(t){if(this.mapping===cr){if(t.multiply(this.repeat),t.add(this.offset),t.x<0||t.x>1)switch(this.wrapS){case vr:t.x=t.x-Math.floor(t.x);break;case yr:t.x=t.x<0?0:1;break;case xr:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case vr:t.y=t.y-Math.floor(t.y);break;case yr:t.y=t.y<0?0:1;break;case xr:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}this.flipY&&(t.y=1-t.y)}}},Object.assign(i.prototype,e.prototype);var _a=0;a.prototype={constructor:a,set:function(t,e,n,i,r,a,o,s,h,c,l,u,d,p,f,m){var g=this.elements;return g[0]=t,g[4]=e,g[8]=n,g[12]=i,g[1]=r,g[5]=a,g[9]=o,g[13]=s,g[2]=h,g[6]=c,g[10]=l,g[14]=u,g[3]=d,g[7]=p,g[11]=f,g[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},clone:function(){return(new a).fromArray(this.elements)},copy:function(t){return this.elements.set(t.elements),this},copyPosition:function(t){var e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this},extractBasis:function(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this},makeBasis:function(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this},extractRotation:function(){var t;return function(e){void 0===t&&(t=new s);var n=this.elements,i=e.elements,r=1/t.setFromMatrixColumn(e,0).length(),a=1/t.setFromMatrixColumn(e,1).length(),o=1/t.setFromMatrixColumn(e,2).length();return n[0]=i[0]*r,n[1]=i[1]*r,n[2]=i[2]*r,n[4]=i[4]*a,n[5]=i[5]*a,n[6]=i[6]*a,n[8]=i[8]*o,n[9]=i[9]*o,n[10]=i[10]*o,this}}(),makeRotationFromEuler:function(t){(t&&t.isEuler)===!1&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var e=this.elements,n=t.x,i=t.y,r=t.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(i),h=Math.sin(i),c=Math.cos(r),l=Math.sin(r);if("XYZ"===t.order){var u=a*c,d=a*l,p=o*c,f=o*l;e[0]=s*c,e[4]=-s*l,e[8]=h,e[1]=d+p*h,e[5]=u-f*h,e[9]=-o*s,e[2]=f-u*h,e[6]=p+d*h,e[10]=a*s}else if("YXZ"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m+y*o,e[4]=v*o-g,e[8]=a*h,e[1]=a*l,e[5]=a*c,e[9]=-o,e[2]=g*o-v,e[6]=y+m*o,e[10]=a*s}else if("ZXY"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m-y*o,e[4]=-a*l,e[8]=v+g*o,e[1]=g+v*o,e[5]=a*c,e[9]=y-m*o,e[2]=-a*h,e[6]=o,e[10]=a*s}else if("ZYX"===t.order){var u=a*c,d=a*l,p=o*c,f=o*l;e[0]=s*c,e[4]=p*h-d,e[8]=u*h+f,e[1]=s*l,e[5]=f*h+u,e[9]=d*h-p,e[2]=-h,e[6]=o*s,e[10]=a*s}else if("YZX"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=w-x*l,e[8]=_*l+b,e[1]=l,e[5]=a*c,e[9]=-o*c,e[2]=-h*c,e[6]=b*l+_,e[10]=x-w*l}else if("XZY"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=-l,e[8]=h*c,e[1]=x*l+w,e[5]=a*c,e[9]=b*l-_,e[2]=_*l-b,e[6]=o*c,e[10]=w*l+x}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},makeRotationFromQuaternion:function(t){var e=this.elements,n=t.x,i=t.y,r=t.z,a=t.w,o=n+n,s=i+i,h=r+r,c=n*o,l=n*s,u=n*h,d=i*s,p=i*h,f=r*h,m=a*o,g=a*s,v=a*h;return e[0]=1-(d+f),e[4]=l-v,e[8]=u+g,e[1]=l+v,e[5]=1-(c+f),e[9]=p-m,e[2]=u-g,e[6]=p+m,e[10]=1-(c+d),e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},lookAt:function(){var t,e,n;return function(i,r,a){void 0===t&&(t=new s,e=new s,n=new s);var o=this.elements;return n.subVectors(i,r).normalize(),0===n.lengthSq()&&(n.z=1),t.crossVectors(a,n).normalize(),0===t.lengthSq()&&(n.z+=1e-4,t.crossVectors(a,n).normalize()),e.crossVectors(n,t),o[0]=t.x,o[4]=e.x,o[8]=n.x,o[1]=t.y,o[5]=e.y,o[9]=n.y,o[2]=t.z,o[6]=e.z,o[10]=n.z,this}}(),multiply:function(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)},premultiply:function(t){return this.multiplyMatrices(t,this)},multiplyMatrices:function(t,e){var n=t.elements,i=e.elements,r=this.elements,a=n[0],o=n[4],s=n[8],h=n[12],c=n[1],l=n[5],u=n[9],d=n[13],p=n[2],f=n[6],m=n[10],g=n[14],v=n[3],y=n[7],x=n[11],b=n[15],_=i[0],w=i[4],M=i[8],E=i[12],S=i[1],T=i[5],A=i[9],L=i[13],R=i[2],C=i[6],P=i[10],U=i[14],I=i[3],D=i[7],N=i[11],O=i[15];return r[0]=a*_+o*S+s*R+h*I,r[4]=a*w+o*T+s*C+h*D,r[8]=a*M+o*A+s*P+h*N,r[12]=a*E+o*L+s*U+h*O,r[1]=c*_+l*S+u*R+d*I,r[5]=c*w+l*T+u*C+d*D,r[9]=c*M+l*A+u*P+d*N,r[13]=c*E+l*L+u*U+d*O,r[2]=p*_+f*S+m*R+g*I,r[6]=p*w+f*T+m*C+g*D,r[10]=p*M+f*A+m*P+g*N,r[14]=p*E+f*L+m*U+g*O,r[3]=v*_+y*S+x*R+b*I,r[7]=v*w+y*T+x*C+b*D,r[11]=v*M+y*A+x*P+b*N,r[15]=v*E+y*L+x*U+b*O,this},multiplyToArray:function(t,e,n){var i=this.elements;return this.multiplyMatrices(t,e),n[0]=i[0],n[1]=i[1],n[2]=i[2],n[3]=i[3],n[4]=i[4],n[5]=i[5],n[6]=i[6],n[7]=i[7],n[8]=i[8],n[9]=i[9],n[10]=i[10],n[11]=i[11],n[12]=i[12],n[13]=i[13],n[14]=i[14],n[15]=i[15],this},multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this},applyToVector3Array:function(){var t;return function(e,n,i){void 0===t&&(t=new s),void 0===n&&(n=0),void 0===i&&(i=e.length);for(var r=0,a=n;r0?(e=.5/Math.sqrt(d+1),this._w=.25/e,this._x=(l-h)*e,this._y=(a-c)*e,this._z=(o-r)*e):i>s&&i>u?(e=2*Math.sqrt(1+i-s-u),this._w=(l-h)/e,this._x=.25*e,this._y=(r+o)/e,this._z=(a+c)/e):s>u?(e=2*Math.sqrt(1+s-i-u),this._w=(a-c)/e,this._x=(r+o)/e,this._y=.25*e,this._z=(h+l)/e):(e=2*Math.sqrt(1+u-i-s),this._w=(o-r)/e,this._x=(a+c)/e,this._y=(h+l)/e,this._z=.25*e),this.onChangeCallback(),this},setFromUnitVectors:function(){var t,e,n=1e-6;return function(i,r){return void 0===t&&(t=new s),e=i.dot(r)+1,eMath.abs(i.z)?t.set(-i.y,i.x,0):t.set(0,-i.z,i.y)):t.crossVectors(i,r),this._x=t.x,this._y=t.y,this._z=t.z,this._w=e,this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this.onChangeCallback(),this},dot:function(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this.onChangeCallback(),this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)},premultiply:function(t){return this.multiplyQuaternions(t,this)},multiplyQuaternions:function(t,e){var n=t._x,i=t._y,r=t._z,a=t._w,o=e._x,s=e._y,h=e._z,c=e._w;return this._x=n*c+a*o+i*h-r*s,this._y=i*c+a*s+r*o-n*h,this._z=r*c+a*h+n*s-i*o,this._w=a*c-n*o-i*s-r*h,this.onChangeCallback(),this},slerp:function(t,e){if(0===e)return this;if(1===e)return this.copy(t);var n=this._x,i=this._y,r=this._z,a=this._w,o=a*t._w+n*t._x+i*t._y+r*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=a,this._x=n,this._y=i,this._z=r,this;var s=Math.sqrt(1-o*o);if(Math.abs(s)<.001)return this._w=.5*(a+this._w),this._x=.5*(n+this._x),this._y=.5*(i+this._y),this._z=.5*(r+this._z),this;var h=Math.atan2(s,o),c=Math.sin((1-e)*h)/s,l=Math.sin(e*h)/s;return this._w=a*c+this._w*l,this._x=n*c+this._x*l,this._y=i*c+this._y*l,this._z=r*c+this._z*l,this.onChangeCallback(),this},equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w},fromArray:function(t,e){return void 0===e&&(e=0),this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this.onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t},onChange:function(t){return this.onChangeCallback=t,this},onChangeCallback:function(){}},Object.assign(o,{slerp:function(t,e,n,i){return n.copy(t).slerp(e,i)},slerpFlat:function(t,e,n,i,r,a,o){var s=n[i+0],h=n[i+1],c=n[i+2],l=n[i+3],u=r[a+0],d=r[a+1],p=r[a+2],f=r[a+3];if(l!==f||s!==u||h!==d||c!==p){var m=1-o,g=s*u+h*d+c*p+l*f,v=g>=0?1:-1,y=1-g*g;if(y>Number.EPSILON){var x=Math.sqrt(y),b=Math.atan2(x,g*v);m=Math.sin(m*b)/x,o=Math.sin(o*b)/x}var _=o*v;if(s=s*m+u*_,h=h*m+d*_,c=c*m+p*_,l=l*m+f*_,m===1-o){var w=1/Math.sqrt(s*s+h*h+c*c+l*l);s*=w,h*=w,c*=w,l*=w}}t[e]=s,t[e+1]=h,t[e+2]=c,t[e+3]=l}}),s.prototype={constructor:s,set:function(t,e,n){return this.x=t,this.y=e,this.z=n,this},setScalar:function(t){return this.x=t,this.y=t,this.z=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x,this.y*=t.y,this.z*=t.z,this)},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t,this.z*=t):(this.x=0,this.y=0,this.z=0),this},multiplyVectors:function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},applyEuler:function(){var t;return function(e){return(e&&e.isEuler)===!1&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),void 0===t&&(t=new o),this.applyQuaternion(t.setFromEuler(e))}}(),applyAxisAngle:function(){var t;return function(e,n){return void 0===t&&(t=new o), -this.applyQuaternion(t.setFromAxisAngle(e,n))}}(),applyMatrix3:function(t){var e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*i,this.y=r[1]*e+r[4]*n+r[7]*i,this.z=r[2]*e+r[5]*n+r[8]*i,this},applyMatrix4:function(t){var e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i+r[12],this.y=r[1]*e+r[5]*n+r[9]*i+r[13],this.z=r[2]*e+r[6]*n+r[10]*i+r[14],this},applyProjection:function(t){var e=this.x,n=this.y,i=this.z,r=t.elements,a=1/(r[3]*e+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*i+r[12])*a,this.y=(r[1]*e+r[5]*n+r[9]*i+r[13])*a,this.z=(r[2]*e+r[6]*n+r[10]*i+r[14])*a,this},applyQuaternion:function(t){var e=this.x,n=this.y,i=this.z,r=t.x,a=t.y,o=t.z,s=t.w,h=s*e+a*i-o*n,c=s*n+o*e-r*i,l=s*i+r*n-a*e,u=-r*e-a*n-o*i;return this.x=h*s+u*-r+c*-o-l*-a,this.y=c*s+u*-a+l*-r-h*-o,this.z=l*s+u*-o+h*-a-c*-r,this},project:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.projectionMatrix,t.getInverse(e.matrixWorld)),this.applyProjection(t)}}(),unproject:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.matrixWorld,t.getInverse(e.projectionMatrix)),this.applyProjection(t)}}(),transformDirection:function(t){var e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i,this.y=r[1]*e+r[5]*n+r[9]*i,this.z=r[2]*e+r[6]*n+r[10]*i,this.normalize()},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this},clampScalar:function(){var t,e;return function(n,i){return void 0===t&&(t=new s,e=new s),t.set(n,n,n),e.set(i,i,i),this.clamp(t,e)}}(),clampLength:function(t,e){var n=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,n))/n)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this},lerpVectors:function(t,e,n){return this.subVectors(e,t).multiplyScalar(n).add(t)},cross:function(t,e){if(void 0!==e)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e);var n=this.x,i=this.y,r=this.z;return this.x=i*t.z-r*t.y,this.y=r*t.x-n*t.z,this.z=n*t.y-i*t.x,this},crossVectors:function(t,e){var n=t.x,i=t.y,r=t.z,a=e.x,o=e.y,s=e.z;return this.x=i*s-r*o,this.y=r*a-n*s,this.z=n*o-i*a,this},projectOnVector:function(t){var e=t.dot(this)/t.lengthSq();return this.copy(t).multiplyScalar(e)},projectOnPlane:function(){var t;return function(e){return void 0===t&&(t=new s),t.copy(this).projectOnVector(e),this.sub(t)}}(),reflect:function(){var t;return function(e){return void 0===t&&(t=new s),this.sub(t.copy(e).multiplyScalar(2*this.dot(e)))}}(),angleTo:function(e){var n=this.dot(e)/Math.sqrt(this.lengthSq()*e.lengthSq());return Math.acos(t.Math.clamp(n,-1,1))},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return e*e+n*n+i*i},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)},setFromSpherical:function(t){var e=Math.sin(t.phi)*t.radius;return this.x=e*Math.sin(t.theta),this.y=Math.cos(t.phi)*t.radius,this.z=e*Math.cos(t.theta),this},setFromMatrixPosition:function(t){return this.setFromMatrixColumn(t,3)},setFromMatrixScale:function(t){var e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=i,this},setFromMatrixColumn:function(t,e){if("number"==typeof t){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var n=t;t=e,e=n}return this.fromArray(t.elements,4*e)},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t},fromAttribute:function(t,e,n){return void 0===n&&(n=0),e=e*t.itemSize+n,this.x=t.array[e],this.y=t.array[e+1],this.z=t.array[e+2],this}},c.prototype={constructor:c,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,n=t.length;ethis.max.x||t.ythis.max.y)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y},getParameter:function(t,e){var i=e||new n;return i.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)},clampPoint:function(t,e){var i=e||new n;return i.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new n;return function(e){var n=t.copy(e).clamp(this.min,this.max);return n.sub(e).length()}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},u.prototype=Object.create(i.prototype),u.prototype.constructor=u,Object.defineProperty(u.prototype,"images",{get:function(){return this.image},set:function(t){this.image=t}}),t.WebGLUniforms=function(){var t=new i,e=new u,n=function(){this.seq=[],this.map={}},r=[],a=[],o=function(t,e,n){var i=t[0];if(i<=0||i>0)return t;var a=e*n,o=r[a];if(void 0===o&&(o=new Float32Array(a),r[a]=o),0!==e){i.toArray(o,0);for(var s=1,h=0;s!==e;++s)h+=n,t[s].toArray(o,h)}return o},s=function(t,e){var n=a[e];void 0===n&&(n=new Int32Array(e),a[e]=n);for(var i=0;i!==e;++i)n[i]=t.allocTextureUnit();return n},h=function(t,e){t.uniform1f(this.addr,e)},c=function(t,e){t.uniform1i(this.addr,e)},l=function(t,e){void 0===e.x?t.uniform2fv(this.addr,e):t.uniform2f(this.addr,e.x,e.y)},d=function(t,e){void 0!==e.x?t.uniform3f(this.addr,e.x,e.y,e.z):void 0!==e.r?t.uniform3f(this.addr,e.r,e.g,e.b):t.uniform3fv(this.addr,e)},p=function(t,e){void 0===e.x?t.uniform4fv(this.addr,e):t.uniform4f(this.addr,e.x,e.y,e.z,e.w)},f=function(t,e){t.uniformMatrix2fv(this.addr,!1,e.elements||e)},m=function(t,e){t.uniformMatrix3fv(this.addr,!1,e.elements||e)},g=function(t,e){t.uniformMatrix4fv(this.addr,!1,e.elements||e)},v=function(e,n,i){var r=i.allocTextureUnit();e.uniform1i(this.addr,r),i.setTexture2D(n||t,r)},y=function(t,n,i){var r=i.allocTextureUnit();t.uniform1i(this.addr,r),i.setTextureCube(n||e,r)},x=function(t,e){t.uniform2iv(this.addr,e)},b=function(t,e){t.uniform3iv(this.addr,e)},_=function(t,e){t.uniform4iv(this.addr,e)},w=function(t){switch(t){case 5126:return h;case 35664:return l;case 35665:return d;case 35666:return p;case 35674:return f;case 35675:return m;case 35676:return g;case 35678:return v;case 35680:return y;case 5124:case 35670:return c;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},M=function(t,e){t.uniform1fv(this.addr,e)},E=function(t,e){t.uniform1iv(this.addr,e)},S=function(t,e){t.uniform2fv(this.addr,o(e,this.size,2))},T=function(t,e){t.uniform3fv(this.addr,o(e,this.size,3))},A=function(t,e){t.uniform4fv(this.addr,o(e,this.size,4))},L=function(t,e){t.uniformMatrix2fv(this.addr,!1,o(e,this.size,4))},R=function(t,e){t.uniformMatrix3fv(this.addr,!1,o(e,this.size,9))},C=function(t,e){t.uniformMatrix4fv(this.addr,!1,o(e,this.size,16))},P=function(e,n,i){var r=n.length,a=s(i,r);e.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)i.setTexture2D(n[o]||t,a[o])},U=function(t,n,i){var r=n.length,a=s(i,r);t.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)i.setTextureCube(n[o]||e,a[o])},I=function(t){switch(t){case 5126:return M;case 35664:return S;case 35665:return T;case 35666:return A;case 35674:return L;case 35675:return R;case 35676:return C;case 35678:return P;case 35680:return U;case 5124:case 35670:return E;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},D=function(t,e,n){this.id=t,this.addr=n,this.setValue=w(e.type)},N=function(t,e,n){this.id=t,this.addr=n,this.size=e.size,this.setValue=I(e.type)},O=function(t){this.id=t,n.call(this)};O.prototype.setValue=function(t,e){for(var n=this.seq,i=0,r=n.length;i!==r;++i){var a=n[i];a.setValue(t,e[a.id])}};var F=/([\w\d_]+)(\])?(\[|\.)?/g,B=function(t,e){t.seq.push(e),t.map[e.id]=e},z=function(t,e,n){var i=t.name,r=i.length;for(F.lastIndex=0;;){var a=F.exec(i),o=F.lastIndex,s=a[1],h="]"===a[2],c=a[3];if(h&&(s=0|s),void 0===c||"["===c&&o+2===r){B(n,void 0===c?new D(s,t,e):new N(s,t,e));break}var l=n.map,u=l[s];void 0===u&&(u=new O(s),B(n,u)),n=u}},G=function(t,e,i){n.call(this),this.renderer=i;for(var r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),a=0;a!==r;++a){var o=t.getActiveUniform(e,a),s=o.name,h=t.getUniformLocation(e,s);z(o,h,this)}};return G.prototype.setValue=function(t,e,n){var i=this.map[e];void 0!==i&&i.setValue(t,n,this.renderer)},G.prototype.set=function(t,e,n){var i=this.map[n];void 0!==i&&i.setValue(t,e[n],this.renderer)},G.prototype.setOptional=function(t,e,n){var i=e[n];void 0!==i&&this.setValue(t,n,i)},G.upload=function(t,e,n,i){for(var r=0,a=e.length;r!==a;++r){var o=e[r],s=n[o.id];s.needsUpdate!==!1&&o.setValue(t,s.value,i)}},G.seqWithValue=function(t,e){for(var n=[],i=0,r=t.length;i!==r;++i){var a=t[i];a.id in e&&n.push(a)}return n},G.splitDynamic=function(t,e){for(var n=null,i=t.length,r=0,a=0;a!==i;++a){var o=t[a],s=e[o.id];s&&s.dynamic===!0?(null===n&&(n=[]),n.push(o)):(ry&&v>x?vx?y0&&(i.alphaTest=this.alphaTest),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=this.premultipliedAlpha),this.wireframe===!0&&(i.wireframe=this.wireframe),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),n){var r=e(t.textures),a=e(t.images);r.length>0&&(i.textures=r),a.length>0&&(i.images=a)}return i},clone:function(){return(new this.constructor).copy(this)},copy:function(t){this.name=t.name,this.fog=t.fog,this.lights=t.lights,this.blending=t.blending,this.side=t.side,this.shading=t.shading,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.alphaTest=t.alphaTest,this.premultipliedAlpha=t.premultipliedAlpha,this.overdraw=t.overdraw,this.visible=t.visible,this.clipShadows=t.clipShadows;var e=t.clippingPlanes,n=null;if(null!==e){var i=e.length;n=new Array(i);for(var r=0;r!==i;++r)n[r]=e[r].clone()}return this.clippingPlanes=n,this},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}},Object.assign(x.prototype,e.prototype);var wa=0;t.UniformsUtils={merge:function(t){for(var e={},n=0;n>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this},setRGB:function(t,e,n){return this.r=t,this.g=e,this.b=n,this},setHSL:function(){function e(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+6*(e-t)*(2/3-n):t}return function(n,i,r){if(n=t.Math.euclideanModulo(n,1),i=t.Math.clamp(i,0,1),r=t.Math.clamp(r,0,1),0===i)this.r=this.g=this.b=r;else{var a=r<=.5?r*(1+i):r+i-r*i,o=2*r-a;this.r=e(o,a,n+1/3),this.g=e(o,a,n),this.b=e(o,a,n-1/3)}return this}}(),setStyle:function(e){function n(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}var i;if(i=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(e)){var r,a=i[1],o=i[2];switch(a){case"rgb":case"rgba":if(r=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(255,parseInt(r[1],10))/255,this.g=Math.min(255,parseInt(r[2],10))/255,this.b=Math.min(255,parseInt(r[3],10))/255,n(r[5]),this;if(r=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(100,parseInt(r[1],10))/100,this.g=Math.min(100,parseInt(r[2],10))/100,this.b=Math.min(100,parseInt(r[3],10))/100,n(r[5]),this;break;case"hsl":case"hsla":if(r=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o)){var s=parseFloat(r[1])/360,h=parseInt(r[2],10)/100,c=parseInt(r[3],10)/100;return n(r[5]),this.setHSL(s,h,c)}}}else if(i=/^\#([A-Fa-f0-9]+)$/.exec(e)){var l=i[1],u=l.length;if(3===u)return this.r=parseInt(l.charAt(0)+l.charAt(0),16)/255,this.g=parseInt(l.charAt(1)+l.charAt(1),16)/255,this.b=parseInt(l.charAt(2)+l.charAt(2),16)/255,this;if(6===u)return this.r=parseInt(l.charAt(0)+l.charAt(1),16)/255,this.g=parseInt(l.charAt(2)+l.charAt(3),16)/255,this.b=parseInt(l.charAt(4)+l.charAt(5),16)/255,this}if(e&&e.length>0){var l=t.ColorKeywords[e];void 0!==l?this.setHex(l):console.warn("THREE.Color: Unknown color "+e)}return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},copyGammaToLinear:function(t,e){return void 0===e&&(e=2),this.r=Math.pow(t.r,e),this.g=Math.pow(t.g,e),this.b=Math.pow(t.b,e),this},copyLinearToGamma:function(t,e){void 0===e&&(e=2);var n=e>0?1/e:1;return this.r=Math.pow(t.r,n),this.g=Math.pow(t.g,n),this.b=Math.pow(t.b,n),this},convertGammaToLinear:function(){var t=this.r,e=this.g,n=this.b;return this.r=t*t,this.g=e*e,this.b=n*n,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(t){var e,n,i=t||{h:0,s:0,l:0},r=this.r,a=this.g,o=this.b,s=Math.max(r,a,o),h=Math.min(r,a,o),c=(h+s)/2;if(h===s)e=0,n=0;else{var l=s-h;switch(n=c<=.5?l/(s+h):l/(2-s-h),s){case r:e=(a-o)/l+(ar&&(r=c),l>a&&(a=l),u>o&&(o=u)}this.min.set(e,n,i),this.max.set(r,a,o)},setFromPoints:function(t){this.makeEmpty();for(var e=0,n=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z},getParameter:function(t,e){var n=e||new s;return n.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)},intersectsSphere:function(){var t;return function(e){return void 0===t&&(t=new s),this.clampPoint(e.center,t),t.distanceToSquared(e.center)<=e.radius*e.radius}}(),intersectsPlane:function(t){var e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=t.constant&&n>=t.constant},clampPoint:function(t,e){var n=e||new s;return n.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new s;return function(e){var n=t.copy(e).clamp(this.min,this.max);return n.sub(e).length()}}(),getBoundingSphere:function(){var t=new s;return function(e){var n=e||new S;return n.center=this.center(),n.radius=.5*this.size(t).length(),n}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},applyMatrix4:function(){var t=[new s,new s,new s,new s,new s,new s,new s,new s];return function(e){return this.isEmpty()?this:(t[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),t[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),t[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),t[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),t[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),t[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),t[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),t[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(t),this)}}(),translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},S.prototype={constructor:S,set:function(t,e){return this.center.copy(t),this.radius=e,this},setFromPoints:function(){var t=new E;return function(e,n){var i=this.center;void 0!==n?i.copy(n):t.setFromPoints(e).center(i);for(var r=0,a=0,o=e.length;athis.radius*this.radius&&(i.sub(this.center).normalize(),i.multiplyScalar(this.radius).add(this.center)),i},getBoundingBox:function(t){var e=t||new E;return e.set(this.center,this.center),e.expandByScalar(this.radius),e},applyMatrix4:function(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this},translate:function(t){return this.center.add(t),this},equals:function(t){return t.center.equals(this.center)&&t.radius===this.radius}},T.prototype={constructor:T,set:function(t,e,n,i,r,a,o,s,h){var c=this.elements;return c[0]=t,c[1]=i,c[2]=o,c[3]=e,c[4]=r,c[5]=s,c[6]=n,c[7]=a,c[8]=h,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(t){var e=t.elements;return this.set(e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]),this},setFromMatrix4:function(t){var e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this},applyToVector3Array:function(){var t;return function(e,n,i){void 0===t&&(t=new s),void 0===n&&(n=0),void 0===i&&(i=e.length);for(var r=0,a=n;r1))return i.copy(r).multiplyScalar(o).add(e.start)}else if(0===this.distanceToPoint(e.start))return i.copy(e.start)}}(),intersectsLine:function(t){var e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0},intersectsBox:function(t){return t.intersectsPlane(this)},intersectsSphere:function(t){return t.intersectsPlane(this)},coplanarPoint:function(t){var e=t||new s;return e.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var t=new s,e=new T;return function(n,i){var r=this.coplanarPoint(t).applyMatrix4(n),a=i||e.getNormalMatrix(n),o=this.normal.applyMatrix3(a).normalize();return this.constant=-r.dot(o),this}}(),translate:function(t){return this.constant=this.constant-t.dot(this.normal),this},equals:function(t){return t.normal.equals(this.normal)&&t.constant===this.constant}},L.prototype={constructor:L,set:function(t,e,n,i,r,a){var o=this.planes;return o[0].copy(t),o[1].copy(e),o[2].copy(n),o[3].copy(i),o[4].copy(r),o[5].copy(a),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){for(var e=this.planes,n=0;n<6;n++)e[n].copy(t.planes[n]);return this},setFromMatrix:function(t){var e=this.planes,n=t.elements,i=n[0],r=n[1],a=n[2],o=n[3],s=n[4],h=n[5],c=n[6],l=n[7],u=n[8],d=n[9],p=n[10],f=n[11],m=n[12],g=n[13],v=n[14],y=n[15];return e[0].setComponents(o-i,l-s,f-u,y-m).normalize(),e[1].setComponents(o+i,l+s,f+u,y+m).normalize(),e[2].setComponents(o+r,l+h,f+d,y+g).normalize(),e[3].setComponents(o-r,l-h,f-d,y-g).normalize(),e[4].setComponents(o-a,l-c,f-p,y-v).normalize(),e[5].setComponents(o+a,l+c,f+p,y+v).normalize(),this},intersectsObject:function(){var t=new S;return function(e){var n=e.geometry;return null===n.boundingSphere&&n.computeBoundingSphere(),t.copy(n.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSprite:function(){var t=new S;return function(e){return t.center.set(0,0,0),t.radius=.7071067811865476,t.applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSphere:function(t){for(var e=this.planes,n=t.center,i=-t.radius,r=0;r<6;r++){var a=e[r].distanceToPoint(n);if(a0?n.min.x:n.max.x,e.x=a.normal.x>0?n.max.x:n.min.x,t.y=a.normal.y>0?n.min.y:n.max.y,e.y=a.normal.y>0?n.max.y:n.min.y,t.z=a.normal.z>0?n.min.z:n.max.z,e.z=a.normal.z>0?n.max.z:n.min.z;var o=a.distanceToPoint(t),s=a.distanceToPoint(e);if(o<0&&s<0)return!1}return!0}}(),containsPoint:function(t){for(var e=this.planes,n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}},t.WebGLShader=function(){function t(t){for(var e=t.split("\n"),n=0;n");return l(i)}var i=/#include +<([\w\d.]+)>/g;return e.replace(i,n)}function u(t){function e(t,e,n,i){for(var r="",a=parseInt(e);a0?e.gammaFactor:1,L=a(v,m,e.extensions),R=o(y),C=g.createProgram();f&&f.isRawShaderMaterial?(S=[R].filter(h).join("\n"),T=[R].filter(h).join("\n")):(S=["precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+A,"#define MAX_BONES "+m.maxBones,m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+M:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.displacementMap&&m.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.skinning?"#define USE_SKINNING":"",m.useVertexTexture?"#define BONE_TEXTURE":"",m.morphTargets?"#define USE_MORPHTARGETS":"",m.morphNormals&&m.flatShading===!1?"#define USE_MORPHNORMALS":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+_:"",m.sizeAttenuation?"#define USE_SIZEATTENUATION":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(h).join("\n"),T=[L,"precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.alphaTest?"#define ALPHATEST "+m.alphaTest:"","#define GAMMA_FACTOR "+A,m.useFog&&m.fog?"#define USE_FOG":"",m.useFog&&m.fogExp?"#define FOG_EXP2":"",m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+w:"",m.envMap?"#define "+M:"",m.envMap?"#define "+E:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+_:"",m.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",m.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",m.envMap&&e.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",m.toneMapping!==rr?"#define TONE_MAPPING":"",m.toneMapping!==rr?t.ShaderChunk.tonemapping_pars_fragment:"",m.toneMapping!==rr?r("toneMapping",m.toneMapping):"",m.outputEncoding||m.mapEncoding||m.envMapEncoding||m.emissiveMapEncoding?t.ShaderChunk.encodings_pars_fragment:"",m.mapEncoding?n("mapTexelToLinear",m.mapEncoding):"",m.envMapEncoding?n("envMapTexelToLinear",m.envMapEncoding):"",m.emissiveMapEncoding?n("emissiveMapTexelToLinear",m.emissiveMapEncoding):"",m.outputEncoding?i("linearToOutputTexel",m.outputEncoding):"",m.depthPacking?"#define DEPTH_PACKING "+f.depthPacking:"","\n"].filter(h).join("\n")),x=l(x,m),x=c(x,m),b=l(b,m),b=c(b,m),(f&&f.isShaderMaterial)===!1&&(x=u(x),b=u(b));var P=S+x,U=T+b,I=t.WebGLShader(g,g.VERTEX_SHADER,P),D=t.WebGLShader(g,g.FRAGMENT_SHADER,U);g.attachShader(C,I),g.attachShader(C,D),void 0!==f.index0AttributeName?g.bindAttribLocation(C,0,f.index0AttributeName):m.morphTargets===!0&&g.bindAttribLocation(C,0,"position"),g.linkProgram(C);var N=g.getProgramInfoLog(C),O=g.getShaderInfoLog(I),F=g.getShaderInfoLog(D),B=!0,z=!0;g.getProgramParameter(C,g.LINK_STATUS)===!1?(B=!1,console.error("THREE.WebGLProgram: shader error: ",g.getError(),"gl.VALIDATE_STATUS",g.getProgramParameter(C,g.VALIDATE_STATUS),"gl.getProgramInfoLog",N,O,F)):""!==N?console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",N):""!==O&&""!==F||(z=!1),z&&(this.diagnostics={runnable:B,material:f,programLog:N,vertexShader:{log:O,prefix:S},fragmentShader:{log:F,prefix:T}}),g.deleteShader(I),g.deleteShader(D);var G;this.getUniforms=function(){return void 0===G&&(G=new t.WebGLUniforms(g,C,e)),G};var k;return this.getAttributes=function(){return void 0===k&&(k=s(g,C)),k},this.destroy=function(){g.deleteProgram(C),this.program=void 0},Object.defineProperties(this,{uniforms:{get:function(){return console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms()."),this.getUniforms()}},attributes:{get:function(){return console.warn("THREE.WebGLProgram: .attributes is now .getAttributes()."),this.getAttributes()}}}),this.id=d++,this.code=p,this.usedTimes=1,this.program=C,this.vertexShader=I,this.fragmentShader=D,this}}(),U.prototype={constructor:U,get count(){return this.array.length/this.itemSize},set needsUpdate(t){t===!0&&this.version++},setDynamic:function(t){return this.dynamic=t,this},copy:function(t){return this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.dynamic=t.dynamic,this},copyAt:function(t,e,n){t*=this.itemSize,n*=e.itemSize;for(var i=0,r=this.itemSize;i1){for(var e=0;e1)for(var e=0;e0){r.children=[];for(var a=0;a0&&(i.geometries=o),s.length>0&&(i.materials=s),h.length>0&&(i.textures=h),c.length>0&&(i.images=c)}return i.object=r,i},clone:function(t){return(new this.constructor).copy(this,t)},copy:function(t,e){if(void 0===e&&(e=!0),this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(var n=0;n0)for(var m=0;m0&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var t,e,n,i,r;for(n=0,i=this.faces.length;n0&&(t+=e[n].distanceTo(e[n-1])),this.lineDistances[n]=t},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E),this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new S),this.boundingSphere.setFromPoints(this.vertices)},merge:function(t,e,n){if((t&&t.isGeometry)===!1)return void console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",t);var i,r=this.vertices.length,a=this.vertices,o=t.vertices,s=this.faces,h=t.faces,c=this.faceVertexUvs[0],l=t.faceVertexUvs[0];void 0===n&&(n=0),void 0!==e&&(i=(new T).getNormalMatrix(e));for(var u=0,d=o.length;u=0;n--){var g=p[n];for(this.faces.splice(g,1),o=0,s=this.faceVertexUvs.length;o0,w=v.vertexNormals.length>0,M=1!==v.color.r||1!==v.color.g||1!==v.color.b,E=v.vertexColors.length>0,S=0;if(S=t(S,0,0),S=t(S,1,y),S=t(S,2,x),S=t(S,3,b),S=t(S,4,_),S=t(S,5,w),S=t(S,6,M),S=t(S,7,E),l.push(S),l.push(v.a,v.b,v.c),l.push(v.materialIndex),b){var T=this.faceVertexUvs[0][h];l.push(i(T[0]),i(T[1]),i(T[2]))}if(_&&l.push(e(v.normal)),w){var A=v.vertexNormals;l.push(e(A[0]),e(A[1]),e(A[2]))}if(M&&l.push(n(v.color)),E){var L=v.vertexColors;l.push(n(L[0]),n(L[1]),n(L[2]))}}return r.data={},r.data.vertices=s,r.data.normals=u,p.length>0&&(r.data.colors=p),m.length>0&&(r.data.uvs=[m]),r.data.faces=l,r},clone:function(){return(new q).copy(this)},copy:function(t){this.vertices=[],this.faces=[],this.faceVertexUvs=[[]];for(var e=t.vertices,n=0,i=e.length;n0,s=a[1]&&a[1].length>0,h=t.morphTargets,c=h.length;if(c>0){e=[];for(var l=0;l0){u=[];for(var l=0;l0){var n=new Float32Array(3*t.normals.length);this.addAttribute("normal",new U(n,3).copyVector3sArray(t.normals))}if(t.colors.length>0){var i=new Float32Array(3*t.colors.length);this.addAttribute("color",new U(i,3).copyColorsArray(t.colors))}if(t.uvs.length>0){var r=new Float32Array(2*t.uvs.length);this.addAttribute("uv",new U(r,2).copyVector2sArray(t.uvs))}if(t.uvs2.length>0){var a=new Float32Array(2*t.uvs2.length);this.addAttribute("uv2",new U(a,2).copyVector2sArray(t.uvs2))}if(t.indices.length>0){var o=t.vertices.length>65535?Uint32Array:Uint16Array,s=new o(3*t.indices.length);this.setIndex(new U(s,1).copyIndicesArray(t.indices))}this.groups=t.groups;for(var h in t.morphTargets){for(var c=[],l=t.morphTargets[h],u=0,d=l.length;u0){var m=new G(4*t.skinIndices.length,4);this.addAttribute("skinIndex",m.copyVector4sArray(t.skinIndices))}if(t.skinWeights.length>0){var g=new G(4*t.skinWeights.length,4);this.addAttribute("skinWeight",g.copyVector4sArray(t.skinWeights))}return null!==t.boundingSphere&&(this.boundingSphere=t.boundingSphere.clone()),null!==t.boundingBox&&(this.boundingBox=t.boundingBox.clone()),this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E);var t=this.attributes.position.array;void 0!==t?this.boundingBox.setFromArray(t):this.boundingBox.makeEmpty(),(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var t=new E,e=new s;return function(){null===this.boundingSphere&&(this.boundingSphere=new S);var n=this.attributes.position;if(n){var i=n.array,r=this.boundingSphere.center;t.setFromArray(i),t.center(r);for(var a=0,o=0,s=i.length;o0&&(t.data.groups=JSON.parse(JSON.stringify(s)));var h=this.boundingSphere;return null!==h&&(t.data.boundingSphere={center:h.center.toArray(),radius:h.radius}),t},clone:function(){return(new Q).copy(this)},copy:function(t){var e=t.index;null!==e&&this.setIndex(e.clone());var n=t.attributes;for(var i in n){var r=n[i];this.addAttribute(i,r.clone())}for(var a=t.groups,o=0,s=a.length;o0)if(s=d*f-p,h=d*p-f,l=u*g,s>=0)if(h>=-l)if(h<=l){var v=1/g;s*=v,h*=v,c=s*(s+d*h+2*p)+h*(d*s+h+2*f)+m}else h=u,s=Math.max(0,-(d*h+p)),c=-s*s+h*(h+2*f)+m;else h=-u,s=Math.max(0,-(d*h+p)),c=-s*s+h*(h+2*f)+m;else h<=-l?(s=Math.max(0,-(-d*u+p)),h=s>0?-u:Math.min(Math.max(-u,-f),u),c=-s*s+h*(h+2*f)+m):h<=l?(s=0,h=Math.min(Math.max(-u,-f),u),c=h*(h+2*f)+m):(s=Math.max(0,-(d*u+p)),h=s>0?u:Math.min(Math.max(-u,-f),u),c=-s*s+h*(h+2*f)+m);else h=d>0?-u:u,s=Math.max(0,-(d*h+p)),c=-s*s+h*(h+2*f)+m;return a&&a.copy(this.direction).multiplyScalar(s).add(this.origin),o&&o.copy(e).multiplyScalar(h).add(t),c}}(),intersectSphere:function(){var t=new s;return function(e,n){t.subVectors(e.center,this.origin);var i=t.dot(this.direction),r=t.dot(t)-i*i,a=e.radius*e.radius;if(r>a)return null;var o=Math.sqrt(a-r),s=i-o,h=i+o;return s<0&&h<0?null:s<0?this.at(h,n):this.at(s,n)}}(),intersectsSphere:function(t){return this.distanceToPoint(t.center)<=t.radius},distanceToPlane:function(t){var e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;var n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null},intersectPlane:function(t,e){var n=this.distanceToPlane(t);return null===n?null:this.at(n,e)},intersectsPlane:function(t){var e=t.distanceToPoint(this.origin);if(0===e)return!0;var n=t.normal.dot(this.direction);return n*e<0},intersectBox:function(t,e){var n,i,r,a,o,s,h=1/this.direction.x,c=1/this.direction.y,l=1/this.direction.z,u=this.origin;return h>=0?(n=(t.min.x-u.x)*h,i=(t.max.x-u.x)*h):(n=(t.max.x-u.x)*h,i=(t.min.x-u.x)*h),c>=0?(r=(t.min.y-u.y)*c,a=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,a=(t.min.y-u.y)*c),n>a||r>i?null:((r>n||n!==n)&&(n=r),(a=0?(o=(t.min.z-u.z)*l,s=(t.max.z-u.z)*l):(o=(t.max.z-u.z)*l,s=(t.min.z-u.z)*l),n>s||o>i?null:((o>n||n!==n)&&(n=o),(s=0?n:i,e)))},intersectsBox:function(){var t=new s;return function(e){return null!==this.intersectBox(e,t)}}(),intersectTriangle:function(){var t=new s,e=new s,n=new s,i=new s;return function(r,a,o,s,h){e.subVectors(a,r),n.subVectors(o,r),i.crossVectors(e,n);var c,l=this.direction.dot(i);if(l>0){if(s)return null;c=1}else{if(!(l<0))return null;c=-1,l=-l}t.subVectors(this.origin,r);var u=c*this.direction.dot(n.crossVectors(t,n));if(u<0)return null;var d=c*this.direction.dot(e.cross(t));if(d<0)return null;if(u+d>l)return null;var p=-c*t.dot(i);return p<0?null:this.at(p/l,h)}}(),applyMatrix4:function(t){return this.direction.add(this.origin).applyMatrix4(t),this.origin.applyMatrix4(t),this.direction.sub(this.origin),this.direction.normalize(),this},equals:function(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}},ct.prototype={constructor:ct,set:function(t,e){return this.start.copy(t),this.end.copy(e),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.start.copy(t.start),this.end.copy(t.end),this},center:function(t){var e=t||new s;return e.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(t){var e=t||new s;return e.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(t,e){var n=e||new s;return this.delta(n).multiplyScalar(t).add(this.start)},closestPointToPointParameter:function(){var e=new s,n=new s;return function(i,r){e.subVectors(i,this.start),n.subVectors(this.end,this.start);var a=n.dot(n),o=n.dot(e),s=o/a;return r&&(s=t.Math.clamp(s,0,1)),s}}(),closestPointToPoint:function(t,e,n){var i=this.closestPointToPointParameter(t,e),r=n||new s;return this.delta(r).multiplyScalar(i).add(this.start)},applyMatrix4:function(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this},equals:function(t){return t.start.equals(this.start)&&t.end.equals(this.end)}},lt.normal=function(){var t=new s;return function(e,n,i,r){var a=r||new s;a.subVectors(i,n),t.subVectors(e,n),a.cross(t);var o=a.lengthSq();return o>0?a.multiplyScalar(1/Math.sqrt(o)):a.set(0,0,0)}}(),lt.barycoordFromPoint=function(){var t=new s,e=new s,n=new s;return function(i,r,a,o,h){t.subVectors(o,r),e.subVectors(a,r),n.subVectors(i,r);var c=t.dot(t),l=t.dot(e),u=t.dot(n),d=e.dot(e),p=e.dot(n),f=c*d-l*l,m=h||new s;if(0===f)return m.set(-2,-1,-1);var g=1/f,v=(d*u-l*p)*g,y=(c*p-l*u)*g;return m.set(1-v-y,y,v)}}(),lt.containsPoint=function(){var t=new s;return function(e,n,i,r){var a=lt.barycoordFromPoint(e,n,i,r,t);return a.x>=0&&a.y>=0&&a.x+a.y<=1}}(),lt.prototype={constructor:lt,set:function(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this},setFromPointsAndIndices:function(t,e,n,i){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[i]),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this},area:function(){var t=new s,e=new s;return function(){return t.subVectors(this.c,this.b),e.subVectors(this.a,this.b),.5*t.cross(e).length()}}(),midpoint:function(t){var e=t||new s;return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(t){return lt.normal(this.a,this.b,this.c,t)},plane:function(t){var e=t||new A;return e.setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(t,e){return lt.barycoordFromPoint(t,this.a,this.b,this.c,e)},containsPoint:function(t){return lt.containsPoint(t,this.a,this.b,this.c)},closestPointToPoint:function(){var t,e,n,i;return function(r,a){void 0===t&&(t=new A,e=[new ct,new ct,new ct],n=new s,i=new s);var o=a||new s,h=1/0;if(t.setFromCoplanarPoints(this.a,this.b,this.c),t.projectPoint(r,n),this.containsPoint(n)===!0)o.copy(n);else{e[0].set(this.a,this.b),e[1].set(this.b,this.c),e[2].set(this.c,this.a);for(var c=0;c0){this.morphTargetBase=-1,this.morphTargetInfluences=[],this.morphTargetDictionary={};for(var t=0,e=this.geometry.morphTargets.length;te.far?null:{distance:c,point:b.clone(),object:t}}function i(n,i,r,a,o,s,h,d){c.fromArray(a,3*s),l.fromArray(a,3*h),u.fromArray(a,3*d);var p=e(n,i,r,c,l,u,x);return p&&(o&&(m.fromArray(o,2*s),g.fromArray(o,2*h),v.fromArray(o,2*d),p.uv=t(x,c,l,u,m,g,v)),p.face=new V(s,h,d,lt.normal(c,l,u)),p.faceIndex=s),p}var r=new a,o=new ht,h=new S,c=new s,l=new s,u=new s,d=new s,p=new s,f=new s,m=new n,g=new n,v=new n,y=new s,x=new s,b=new s;return function(n,a){var s=this.geometry,y=this.material,b=this.matrixWorld;if(void 0!==y&&(null===s.boundingSphere&&s.computeBoundingSphere(),h.copy(s.boundingSphere),h.applyMatrix4(b),n.ray.intersectsSphere(h)!==!1&&(r.getInverse(b),o.copy(n.ray).applyMatrix4(r),null===s.boundingBox||o.intersectsBox(s.boundingBox)!==!1))){var _,w;if(s&&s.isBufferGeometry){var M,E,S,T=s.index,A=s.attributes,L=A.position.array;if(void 0!==A.uv&&(_=A.uv.array),null!==T)for(var R=T.array,C=0,P=R.length;C0&&(_=z);for(var G=0,k=B.length;Gr||n.push({distance:Math.sqrt(i),point:this.position,face:null,object:this})}}(),clone:function(){return new this.constructor(this.material).copy(this)}}),Et.prototype=Object.assign(Object.create(X.prototype),{constructor:Et,copy:function(t){X.prototype.copy.call(this,t,!1);for(var e=t.levels,n=0,i=e.length;n1){t.setFromMatrixPosition(n.matrixWorld),e.setFromMatrixPosition(this.matrixWorld);var r=t.distanceTo(e);i[0].object.visible=!0;for(var a=1,o=i.length;a=i[a].distance;a++)i[a-1].object.visible=!1,i[a].object.visible=!0;for(;ao)){p.applyMatrix4(this.matrixWorld);var E=i.ray.origin.distanceTo(p);Ei.far||r.push({distance:E,point:d.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}else for(var x=0,b=v.length/3-1;xo)){p.applyMatrix4(this.matrixWorld);var E=i.ray.origin.distanceTo(p);Ei.far||r.push({distance:E,point:d.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}else if(h&&h.isGeometry)for(var S=h.vertices,T=S.length,x=0;xo)){p.applyMatrix4(this.matrixWorld);var E=i.ray.origin.distanceTo(p);Ei.far||r.push({distance:E,point:d.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}}),Pt.prototype=Object.assign(Object.create(Ct.prototype),{constructor:Pt}),Ut.prototype=Object.create(x.prototype),Ut.prototype.constructor=Ut,Ut.prototype.copy=function(t){return x.prototype.copy.call(this,t),this.color.copy(t.color),this.map=t.map,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this},It.prototype=Object.assign(Object.create(X.prototype),{constructor:It,raycast:function(){var t=new a,e=new ht,n=new S;return function(i,r){function a(t,n){var a=e.distanceSqToPoint(t);if(ai.far)return;r.push({distance:h,distanceToRay:Math.sqrt(a),point:s.clone(),index:n,face:null,object:o})}}var o=this,h=this.geometry,c=this.matrixWorld,l=i.params.Points.threshold;if(null===h.boundingSphere&&h.computeBoundingSphere(),n.copy(h.boundingSphere),n.applyMatrix4(c),i.ray.intersectsSphere(n)!==!1){t.getInverse(c),e.copy(i.ray).applyMatrix4(t);var u=l/((this.scale.x+this.scale.y+this.scale.z)/3),d=u*u,p=new s;if(h&&h.isBufferGeometry){var f=h.index,m=h.attributes,g=m.position.array;if(null!==f)for(var v=f.array,y=0,x=v.length;y0||0===t.search(/^data\:image\/jpeg/);a.format=i?Br:zr,a.image=n,a.needsUpdate=!0,void 0!==e&&e(a)},n,r),a},setCrossOrigin:function(t){return this.crossOrigin=t,this},setPath:function(t){return this.path=t,this}}),ee.prototype=Object.assign(Object.create(X.prototype),{constructor:ee,copy:function(t){return X.prototype.copy.call(this,t),this.color.copy(t.color),this.intensity=t.intensity,this},toJSON:function(t){var e=X.prototype.toJSON.call(this,t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),e}}),ne.prototype=Object.assign(Object.create(ee.prototype),{constructor:ne,copy:function(t){return ee.prototype.copy.call(this,t),this.groundColor.copy(t.groundColor),this}}),Object.assign(ie.prototype,{copy:function(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this},clone:function(){return(new this.constructor).copy(this)}}),re.prototype=Object.assign(Object.create(ie.prototype),{constructor:re,update:function(e){var n=2*t.Math.RAD2DEG*e.angle,i=this.mapSize.width/this.mapSize.height,r=e.distance||500,a=this.camera;n===a.fov&&i===a.aspect&&r===a.far||(a.fov=n,a.aspect=i,a.far=r,a.updateProjectionMatrix())}}),ae.prototype=Object.assign(Object.create(ee.prototype),{constructor:ae,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),oe.prototype=Object.assign(Object.create(ee.prototype),{constructor:oe,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}),se.prototype=Object.assign(Object.create(ie.prototype),{constructor:se}),he.prototype=Object.assign(Object.create(ee.prototype),{constructor:he,copy:function(t){return ee.prototype.copy.call(this,t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),ce.prototype=Object.assign(Object.create(ee.prototype),{constructor:ce}),t.AnimationUtils={arraySlice:function(e,n,i){return t.AnimationUtils.isTypedArray(e)?new e.constructor(e.subarray(n,i)):e.slice(n,i)},convertArray:function(t,e,n){return!t||!n&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)},isTypedArray:function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},getKeyframeOrder:function(t){function e(e,n){return t[e]-t[n]}for(var n=t.length,i=new Array(n),r=0;r!==n;++r)i[r]=r;return i.sort(e),i},sortedArray:function(t,e,n){for(var i=t.length,r=new t.constructor(i),a=0,o=0;o!==i;++a)for(var s=n[a]*e,h=0;h!==e;++h)r[o++]=t[s+h];return r},flattenJSON:function(t,e,n,i){for(var r=1,a=t[0];void 0!==a&&void 0===a[i];)a=t[r++];if(void 0!==a){var o=a[i];if(void 0!==o)if(Array.isArray(o)){do o=a[i],void 0!==o&&(e.push(a.time),n.push.apply(n,o)),a=t[r++];while(void 0!==a)}else if(void 0!==o.toArray){do o=a[i],void 0!==o&&(e.push(a.time),o.toArray(n,n.length)),a=t[r++];while(void 0!==a)}else do o=a[i],void 0!==o&&(e.push(a.time),n.push(o)),a=t[r++];while(void 0!==a)}}},le.prototype={constructor:le,evaluate:function(t){var e=this.parameterPositions,n=this._cachedIndex,i=e[n],r=e[n-1];t:{e:{var a;n:{i:if(!(t=r)break t;var s=e[1];t=r)break e}a=n,n=0}}for(;n>>1;tn;)--o;if(++o,0!==a||o!==r){a>=o&&(o=Math.max(o,1),a=o-1);var s=this.getValueSize();this.times=t.AnimationUtils.arraySlice(i,a,o),this.values=t.AnimationUtils.arraySlice(this.values,a*s,o*s)}return this},validate:function(){var e=!0,n=this.getValueSize();n-Math.floor(n)!==0&&(console.error("invalid value size in track",this),e=!1);var i=this.times,r=this.values,a=i.length;0===a&&(console.error("track is empty",this),e=!1);for(var o=null,s=0;s!==a;s++){var h=i[s];if("number"==typeof h&&isNaN(h)){console.error("time is not a valid number",this,s,h),e=!1;break}if(null!==o&&o>h){console.error("out of order keys",this,s,h,o),e=!1;break}o=h}if(void 0!==r&&t.AnimationUtils.isTypedArray(r))for(var s=0,c=r.length;s!==c;++s){var l=r[s];if(isNaN(l)){console.error("value is not a valid number",this,s,l),e=!1;break}}return e},optimize:function(){for(var e=this.times,n=this.values,i=this.getValueSize(),r=1,a=1,o=e.length-1;a<=o;++a){var s=!1,h=e[a],c=e[a+1];if(h!==c&&(1!==a||h!==h[0]))for(var l=a*i,u=l-i,d=l+i,p=0;p!==i;++p){var f=n[l+p];if(f!==n[u+p]||f!==n[d+p]){s=!0;break}}if(s){if(a!==r){e[r]=e[a];for(var m=a*i,g=r*i,p=0;p!==i;++p)n[g+p]=n[m+p]}++r}}return r!==e.length&&(this.times=t.AnimationUtils.arraySlice(e,0,r),this.values=t.AnimationUtils.arraySlice(n,0,r*i)),this}},me.prototype=Object.assign(Object.create(Ta),{constructor:me,ValueTypeName:"vector"}),ge.prototype=Object.assign(Object.create(le.prototype),{constructor:ge,interpolate_:function(t,e,n,i){for(var r=this.resultBuffer,a=this.sampleValues,s=this.valueSize,h=t*s,c=(n-e)/(i-e),l=h+s;h!==l;h+=4)o.slerpFlat(r,0,a,h-s,a,h,c);return r}}),ve.prototype=Object.assign(Object.create(Ta),{constructor:ve,ValueTypeName:"quaternion",DefaultInterpolation:ia,InterpolantFactoryMethodLinear:function(t){return new ge(this.times,this.values,this.getValueSize(),t)},InterpolantFactoryMethodSmooth:void 0}),ye.prototype=Object.assign(Object.create(Ta),{constructor:ye,ValueTypeName:"number"}),xe.prototype=Object.assign(Object.create(Ta),{constructor:xe,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:na,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),be.prototype=Object.assign(Object.create(Ta),{constructor:be,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:na,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),_e.prototype=Object.assign(Object.create(Ta),{constructor:_e,ValueTypeName:"color"}),we.prototype=Ta,Ta.constructor=we,Object.assign(we,{parse:function(e){if(void 0===e.type)throw new Error("track type undefined, can not parse");var n=we._getTrackTypeForValueTypeName(e.type);if(void 0===e.times){var i=[],r=[];t.AnimationUtils.flattenJSON(e.keys,i,r,"value"),e.times=i,e.values=r}return void 0!==n.parse?n.parse(e):new n(e.name,e.times,e.values,e.interpolation)},toJSON:function(e){var n,i=e.constructor;if(void 0!==i.toJSON)n=i.toJSON(e);else{n={name:e.name,times:t.AnimationUtils.convertArray(e.times,Array),values:t.AnimationUtils.convertArray(e.values,Array)};var r=e.getInterpolation();r!==e.DefaultInterpolation&&(n.interpolation=r)}return n.type=e.ValueTypeName,n},_getTrackTypeForValueTypeName:function(t){switch(t.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return ye;case"vector":case"vector2":case"vector3":case"vector4":return me;case"color":return _e;case"quaternion":return ve;case"bool":case"boolean":return be;case"string":return xe}throw new Error("Unsupported typeName: "+t)}}),Me.prototype={constructor:Me,resetDuration:function(){for(var t=this.tracks,e=0,n=0,i=t.length;n!==i;++n){var r=this.tracks[n];e=Math.max(e,r.times[r.times.length-1])}this.duration=e},trim:function(){for(var t=0;t1){var c=h[1],l=i[c];l||(i[c]=l=[]),l.push(s)}}var u=[];for(var c in i)u.push(Me.CreateFromMorphTargetSequence(c,i[c],e,n));return u},parseAnimation:function(e,n,i){if(!e)return console.error(" no animation in JSONLoader data"),null;for(var r=function(e,n,i,r,a){if(0!==i.length){var o=[],s=[];t.AnimationUtils.flattenJSON(i,o,s,r),0!==o.length&&a.push(new e(n,o,s))}},a=[],o=e.name||"default",s=e.length||-1,h=e.fps||30,c=e.hierarchy||[],l=0;l1?t.skinWeights[n+1]:0,o=e>2?t.skinWeights[n+2]:0,s=e>3?t.skinWeights[n+3]:0;h.skinWeights.push(new p(r,a,o,s))}if(t.skinIndices)for(var n=0,i=t.skinIndices.length;n1?t.skinIndices[n+1]:0,u=e>2?t.skinIndices[n+2]:0,d=e>3?t.skinIndices[n+3]:0;h.skinIndices.push(new p(c,l,u,d))}h.bones=t.bones,h.bones&&h.bones.length>0&&(h.skinWeights.length!==h.skinIndices.length||h.skinIndices.length!==h.vertices.length)&&console.warn("When skinning, number of vertices ("+h.vertices.length+"), skinIndices ("+h.skinIndices.length+"), and skinWeights ("+h.skinWeights.length+") should match.")}function a(e){if(void 0!==t.morphTargets)for(var n=0,i=t.morphTargets.length;n0){console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.');for(var u=h.faces,d=t.morphColors[0].colors,n=0,i=u.length;n0&&(h.animations=e)}var h=new q,c=void 0!==t.scale?1/t.scale:1;if(i(c),r(),a(c),o(),h.computeFaceNormals(),h.computeBoundingSphere(),void 0===t.materials||0===t.materials.length)return{geometry:h};var l=Te.prototype.initMaterials(t.materials,e,this.crossOrigin);return{geometry:h,materials:l}}}),Object.assign(Le.prototype,{load:function(t,e,n,i){""===this.texturePath&&(this.texturePath=t.substring(0,t.lastIndexOf("/")+1));var r=this,a=new Zt(r.manager);a.load(t,function(t){r.parse(JSON.parse(t),e)},n,i)},setTexturePath:function(t){this.texturePath=t},setCrossOrigin:function(t){this.crossOrigin=t},parse:function(t,e){var n=this.parseGeometries(t.geometries),i=this.parseImages(t.images,function(){void 0!==e&&e(o)}),r=this.parseTextures(t.textures,i),a=this.parseMaterials(t.materials,r),o=this.parseObject(t.object,n,a);return t.animations&&(o.animations=this.parseAnimations(t.animations)),void 0!==t.images&&0!==t.images.length||void 0!==e&&e(o),o},parseGeometries:function(t){var e={};if(void 0!==t)for(var n=new Ae,i=new Se,r=0,a=t.length;r0){var a=new qt(e),o=new Kt(a);o.setCrossOrigin(this.crossOrigin);for(var s=0,h=t.length;s0?new Lt(s,h):new dt(s,h);break;case"LOD":o=new Et;break;case"Line":o=new Ct(r(e.geometry),a(e.material),e.mode);break;case"PointCloud":case"Points":o=new It(r(e.geometry),a(e.material));break;case"Sprite":o=new Mt(a(e.material));break;case"Group":o=new Dt;break;default:o=new X}if(o.uuid=e.uuid,void 0!==e.name&&(o.name=e.name),void 0!==e.matrix?(t.fromArray(e.matrix),t.decompose(o.position,o.quaternion,o.scale)):(void 0!==e.position&&o.position.fromArray(e.position),void 0!==e.rotation&&o.rotation.fromArray(e.rotation),void 0!==e.scale&&o.scale.fromArray(e.scale)),void 0!==e.castShadow&&(o.castShadow=e.castShadow),void 0!==e.receiveShadow&&(o.receiveShadow=e.receiveShadow),void 0!==e.visible&&(o.visible=e.visible),void 0!==e.userData&&(o.userData=e.userData),void 0!==e.children)for(var c in e.children)o.add(this.parseObject(e.children[c],n,i));if("LOD"===e.type)for(var l=e.levels,u=0;u(c-s)*(d-h)-(l-h)*(u-s))return!1;var m,g,v,y,x,b,_,w,M,E,S,T,A,L,R;for(m=u-c,g=d-l,v=s-u,y=h-d,x=c-s,b=l-h,o=0;o=-Number.EPSILON&&L>=-Number.EPSILON&&A>=-Number.EPSILON))return!1;return!0}return function(n,i){var r=n.length;if(r<3)return null;var a,o,s,h=[],c=[],l=[];if(t.ShapeUtils.area(n)>0)for(o=0;o2;){if(d--<=0)return console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()"),i?l:h;if(a=o,u<=a&&(a=0),o=a+1,u<=o&&(o=0),s=o+1,u<=s&&(s=0),e(n,a,o,s,u,c)){var p,f,m,g,v;for(p=c[a],f=c[o],m=c[s],h.push([n[p],n[f],n[m]]),l.push([c[a],c[o],c[s]]),g=o,v=o+1;v2&&t[e-1].equals(t[0])&&t.pop()}function r(t,e,n){return t.x!==e.x?t.xNumber.EPSILON){var f;if(d>0){if(p<0||p>d)return[];if(f=c*l-h*u,f<0||f>d)return[]}else{if(p>0||p0||fS?[]:b===S?a?[]:[y]:_<=S?[y,x]:[y,M]}function o(t,e,n,i){var r=e.x-t.x,a=e.y-t.y,o=n.x-t.x,s=n.y-t.y,h=i.x-t.x,c=i.y-t.y,l=r*s-a*o,u=r*c-a*h;if(Math.abs(l)>Number.EPSILON){var d=h*s-c*o;return l>0?u>=0&&d>=0:u>=0||d>=0}return u>0}function s(t,e){function n(t,e){var n=y.length-1,i=t-1;i<0&&(i=n);var r=t+1;r>n&&(r=0);var a=o(y[t],y[i],y[r],s[e]);if(!a)return!1;var h=s.length-1,c=e-1;c<0&&(c=h);var l=e+1;return l>h&&(l=0),a=o(s[e],s[c],s[l],y[t]),!!a}function i(t,e){var n,i,r;for(n=0;n0)return!0;return!1}function r(t,n){var i,r,o,s,h;for(i=0;i0)return!0;return!1}for(var s,h,c,l,u,d,p,f,m,g,v,y=t.concat(),x=[],b=[],_=0,w=e.length;_0;){if(E--,E<0){console.log("Infinite Loop! Holes left:"+x.length+", Probably Hole outside Shape!");break}for(c=M;c=0)break;b[p]=!0}if(h>=0)break}}return y}i(e),n.forEach(i);for(var h,c,l,u,d,p,f={},m=e.concat(),g=0,v=n.length;g0)){h=r;break}h=r-1}if(r=h,i[r]===n){var c=r/(a-1);return c}var l=i[r],u=i[r+1],d=u-l,p=(n-l)/d,c=(r+p)/(a-1);return c},getTangent:function(t){var e=1e-4,n=t-e,i=t+e;n<0&&(n=0),i>1&&(i=1);var r=this.getPoint(n),a=this.getPoint(i),o=a.clone().sub(r);return o.normalize()},getTangentAt:function(t){var e=this.getUtoTmapping(t);return this.getTangent(e)}},Re.create=function(t,e){return t.prototype=Object.create(Re.prototype),t.prototype.constructor=t,t.prototype.getPoint=e,t},Ce.prototype=Object.create(Re.prototype),Ce.prototype.constructor=Ce,Ce.prototype.getPoint=function(t){if(1===t)return this.v2.clone();var e=this.v2.clone().sub(this.v1);return e.multiplyScalar(t).add(this.v1),e},Ce.prototype.getPointAt=function(t){return this.getPoint(t)},Ce.prototype.getTangent=function(t){var e=this.v2.clone().sub(this.v1);return e.normalize()},Pe.prototype=Object.assign(Object.create(Re.prototype),{constructor:Pe,add:function(t){this.curves.push(t)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);t.equals(e)||this.curves.push(new Ce(e,t))},getPoint:function(t){for(var e=t*this.getLength(),n=this.getCurveLengths(),i=0;i=e){var r=n[i]-e,a=this.curves[i],o=a.getLength(),s=0===o?0:1-r/o;return a.getPointAt(s)}i++}return null},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},updateArcLengths:function(){this.needsUpdate=!0,this.cacheLengths=null,this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var t=[],e=0,n=0,i=this.curves.length;n1&&!n[n.length-1].equals(n[0])&&n.push(n[0]),n},createPointsGeometry:function(t){var e=this.getPoints(t);return this.createGeometry(e)},createSpacedPointsGeometry:function(t){var e=this.getSpacedPoints(t);return this.createGeometry(e)},createGeometry:function(t){for(var e=new q,n=0,i=t.length;ne;)i-=e;ii.length-2?i.length-1:a+1],l=i[a>i.length-3?i.length-1:a+2],u=t.CurveUtils.interpolate;return new n(u(s.x,h.x,c.x,l.x,o),u(s.y,h.y,c.y,l.y,o))},De.prototype=Object.create(Re.prototype),De.prototype.constructor=De,De.prototype.getPoint=function(e){var i=t.ShapeUtils.b3;return new n(i(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),i(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y))},De.prototype.getTangent=function(e){var i=t.CurveUtils.tangentCubicBezier;return new n(i(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),i(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y)).normalize()},Ne.prototype=Object.create(Re.prototype),Ne.prototype.constructor=Ne,Ne.prototype.getPoint=function(e){var i=t.ShapeUtils.b2;return new n(i(e,this.v0.x,this.v1.x,this.v2.x),i(e,this.v0.y,this.v1.y,this.v2.y))},Ne.prototype.getTangent=function(e){var i=t.CurveUtils.tangentQuadraticBezier;return new n(i(e,this.v0.x,this.v1.x,this.v2.x),i(e,this.v0.y,this.v1.y,this.v2.y)).normalize()};var Aa;Aa=Object.assign(Object.create(Pe.prototype),{fromPoints:function(t){this.moveTo(t[0].x,t[0].y);for(var e=1,n=t.length;e0){var c=h.getPoint(0);c.equals(this.currentPoint)||this.lineTo(c.x,c.y)}this.curves.push(h);var l=h.getPoint(1);this.currentPoint.copy(l)}}),Oe.prototype=Object.create(q.prototype),Oe.prototype.constructor=Oe,Oe.NoTaper=function(t){return 1},Oe.SinusoidalTaper=function(t){return Math.sin(Math.PI*t)},Oe.FrenetFrames=function(e,n,i){function r(){g[0]=new s,v[0]=new s,h=Number.MAX_VALUE,c=Math.abs(m[0].x),l=Math.abs(m[0].y),u=Math.abs(m[0].z),c<=h&&(h=c,f.set(1,0,0)),l<=h&&(h=l,f.set(0,1,0)),u<=h&&f.set(0,0,1),y.crossVectors(m[0],f).normalize(),g[0].crossVectors(m[0],y),v[0].crossVectors(m[0],g[0])}var o,h,c,l,u,d,p,f=new s,m=[],g=[],v=[],y=new s,x=new a,b=n+1;for(this.tangents=m,this.normals=g,this.binormals=v,d=0;dNumber.EPSILON&&(y.normalize(),o=Math.acos(t.Math.clamp(m[d-1].dot(m[d]),-1,1)),g[d].applyMatrix4(x.makeRotationAxis(y,o))),v[d].crossVectors(m[d],g[d]);if(i)for(o=Math.acos(t.Math.clamp(g[0].dot(g[b-1]),-1,1)),o/=b-1,m[0].dot(y.crossVectors(g[0],g[b-1]))>0&&(o=-o),d=1;dNumber.EPSILON){var p=Math.sqrt(u),f=Math.sqrt(c*c+l*l),m=e.x-h/p,g=e.y+s/p,v=i.x-l/f,y=i.y+c/f,x=((v-m)*l-(y-g)*c)/(s*l-h*c);r=m+s*x-t.x,a=g+h*x-t.y;var b=r*r+a*a;if(b<=2)return new n(r,a);o=Math.sqrt(b/2)}else{var _=!1;s>Number.EPSILON?c>Number.EPSILON&&(_=!0):s<-Number.EPSILON?c<-Number.EPSILON&&(_=!0):Math.sign(h)===Math.sign(l)&&(_=!0),_?(r=-h,a=s,o=Math.sqrt(u)):(r=s,a=h,o=Math.sqrt(u/2))}return new n(r/o,a/o)}function o(){if(w){var t=0,e=X*t;for(Z=0;Z=0;){n=Z,i=Z-1,i<0&&(i=t.length-1);var r=0,a=E+2*_;for(r=0;r=0;z--){for(k=z/_,H=x*(1-k),G=b*Math.sin(k*Math.PI/2),Z=0,J=B.length;ZNumber.EPSILON){if(c<0&&(o=e[a],h=-h,s=e[r],c=-c),t.ys.y)continue;if(t.y===o.y){if(t.x===o.x)return!0}else{var l=c*(t.x-o.x)-h*(t.y-o.y);if(0===l)return!0;if(l<0)continue;i=!i}}else{if(t.y!==o.y)continue;if(s.x<=t.x&&t.x<=o.x||o.x<=t.x&&t.x<=s.x)return!0}}return i}var a=t.ShapeUtils.isClockWise,o=this.subPaths;if(0===o.length)return[];if(n===!0)return i(o);var s,h,c,l=[];if(1===o.length)return h=o[0],c=new ze,c.curves=h.curves,l.push(c),l;var u=!a(o[0].getPoints());u=e?!u:u;var d,p=[],f=[],m=[],g=0;f[g]=void 0,m[g]=[];for(var v=0,y=o.length;v1){for(var x=!1,b=[],_=0,w=f.length;_0&&(x||(m=p))}for(var L,v=0,R=f.length;v0){this.source.connect(this.filters[0]);for(var t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(var t=1,e=this.filters.length;t=.5)for(var a=0;a!==r;++a)t[e+a]=t[n+a]},_slerp:function(t,e,n,i,r){o.slerpFlat(t,e,t,e,t,n,i)},_lerp:function(t,e,n,i,r){for(var a=1-i,o=0;o!==r;++o){var s=e+o;t[s]=t[s]*a+t[n+o]*i}}},$e.prototype={constructor:$e,getValue:function(t,e){this.bind(),this.getValue(t,e)},setValue:function(t,e){this.bind(),this.setValue(t,e)},bind:function(){var t=this.node,e=this.parsedPath,n=e.objectName,i=e.propertyName,r=e.propertyIndex;if(t||(t=$e.findNode(this.rootNode,e.nodeName)||this.rootNode,this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t)return void console.error(" trying to update node for track: "+this.path+" but it wasn't found.");if(n){var a=e.objectIndex;switch(n){case"materials":if(!t.material)return void console.error(" can not bind to material as node does not have a material",this);if(!t.material.materials)return void console.error(" can not bind to material.materials as node.material does not have a materials array",this);t=t.material.materials;break;case"bones":if(!t.skeleton)return void console.error(" can not bind to bones as node does not have a skeleton",this);t=t.skeleton.bones;for(var o=0;o=n){var u=n++,d=e[u];i[d.uuid]=l,e[l]=d,i[c]=u,e[u]=h;for(var p=0,f=a;p!==f;++p){var m=r[p],g=m[u],v=m[l];m[l]=g,m[u]=v}}}this.nCachedObjects_=n},uncache:function(t){for(var e=this._objects,n=e.length,i=this.nCachedObjects_,r=this._indicesByUUID,a=this._bindings,o=a.length,s=0,h=arguments.length;s!==h;++s){var c=arguments[s],l=c.uuid,u=r[l];if(void 0!==u)if(delete r[l],u0)for(var h=this._interpolants,c=this._propertyBindings,l=0,u=h.length;l!==u;++l)h[l].evaluate(o),c[l].accumulate(i,s)},_updateWeight:function(t){var e=0;if(this.enabled){e=this.weight;var n=this._weightInterpolant;if(null!==n){var i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=e,e},_updateTimeScale:function(t){var e=0;if(!this.paused){e=this.timeScale;var n=this._timeScaleInterpolant;if(null!==n){var i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e},_updateTime:function(t){var e=this.time+t;if(0===t)return e;var n=this._clip.duration,i=this.loop,r=this._loopCount;if(i===$r){r===-1&&(this.loopCount=0,this._setEndings(!0,!0,!1));t:{if(e>=n)e=n;else{if(!(e<0))break t;e=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{var a=i===ea;if(r===-1&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,a)):this._setEndings(0===this.repetitions,!0,a)),e>=n||e<0){var o=Math.floor(e/n);e-=n*o,r+=Math.abs(o);var s=this.repetitions-r;if(s<0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,e=t>0?n:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(0===s){var h=t<0;this._setEndings(h,!h,a)}else this._setEndings(!1,!1,a);this._loopCount=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}if(a&&1===(1&r))return this.time=e,n-e}return this.time=e,e},_setEndings:function(t,e,n){var i=this._interpolantSettings;n?(i.endingStart=oa,i.endingEnd=oa):(t?i.endingStart=this.zeroSlopeAtStart?oa:aa:i.endingStart=sa,e?i.endingEnd=this.zeroSlopeAtEnd?oa:aa:i.endingEnd=sa)},_scheduleFading:function(t,e,n){var i=this._mixer,r=i.time,a=this._weightInterpolant;null===a&&(a=i._lendControlInterpolant(),this._weightInterpolant=a);var o=a.parameterPositions,s=a.sampleValues;return o[0]=r,s[0]=e,o[1]=r+t,s[1]=n,this}},Object.assign(nn.prototype,e.prototype,{clipAction:function(t,e){var n=e||this._root,i=n.uuid,r="string"==typeof t?Me.findByName(n,t):t,a=null!==r?r.uuid:t,o=this._actionsByClip[a],s=null;if(void 0!==o){var h=o.actionByRoot[i];if(void 0!==h)return h;s=o.knownActions[0],null===r&&(r=s._clip)}if(null===r)return null;var c=new nn._Action(this,r,e);return this._bindAction(c,s),this._addInactiveAction(c,a,i),c},existingAction:function(t,e){var n=e||this._root,i=n.uuid,r="string"==typeof t?Me.findByName(n,t):t,a=r?r.uuid:t,o=this._actionsByClip[a];return void 0!==o?o.actionByRoot[i]||null:null},stopAllAction:function(){var t=this._actions,e=this._nActiveActions,n=this._bindings,i=this._nActiveBindings;this._nActiveActions=0,this._nActiveBindings=0;for(var r=0;r!==e;++r)t[r].reset();for(var r=0;r!==i;++r)n[r].useCount=0;return this},update:function(t){t*=this.timeScale;for(var e=this._actions,n=this._nActiveActions,i=this.time+=t,r=Math.sign(t),a=this._accuIndex^=1,o=0;o!==n;++o){var s=e[o];s.enabled&&s._update(i,t,r,a)}for(var h=this._bindings,c=this._nActiveBindings,o=0;o!==c;++o)h[o].apply(a);return this},getRoot:function(){return this._root},uncacheClip:function(t){var e=this._actions,n=t.uuid,i=this._actionsByClip,r=i[n];if(void 0!==r){for(var a=r.knownActions,o=0,s=a.length;o!==s;++o){var h=a[o];this._deactivateAction(h);var c=h._cacheIndex,l=e[e.length-1];h._cacheIndex=null,h._byClipCacheIndex=null,l._cacheIndex=c,e[c]=l,e.pop(),this._removeInactiveBindingsForAction(h)}delete i[n]}},uncacheRoot:function(t){var e=t.uuid,n=this._actionsByClip;for(var i in n){var r=n[i].actionByRoot,a=r[e];void 0!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}var o=this._bindingsByRootAndName,s=o[e];if(void 0!==s)for(var h in s){var c=s[h];c.restoreOriginalState(),this._removeInactiveBinding(c)}},uncacheAction:function(t,e){var n=this.existingAction(t,e);null!==n&&(this._deactivateAction(n), -this._removeInactiveAction(n))}}),nn._Action=en._new,Object.assign(nn.prototype,{_bindAction:function(t,e){var n=t._localRoot||this._root,i=t._clip.tracks,r=i.length,a=t._propertyBindings,o=t._interpolants,s=n.uuid,h=this._bindingsByRootAndName,c=h[s];void 0===c&&(c={},h[s]=c);for(var l=0;l!==r;++l){var u=i[l],d=u.name,p=c[d];if(void 0!==p)a[l]=p;else{if(p=a[l],void 0!==p){null===p._cacheIndex&&(++p.referenceCount,this._addInactiveBinding(p,s,d));continue}var f=e&&e._propertyBindings[l].binding.parsedPath;p=new Ke($e.create(n,d,f),u.ValueTypeName,u.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,s,d),a[l]=p}o[l].resultBuffer=p.buffer}},_activateAction:function(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){var e=(t._localRoot||this._root).uuid,n=t._clip.uuid,i=this._actionsByClip[n];this._bindAction(t,i&&i.knownActions[0]),this._addInactiveAction(t,n,e)}for(var r=t._propertyBindings,a=0,o=r.length;a!==o;++a){var s=r[a];0===s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(t)}},_deactivateAction:function(t){if(this._isActiveAction(t)){for(var e=t._propertyBindings,n=0,i=e.length;n!==i;++n){var r=e[n];0===--r.useCount&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(t)}},_initMemoryManager:function(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;var t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}},_isActiveAction:function(t){var e=t._cacheIndex;return null!==e&&e1){var c=h[1];i[c]||(i[c]={start:1/0,end:-(1/0)});var l=i[c];al.end&&(l.end=a),e||(e=c)}}for(var c in i){var l=i[c];this.createAnimation(c,l.start,l.end,t)}this.firstAnimation=e},gn.prototype.setAnimationDirectionForward=function(t){var e=this.animationsMap[t];e&&(e.direction=1,e.directionBackwards=!1)},gn.prototype.setAnimationDirectionBackward=function(t){var e=this.animationsMap[t];e&&(e.direction=-1,e.directionBackwards=!0)},gn.prototype.setAnimationFPS=function(t,e){var n=this.animationsMap[t];n&&(n.fps=e,n.duration=(n.end-n.start)/n.fps)},gn.prototype.setAnimationDuration=function(t,e){var n=this.animationsMap[t];n&&(n.duration=e,n.fps=(n.end-n.start)/n.duration)},gn.prototype.setAnimationWeight=function(t,e){var n=this.animationsMap[t];n&&(n.weight=e)},gn.prototype.setAnimationTime=function(t,e){var n=this.animationsMap[t];n&&(n.time=e)},gn.prototype.getAnimationTime=function(t){var e=0,n=this.animationsMap[t];return n&&(e=n.time),e},gn.prototype.getAnimationDuration=function(t){var e=-1,n=this.animationsMap[t];return n&&(e=n.duration),e},gn.prototype.playAnimation=function(t){var e=this.animationsMap[t];e?(e.time=0,e.active=!0):console.warn("THREE.MorphBlendMesh: animation["+t+"] undefined in .playAnimation()")},gn.prototype.stopAnimation=function(t){var e=this.animationsMap[t];e&&(e.active=!1)},gn.prototype.update=function(e){for(var n=0,i=this.animationsList.length;nr.duration||r.time<0)&&(r.direction*=-1,r.time>r.duration&&(r.time=r.duration,r.directionBackwards=!0),r.time<0&&(r.time=0,r.directionBackwards=!1)):(r.time=r.time%r.duration,r.time<0&&(r.time+=r.duration));var o=r.start+t.Math.clamp(Math.floor(r.time/a),0,r.length-1),s=r.weight;o!==r.currentFrame&&(this.morphTargetInfluences[r.lastFrame]=0,this.morphTargetInfluences[r.currentFrame]=1*s,this.morphTargetInfluences[o]=0,r.lastFrame=r.currentFrame,r.currentFrame=o);var h=r.time%a/a;r.directionBackwards&&(h=1-h),r.currentFrame!==r.lastFrame?(this.morphTargetInfluences[r.currentFrame]=h*s,this.morphTargetInfluences[r.lastFrame]=(1-h)*s):this.morphTargetInfluences[r.currentFrame]=s}}},vn.prototype=Object.create(X.prototype),vn.prototype.constructor=vn,yn.prototype=Object.create(Q.prototype),yn.prototype.constructor=yn,xn.prototype=Object.create(Pt.prototype),xn.prototype.constructor=xn,bn.prototype=Object.create(Pt.prototype),bn.prototype.constructor=bn,bn.prototype.update=function(){var t=new s,e=new s,n=new T;return function(){var i=["a","b","c"];this.object.updateMatrixWorld(!0),n.getNormalMatrix(this.object.matrixWorld);var r=this.object.matrixWorld,a=this.geometry.attributes.position,o=this.object.geometry;if(o&&o.isGeometry)for(var s=o.vertices,h=o.faces,c=0,l=0,u=h.length;l.99999?this.quaternion.set(0,0,0,1):n.y<-.99999?this.quaternion.set(1,0,0,0):(e.set(n.z,0,-n.x).normalize(),t=Math.acos(n.y),this.quaternion.setFromAxisAngle(e,t))}}(),t.ArrowHelper.prototype.setLength=function(t,e,n){void 0===e&&(e=.2*t),void 0===n&&(n=.2*e),this.line.scale.set(1,Math.max(0,t-e),1),this.line.updateMatrix(),this.cone.scale.set(n,e,n),this.cone.position.y=t,this.cone.updateMatrix()},t.ArrowHelper.prototype.setColor=function(t){this.line.material.color.copy(t),this.cone.material.color.copy(t)},Fn.prototype=Object.create(Pt.prototype),Fn.prototype.constructor=Fn,Bn.prototype=Object.create(q.prototype),Bn.prototype.constructor=Bn,zn.prototype=Object.create(q.prototype),zn.prototype.constructor=zn,Gn.prototype=Object.create(zn.prototype),Gn.prototype.constructor=Gn,kn.prototype=Object.create(zn.prototype),kn.prototype.constructor=kn,Hn.prototype=Object.create(zn.prototype),Hn.prototype.constructor=Hn,Vn.prototype=Object.create(zn.prototype),Vn.prototype.constructor=Vn,jn.prototype=Object.create(Q.prototype),jn.prototype.constructor=jn,Wn.prototype=Object.create(q.prototype),Wn.prototype.constructor=Wn,Xn.prototype=Object.create(Q.prototype),Xn.prototype.constructor=Xn,Yn.prototype=Object.create(q.prototype),Yn.prototype.constructor=Yn,qn.prototype=Object.create(Fe.prototype),qn.prototype.constructor=qn,Zn.prototype=Object.create(Q.prototype),Zn.prototype.constructor=Zn,Jn.prototype=Object.create(q.prototype),Jn.prototype.constructor=Jn,Qn.prototype=Object.create(q.prototype),Qn.prototype.constructor=Qn,Kn.prototype=Object.create(Q.prototype),Kn.prototype.constructor=Kn,$n.prototype=Object.create(q.prototype),$n.prototype.constructor=$n,ti.prototype=Object.create(q.prototype),ti.prototype.constructor=ti,ei.prototype=Object.create(ti.prototype),ei.prototype.constructor=ei,ni.prototype=Object.create(Q.prototype),ni.prototype.constructor=ni,ii.prototype=Object.create(Q.prototype),ii.prototype.constructor=ii,ri.prototype=Object.create(q.prototype),ri.prototype.constructor=ri,t.CatmullRomCurve3=function(){function t(){}var e=new s,n=new t,i=new t,r=new t;return t.prototype.init=function(t,e,n,i){this.c0=t,this.c1=n,this.c2=-3*t+3*e-2*n-i,this.c3=2*t-2*e+n+i},t.prototype.initNonuniformCatmullRom=function(t,e,n,i,r,a,o){var s=(e-t)/r-(n-t)/(r+a)+(n-e)/a,h=(n-e)/a-(i-e)/(a+o)+(i-n)/o;s*=a,h*=a,this.init(e,n,s,h)},t.prototype.initCatmullRom=function(t,e,n,i,r){this.init(e,n,r*(n-t),r*(i-e))},t.prototype.calc=function(t){var e=t*t,n=e*t;return this.c0+this.c1*t+this.c2*e+this.c3*n},Re.create(function(t){this.points=t||[],this.closed=!1},function(t){var a,o,h,c,l=this.points;c=l.length,c<2&&console.log("duh, you need at least 2 points"),a=(c-(this.closed?0:1))*t,o=Math.floor(a),h=a-o,this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/l.length)+1)*l.length:0===h&&o===c-1&&(o=c-2,h=1);var u,d,p,f;if(this.closed||o>0?u=l[(o-1)%c]:(e.subVectors(l[0],l[1]).add(l[0]),u=e),d=l[o%c],p=l[(o+1)%c],this.closed||o+2n.length-2?n.length-1:r+1],l=n[r>n.length-3?n.length-1:r+2],u=t.CurveUtils.interpolate;return new s(u(o.x,h.x,c.x,l.x,a),u(o.y,h.y,c.y,l.y,a),u(o.z,h.z,c.z,l.z,a))}),t.CubicBezierCurve3=Re.create(function(t,e,n,i){this.v0=t,this.v1=e,this.v2=n,this.v3=i},function(e){var n=t.ShapeUtils.b3;return new s(n(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y),n(e,this.v0.z,this.v1.z,this.v2.z,this.v3.z))}),t.QuadraticBezierCurve3=Re.create(function(t,e,n){this.v0=t,this.v1=e,this.v2=n},function(e){var n=t.ShapeUtils.b2;return new s(n(e,this.v0.x,this.v1.x,this.v2.x),n(e,this.v0.y,this.v1.y,this.v2.y),n(e,this.v0.z,this.v1.z,this.v2.z))}),t.LineCurve3=Re.create(function(t,e){this.v1=t,this.v2=e},function(t){if(1===t)return this.v2.clone();var e=new s;return e.subVectors(this.v2,this.v1),e.multiplyScalar(t),e.add(this.v1),e}),oi.prototype=Object.create(Ue.prototype),oi.prototype.constructor=oi,t.SceneUtils={createMultiMaterialObject:function(t,e){for(var n=new Dt,i=0,r=e.length;i0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function o(t,e,i,n){this.isQuaternion=!0,this._x=t||0,this._y=e||0,this._z=i||0,this._w=void 0!==n?n:1}function s(t,e,i){this.isVector3=!0,this.x=t||0,this.y=e||0,this.z=i||0}function h(t,e){function i(){var t=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),e=new Uint16Array([0,1,2,0,2,3]);h=f.createBuffer(),c=f.createBuffer(),f.bindBuffer(f.ARRAY_BUFFER,h),f.bufferData(f.ARRAY_BUFFER,t,f.STATIC_DRAW),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c),f.bufferData(f.ELEMENT_ARRAY_BUFFER,e,f.STATIC_DRAW),l=r(),u={position:f.getAttribLocation(l,"position"),uv:f.getAttribLocation(l,"uv")},p={uvOffset:f.getUniformLocation(l,"uvOffset"),uvScale:f.getUniformLocation(l,"uvScale"),rotation:f.getUniformLocation(l,"rotation"),scale:f.getUniformLocation(l,"scale"),color:f.getUniformLocation(l,"color"),map:f.getUniformLocation(l,"map"),opacity:f.getUniformLocation(l,"opacity"),modelViewMatrix:f.getUniformLocation(l,"modelViewMatrix"),projectionMatrix:f.getUniformLocation(l,"projectionMatrix"),fogType:f.getUniformLocation(l,"fogType"),fogDensity:f.getUniformLocation(l,"fogDensity"),fogNear:f.getUniformLocation(l,"fogNear"),fogFar:f.getUniformLocation(l,"fogFar"),fogColor:f.getUniformLocation(l,"fogColor"),alphaTest:f.getUniformLocation(l,"alphaTest")};var i=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");i.width=8,i.height=8;var a=i.getContext("2d");a.fillStyle="white",a.fillRect(0,0,8,8),d=new n(i),d.needsUpdate=!0}function r(){var e=f.createProgram(),i=f.createShader(f.VERTEX_SHADER),n=f.createShader(f.FRAGMENT_SHADER);return f.shaderSource(i,["precision "+t.getPrecision()+" float;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float rotation;","uniform vec2 scale;","uniform vec2 uvOffset;","uniform vec2 uvScale;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","void main() {","vUV = uvOffset + uv * uvScale;","vec2 alignedPosition = position * scale;","vec2 rotatedPosition;","rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;","rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;","vec4 finalPosition;","finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );","finalPosition.xy += rotatedPosition;","finalPosition = projectionMatrix * finalPosition;","gl_Position = finalPosition;","}"].join("\n")),f.shaderSource(n,["precision "+t.getPrecision()+" float;","uniform vec3 color;","uniform sampler2D map;","uniform float opacity;","uniform int fogType;","uniform vec3 fogColor;","uniform float fogDensity;","uniform float fogNear;","uniform float fogFar;","uniform float alphaTest;","varying vec2 vUV;","void main() {","vec4 texture = texture2D( map, vUV );","if ( texture.a < alphaTest ) discard;","gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );","if ( fogType > 0 ) {","float depth = gl_FragCoord.z / gl_FragCoord.w;","float fogFactor = 0.0;","if ( fogType == 1 ) {","fogFactor = smoothstep( fogNear, fogFar, depth );","} else {","const float LOG2 = 1.442695;","fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","}","gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","}","}"].join("\n")),f.compileShader(i),f.compileShader(n),f.attachShader(e,i),f.attachShader(e,n),f.linkProgram(e),e}function a(t,e){return t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:e.id-t.id}this.isSpritePlugin=!0;var h,c,l,u,p,d,f=t.context,m=t.state,g=new s,v=new o,y=new s;this.render=function(n,r){if(0!==e.length){void 0===l&&i(),f.useProgram(l),m.initAttributes(),m.enableAttribute(u.position),m.enableAttribute(u.uv),m.disableUnusedAttributes(),m.disable(f.CULL_FACE),m.enable(f.BLEND),f.bindBuffer(f.ARRAY_BUFFER,h),f.vertexAttribPointer(u.position,2,f.FLOAT,!1,16,0),f.vertexAttribPointer(u.uv,2,f.FLOAT,!1,16,8),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c),f.uniformMatrix4fv(p.projectionMatrix,!1,r.projectionMatrix.elements),m.activeTexture(f.TEXTURE0),f.uniform1i(p.map,0);var o=0,s=0,x=n.fog;x?(f.uniform3f(p.fogColor,x.color.r,x.color.g,x.color.b),x&&x.isFog?(f.uniform1f(p.fogNear,x.near),f.uniform1f(p.fogFar,x.far),f.uniform1i(p.fogType,1),o=1,s=1):x&&x.isFogExp2&&(f.uniform1f(p.fogDensity,x.density),f.uniform1i(p.fogType,2),o=2,s=2)):(f.uniform1i(p.fogType,0),o=0,s=0);for(var b=0,_=e.length;b<_;b++){var w=e[b];w.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,w.matrixWorld),w.z=-w.modelViewMatrix.elements[14]}e.sort(a);for(var M=[],b=0,_=e.length;b<_;b++){var w=e[b],E=w.material;if(E.visible!==!1){f.uniform1f(p.alphaTest,E.alphaTest),f.uniformMatrix4fv(p.modelViewMatrix,!1,w.modelViewMatrix.elements),w.matrixWorld.decompose(g,v,y),M[0]=y.x,M[1]=y.y;var T=0;n.fog&&E.fog&&(T=s),o!==T&&(f.uniform1i(p.fogType,T),o=T),null!==E.map?(f.uniform2f(p.uvOffset,E.map.offset.x,E.map.offset.y),f.uniform2f(p.uvScale,E.map.repeat.x,E.map.repeat.y)):(f.uniform2f(p.uvOffset,0,0),f.uniform2f(p.uvScale,1,1)),f.uniform1f(p.opacity,E.opacity),f.uniform3f(p.color,E.color.r,E.color.g,E.color.b),f.uniform1f(p.rotation,E.rotation),f.uniform2fv(p.scale,M),m.setBlending(E.blending,E.blendEquation,E.blendSrc,E.blendDst),m.setDepthTest(E.depthTest),m.setDepthWrite(E.depthWrite),E.map?t.setTexture2D(E.map,0):t.setTexture2D(d,0),f.drawElements(f.TRIANGLES,6,f.UNSIGNED_SHORT,0)}}m.enable(f.CULL_FACE),t.resetGLState()}}}function c(t,e){this.isBox2=!0,this.min=void 0!==t?t:new i((+(1/0)),(+(1/0))),this.max=void 0!==e?e:new i((-(1/0)),(-(1/0)))}function l(t,e){function n(){var t=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),e=new Uint16Array([0,1,2,0,2,3]);a=m.createBuffer(),o=m.createBuffer(),m.bindBuffer(m.ARRAY_BUFFER,a),m.bufferData(m.ARRAY_BUFFER,t,m.STATIC_DRAW),m.bindBuffer(m.ELEMENT_ARRAY_BUFFER,o),m.bufferData(m.ELEMENT_ARRAY_BUFFER,e,m.STATIC_DRAW),d=m.createTexture(),f=m.createTexture(),g.bindTexture(m.TEXTURE_2D,d),m.texImage2D(m.TEXTURE_2D,0,m.RGB,16,16,0,m.RGB,m.UNSIGNED_BYTE,null),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_S,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_T,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MAG_FILTER,m.NEAREST),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MIN_FILTER,m.NEAREST),g.bindTexture(m.TEXTURE_2D,f),m.texImage2D(m.TEXTURE_2D,0,m.RGBA,16,16,0,m.RGBA,m.UNSIGNED_BYTE,null),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_S,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_T,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MAG_FILTER,m.NEAREST),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MIN_FILTER,m.NEAREST),h={vertexShader:["uniform lowp int renderType;","uniform vec3 screenPosition;","uniform vec2 scale;","uniform float rotation;","uniform sampler2D occlusionMap;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","varying float vVisibility;","void main() {","vUV = uv;","vec2 pos = position;","if ( renderType == 2 ) {","vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );","vVisibility = visibility.r / 9.0;","vVisibility *= 1.0 - visibility.g / 9.0;","vVisibility *= visibility.b / 9.0;","vVisibility *= 1.0 - visibility.a / 9.0;","pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;","pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;","}","gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );","}"].join("\n"),fragmentShader:["uniform lowp int renderType;","uniform sampler2D map;","uniform float opacity;","uniform vec3 color;","varying vec2 vUV;","varying float vVisibility;","void main() {","if ( renderType == 0 ) {","gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );","} else if ( renderType == 1 ) {","gl_FragColor = texture2D( map, vUV );","} else {","vec4 texture = texture2D( map, vUV );","texture.a *= opacity * vVisibility;","gl_FragColor = texture;","gl_FragColor.rgb *= color;","}","}"].join("\n")},l=r(h),u={vertex:m.getAttribLocation(l,"position"),uv:m.getAttribLocation(l,"uv")},p={renderType:m.getUniformLocation(l,"renderType"),map:m.getUniformLocation(l,"map"),occlusionMap:m.getUniformLocation(l,"occlusionMap"),opacity:m.getUniformLocation(l,"opacity"),color:m.getUniformLocation(l,"color"),scale:m.getUniformLocation(l,"scale"),rotation:m.getUniformLocation(l,"rotation"),screenPosition:m.getUniformLocation(l,"screenPosition")}}function r(e){var i=m.createProgram(),n=m.createShader(m.FRAGMENT_SHADER),r=m.createShader(m.VERTEX_SHADER),a="precision "+t.getPrecision()+" float;\n";return m.shaderSource(n,a+e.fragmentShader),m.shaderSource(r,a+e.vertexShader),m.compileShader(n),m.compileShader(r),m.attachShader(i,n),m.attachShader(i,r),m.linkProgram(i),i}this.isLensFlarePlugin=!0;var a,o,h,l,u,p,d,f,m=t.context,g=t.state;this.render=function(r,h,v){if(0!==e.length){var y=new s,x=v.w/v.z,b=.5*v.z,_=.5*v.w,w=16/v.w,M=new i(w*x,w),E=new s(1,1,0),T=new i(1,1),S=new c;S.min.set(0,0),S.max.set(v.z-16,v.w-16),void 0===l&&n(),m.useProgram(l),g.initAttributes(),g.enableAttribute(u.vertex),g.enableAttribute(u.uv),g.disableUnusedAttributes(),m.uniform1i(p.occlusionMap,0),m.uniform1i(p.map,1),m.bindBuffer(m.ARRAY_BUFFER,a),m.vertexAttribPointer(u.vertex,2,m.FLOAT,!1,16,0),m.vertexAttribPointer(u.uv,2,m.FLOAT,!1,16,8),m.bindBuffer(m.ELEMENT_ARRAY_BUFFER,o),g.disable(m.CULL_FACE),g.setDepthWrite(!1);for(var A=0,L=e.length;A.001&&U.scale>.001&&(E.x=U.x,E.y=U.y,E.z=U.z,w=U.size*U.scale/v.w,M.x=w*x,M.y=w,m.uniform3f(p.screenPosition,E.x,E.y,E.z),m.uniform2f(p.scale,M.x,M.y),m.uniform1f(p.rotation,U.rotation),m.uniform1f(p.opacity,U.opacity),m.uniform3f(p.color,U.color.r,U.color.g,U.color.b),g.setBlending(U.blending,U.blendEquation,U.blendSrc,U.blendDst),t.setTexture2D(U.texture,1),m.drawElements(m.TRIANGLES,6,m.UNSIGNED_SHORT,0))}}}g.enable(m.CULL_FACE),g.enable(m.DEPTH_TEST),g.setDepthWrite(!0),t.resetGLState()}}}function u(t,e,i,r,a,o,s,h,c,l){this.isCubeTexture=this.isTexture=!0,t=void 0!==t?t:[],e=void 0!==e?e:lr,n.call(this,t,e,i,r,a,o,s,h,c,l),this.flipY=!1}function p(e,i,n,r,a,o,s){function h(t,e){if(t.width>e||t.height>e){var i=e/Math.max(t.width,t.height),n=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");n.width=Math.floor(t.width*i),n.height=Math.floor(t.height*i);var r=n.getContext("2d");return r.drawImage(t,0,0,t.width,t.height,0,0,n.width,n.height),console.warn("THREE.WebGLRenderer: image is too big ("+t.width+"x"+t.height+"). Resized to "+n.width+"x"+n.height,t),n}return t}function c(e){return t.Math.isPowerOfTwo(e.width)&&t.Math.isPowerOfTwo(e.height)}function l(e){if(e instanceof HTMLImageElement||e instanceof HTMLCanvasElement){var i=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");i.width=t.Math.nearestPowerOfTwo(e.width),i.height=t.Math.nearestPowerOfTwo(e.height);var n=i.getContext("2d");return n.drawImage(e,0,0,i.width,i.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+e.width+"x"+e.height+"). Resized to "+i.width+"x"+i.height,e),i}return e}function u(t){return t.wrapS!==yr||t.wrapT!==yr||t.minFilter!==br&&t.minFilter!==Mr}function p(t){return t===br||t===_r||t===wr?e.NEAREST:e.LINEAR}function d(t){var e=t.target;e.removeEventListener("dispose",d),m(e),L.textures--}function f(t){var e=t.target;e.removeEventListener("dispose",f),g(e),L.textures--}function m(t){var i=r.get(t);if(t.image&&i.__image__webglTextureCube)e.deleteTexture(i.__image__webglTextureCube);else{if(void 0===i.__webglInit)return;e.deleteTexture(i.__webglTexture)}r.delete(t)}function g(t){var i=r.get(t),n=r.get(t.texture);if(t){if(void 0!==n.__webglTexture&&e.deleteTexture(n.__webglTexture),t.depthTexture&&t.depthTexture.dispose(),t&&t.isWebGLRenderTargetCube)for(var a=0;a<6;a++)e.deleteFramebuffer(i.__webglFramebuffer[a]),i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer[a]);else e.deleteFramebuffer(i.__webglFramebuffer),i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer);r.delete(t.texture),r.delete(t)}}function v(t,i){var a=r.get(t);if(t.version>0&&a.__version!==t.version){var o=t.image;if(void 0===o)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",t);else{if(o.complete!==!1)return void _(a,t,i);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",t)}}n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_2D,a.__webglTexture)}function y(t,i){var s=r.get(t);if(6===t.image.length)if(t.version>0&&s.__version!==t.version){s.__image__webglTextureCube||(t.addEventListener("dispose",d),s.__image__webglTextureCube=e.createTexture(),L.textures++),n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_CUBE_MAP,s.__image__webglTextureCube),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,t.flipY);for(var l=t&&t.isCompressedTexture,u=t.image[0]&&t.image[0].isDataTexture,p=[],f=0;f<6;f++)l||u?p[f]=u?t.image[f].image:t.image[f]:p[f]=h(t.image[f],a.maxCubemapSize);var m=p[0],g=c(m),v=o(t.format),y=o(t.type);b(e.TEXTURE_CUBE_MAP,t,g);for(var f=0;f<6;f++)if(l)for(var x,_=p[f].mipmaps,w=0,M=_.length;w-1?n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,w,v,x.width,x.height,0,x.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,w,v,x.width,x.height,0,v,y,x.data);else u?n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,v,p[f].width,p[f].height,0,v,y,p[f].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,v,v,y,p[f]);t.generateMipmaps&&g&&e.generateMipmap(e.TEXTURE_CUBE_MAP),s.__version=t.version,t.onUpdate&&t.onUpdate(t)}else n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_CUBE_MAP,s.__image__webglTextureCube)}function x(t,i){n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_CUBE_MAP,r.get(t).__webglTexture)}function b(t,n,s){var h;if(s?(e.texParameteri(t,e.TEXTURE_WRAP_S,o(n.wrapS)),e.texParameteri(t,e.TEXTURE_WRAP_T,o(n.wrapT)),e.texParameteri(t,e.TEXTURE_MAG_FILTER,o(n.magFilter)),e.texParameteri(t,e.TEXTURE_MIN_FILTER,o(n.minFilter))):(e.texParameteri(t,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(t,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),n.wrapS===yr&&n.wrapT===yr||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",n),e.texParameteri(t,e.TEXTURE_MAG_FILTER,p(n.magFilter)),e.texParameteri(t,e.TEXTURE_MIN_FILTER,p(n.minFilter)),n.minFilter!==br&&n.minFilter!==Mr&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",n)),h=i.get("EXT_texture_filter_anisotropic")){if(n.type===Ur&&null===i.get("OES_texture_float_linear"))return;if(n.type===Ir&&null===i.get("OES_texture_half_float_linear"))return;(n.anisotropy>1||r.get(n).__currentAnisotropy)&&(e.texParameterf(t,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(n.anisotropy,a.getMaxAnisotropy())),r.get(n).__currentAnisotropy=n.anisotropy)}}function _(t,i,r){void 0===t.__webglInit&&(t.__webglInit=!0,i.addEventListener("dispose",d),t.__webglTexture=e.createTexture(),L.textures++),n.activeTexture(e.TEXTURE0+r),n.bindTexture(e.TEXTURE_2D,t.__webglTexture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,i.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,i.unpackAlignment);var s=h(i.image,a.maxTextureSize);u(i)&&c(s)===!1&&(s=l(s));var p=c(s),f=o(i.format),m=o(i.type);b(e.TEXTURE_2D,i,p);var g,v=i.mipmaps;if(i&&i.isDepthTexture){var y=e.DEPTH_COMPONENT;if(i.type===Ur){if(!R)throw new Error("Float Depth Texture only supported in WebGL2.0");y=e.DEPTH_COMPONENT32F}else R&&(y=e.DEPTH_COMPONENT16);n.texImage2D(e.TEXTURE_2D,0,y,s.width,s.height,0,f,m,null)}else if(i&&i.isDataTexture)if(v.length>0&&p){for(var x=0,_=v.length;x<_;x++)g=v[x],n.texImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,f,m,g.data);i.generateMipmaps=!1}else n.texImage2D(e.TEXTURE_2D,0,f,s.width,s.height,0,f,m,s.data);else if(i&&i.isCompressedTexture)for(var x=0,_=v.length;x<_;x++)g=v[x],i.format!==zr&&i.format!==Br?n.getCompressedTextureFormats().indexOf(f)>-1?n.compressedTexImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,g.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):n.texImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,f,m,g.data);else if(v.length>0&&p){for(var x=0,_=v.length;x<_;x++)g=v[x],n.texImage2D(e.TEXTURE_2D,x,f,f,m,g);i.generateMipmaps=!1}else n.texImage2D(e.TEXTURE_2D,0,f,f,m,s);i.generateMipmaps&&p&&e.generateMipmap(e.TEXTURE_2D),t.__version=i.version,i.onUpdate&&i.onUpdate(i)}function w(t,i,a,s){var h=o(i.texture.format),c=o(i.texture.type);n.texImage2D(s,0,h,i.width,i.height,0,h,c,null),e.bindFramebuffer(e.FRAMEBUFFER,t),e.framebufferTexture2D(e.FRAMEBUFFER,a,s,r.get(i.texture).__webglTexture,0),e.bindFramebuffer(e.FRAMEBUFFER,null)}function M(t,i){e.bindRenderbuffer(e.RENDERBUFFER,t),i.depthBuffer&&!i.stencilBuffer?(e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,i.width,i.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t)):i.depthBuffer&&i.stencilBuffer?(e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_STENCIL,i.width,i.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,t)):e.renderbufferStorage(e.RENDERBUFFER,e.RGBA4,i.width,i.height),e.bindRenderbuffer(e.RENDERBUFFER,null)}function E(t,i){var n=i&&i.isWebGLRenderTargetCube;if(n)throw new Error("Depth Texture with cube render targets is not supported!");if(e.bindFramebuffer(e.FRAMEBUFFER,t),!i.depthTexture||!i.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");r.get(i.depthTexture).__webglTexture&&i.depthTexture.image.width===i.width&&i.depthTexture.image.height===i.height||(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),v(i.depthTexture,0);var a=r.get(i.depthTexture).__webglTexture;e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0)}function T(t){var i=r.get(t),n=t&&t.isWebGLRenderTargetCube;if(t.depthTexture){if(n)throw new Error("target.depthTexture not supported in Cube render targets");E(i.__webglFramebuffer,t)}else if(n){i.__webglDepthbuffer=[];for(var a=0;a<6;a++)e.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[a]),i.__webglDepthbuffer[a]=e.createRenderbuffer(),M(i.__webglDepthbuffer[a],t)}else e.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer=e.createRenderbuffer(),M(i.__webglDepthbuffer,t);e.bindFramebuffer(e.FRAMEBUFFER,null)}function S(t){var i=r.get(t),a=r.get(t.texture);t.addEventListener("dispose",f),a.__webglTexture=e.createTexture(),L.textures++;var o=t&&t.isWebGLRenderTargetCube,s=c(t);if(o){i.__webglFramebuffer=[];for(var h=0;h<6;h++)i.__webglFramebuffer[h]=e.createFramebuffer()}else i.__webglFramebuffer=e.createFramebuffer();if(o){n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture),b(e.TEXTURE_CUBE_MAP,t.texture,s);for(var h=0;h<6;h++)w(i.__webglFramebuffer[h],t,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+h);t.texture.generateMipmaps&&s&&e.generateMipmap(e.TEXTURE_CUBE_MAP),n.bindTexture(e.TEXTURE_CUBE_MAP,null)}else n.bindTexture(e.TEXTURE_2D,a.__webglTexture),b(e.TEXTURE_2D,t.texture,s),w(i.__webglFramebuffer,t,e.COLOR_ATTACHMENT0,e.TEXTURE_2D),t.texture.generateMipmaps&&s&&e.generateMipmap(e.TEXTURE_2D),n.bindTexture(e.TEXTURE_2D,null);t.depthBuffer&&T(t)}function A(t){var i=t.texture;if(i.generateMipmaps&&c(t)&&i.minFilter!==br&&i.minFilter!==Mr){var a=t&&t.isWebGLRenderTargetCube?e.TEXTURE_CUBE_MAP:e.TEXTURE_2D,o=r.get(i).__webglTexture;n.bindTexture(a,o),e.generateMipmap(a),n.bindTexture(a,null)}}this.isWebGLTextures=!0;var L=s.memory,R="undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext;this.setTexture2D=v,this.setTextureCube=y,this.setTextureCubeDynamic=x,this.setupRenderTarget=S,this.updateRenderTargetMipmap=A}function d(t,e,i,n){this.isVector4=!0,this.x=t||0,this.y=e||0,this.z=i||0,this.w=void 0!==n?n:1}function f(t,e,i){function n(e,i,n){var r=new Uint8Array(4),a=t.createTexture();t.bindTexture(e,a),t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST);for(var o=0;o0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function A(t,e){this.isPlane=!0,this.normal=void 0!==t?t:new s(1,0,0),this.constant=void 0!==e?e:0}function L(t,e,i,n,r,a){this.isFrustum=!0,this.planes=[void 0!==t?t:new A,void 0!==e?e:new A,void 0!==i?i:new A,void 0!==n?n:new A,void 0!==r?r:new A,void 0!==a?a:new A]}function R(e,n,r,o){function h(t,i,n,r){var a=t.geometry,o=null,s=A,h=t.customDepthMaterial;if(n&&(s=R,h=t.customDistanceMaterial),h)o=h;else{var c=!1;i.morphTargets&&(a&&a.isBufferGeometry?c=a.morphAttributes&&a.morphAttributes.position&&a.morphAttributes.position.length>0:a&&a.isGeometry&&(c=a.morphTargets&&a.morphTargets.length>0));var l=t&&t.isSkinnedMesh&&i.skinning,u=0;c&&(u|=E),l&&(u|=T),o=s[u]}if(e.localClippingEnabled&&i.clipShadows===!0&&0!==i.clippingPlanes.length){var p=o.uuid,d=i.uuid,f=P[p];void 0===f&&(f={},P[p]=f);var m=f[d];void 0===m&&(m=o.clone(),f[d]=m),o=m}o.visible=i.visible,o.wireframe=i.wireframe;var g=i.side;return V.renderSingleSided&&g==xn&&(g=vn),V.renderReverseSided&&(g===vn?g=yn:g===yn&&(g=vn)),o.side=g,o.clipShadows=i.clipShadows,o.clippingPlanes=i.clippingPlanes,o.wireframeLinewidth=i.wireframeLinewidth,o.linewidth=i.linewidth,n&&void 0!==o.uniforms.lightPos&&o.uniforms.lightPos.value.copy(r),o}function c(t,e,i){if(t.visible!==!1){if(t.layers.test(e.layers)&&(t&&t.isMesh||t&&t.isLine||t&&t.isPoints)&&t.castShadow&&(t.frustumCulled===!1||p.intersectsObject(t)===!0)){var n=t.material;n.visible===!0&&(t.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,t.matrixWorld),w.push(t))}for(var r=t.children,a=0,o=r.length;a0,shadowMapType:e.shadowMap.type,toneMapping:e.toneMapping,physicallyCorrectLights:e.physicallyCorrectLights,premultipliedAlpha:t.premultipliedAlpha,alphaTest:t.alphaTest,doubleSided:t.side===xn,flipSided:t.side===yn,depthPacking:void 0!==t.depthPacking&&t.depthPacking};return f},this.getProgramCode=function(t,e){var i=[];if(e.shaderID?i.push(e.shaderID):(i.push(t.fragmentShader),i.push(t.vertexShader)),void 0!==t.defines)for(var n in t.defines)i.push(n),i.push(t.defines[n]);for(var r=0;r65535?Uint32Array:Uint16Array,y=new U(new v(a),1);return r(y,t.ELEMENT_ARRAY_BUFFER),n.wireframe=y,y}function c(t,e,i){if(e>i){var n=e;e=i,i=n}var r=t[e];return void 0===r?(t[e]=[i],!0):r.indexOf(i)===-1&&(r.push(i),!0)}this.isWebGLObjects=!0;var l=new K(t,e,i);this.getAttributeBuffer=s,this.getWireframeAttribute=h,this.update=n}function tt(){this.isWebGLLights=!0;var t={};this.get=function(e){if(void 0!==t[e.id])return t[e.id];var n;switch(e.type){case"DirectionalLight":n={direction:new s,color:new w,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"SpotLight":n={position:new s,direction:new s,color:new w,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"PointLight":n={position:new s,color:new w,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"HemisphereLight":n={direction:new s,skyColor:new w,groundColor:new w}}return t[e.id]=n,n}}function et(t,e,i){function n(){if(void 0!==a)return a;var i=e.get("EXT_texture_filter_anisotropic");return a=null!==i?t.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}function r(e){if("highp"===e){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}this.isWebGLCapabilities=!0;var a;this.getMaxAnisotropy=n,this.getMaxPrecision=r,this.precision=void 0!==i.precision?i.precision:"highp",this.logarithmicDepthBuffer=void 0!==i.logarithmicDepthBuffer&&i.logarithmicDepthBuffer,this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubemapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxAttributes=t.getParameter(t.MAX_VERTEX_ATTRIBS),this.maxVertexUniforms=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.maxVaryings=t.getParameter(t.MAX_VARYING_VECTORS),this.maxFragmentUniforms=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.vertexTextures=this.maxVertexTextures>0,this.floatFragmentTextures=!!e.get("OES_texture_float"),this.floatVertexTextures=this.vertexTextures&&this.floatFragmentTextures;var o=r(this.precision);o!==this.precision&&(console.warn("THREE.WebGLRenderer:",this.precision,"not supported, using",o,"instead."),this.precision=o),this.logarithmicDepthBuffer&&(this.logarithmicDepthBuffer=!!e.get("EXT_frag_depth"))}function it(t){this.isWebGLExtensions=!0;var e={};this.get=function(i){if(void 0!==e[i])return e[i];var n;switch(i){case"WEBGL_depth_texture":n=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case"WEBGL_compressed_texture_etc1":n=t.getExtension("WEBGL_compressed_texture_etc1");break;default:n=t.getExtension(i)}return null===n&&console.warn("THREE.WebGLRenderer: "+i+" extension not supported."),e[i]=n,n}}function nt(t,e,i){function n(t){s=t}function r(i){i.array instanceof Uint32Array&&e.get("OES_element_index_uint")?(h=t.UNSIGNED_INT,c=4):(h=t.UNSIGNED_SHORT,c=2)}function a(e,n){t.drawElements(s,n,h,e*c),i.calls++,i.vertices+=n,s===t.TRIANGLES&&(i.faces+=n/3)}function o(n,r,a){var o=e.get("ANGLE_instanced_arrays");return null===o?void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(o.drawElementsInstancedANGLE(s,a,h,r*c,n.maxInstancedCount),i.calls++,i.vertices+=a*n.maxInstancedCount,void(s===t.TRIANGLES&&(i.faces+=n.maxInstancedCount*a/3)))}this.isWebGLIndexedBufferRenderer=!0;var s,h,c;this.setMode=n,this.setIndex=r,this.render=a,this.renderInstances=o}function rt(){function t(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),i.numPlanes=r}function e(t,e,n,r){var a=null!==t?t.length:0,o=null;if(0!==a){if(o=c.value,r!==!0||null===o){var l=n+4*a,u=e.matrixWorldInverse;h.getNormalMatrix(u),(null===o||o.length0?1:-1,m[v]=C.x,m[v+1]=C.y,m[v+2]=C.z,g[y]=D/c,g[y+1]=1-U/u,v+=3,y+=2,R+=1}for(U=0;U65535?Uint32Array:Uint16Array)(p),f=new Float32Array(3*u),m=new Float32Array(3*u),g=new Float32Array(2*u),v=0,y=0,x=0,b=0,_=0;c("z","y","x",-1,-1,i,e,t,a,r,0),c("z","y","x",1,-1,i,e,-t,a,r,1),c("x","z","y",1,1,t,i,e,n,a,2),c("x","z","y",1,-1,t,i,-e,n,a,3),c("x","y","z",1,-1,t,e,i,n,r,4),c("x","y","z",-1,-1,t,e,-i,n,r,5),this.setIndex(new U(d,1)),this.addAttribute("position",new U(f,3)),this.addAttribute("normal",new U(m,3)),this.addAttribute("uv",new U(g,2))}function ht(t,e){this.isRay=!0,this.origin=void 0!==t?t:new s,this.direction=void 0!==e?e:new s}function ct(t,e){this.isLine3=!0,this.start=void 0!==t?t:new s,this.end=void 0!==e?e:new s}function lt(t,e,i){this.isTriangle=!0,this.a=void 0!==t?t:new s,this.b=void 0!==e?e:new s,this.c=void 0!==i?i:new s}function ut(t){this.isMeshBasicMaterial=this.isMaterial=!0,x.call(this),this.type="MeshBasicMaterial",this.color=new w(16777215),this.map=null,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.lights=!1,this.setValues(t)}function pt(t,e){this.isMesh=!0,X.call(this),this.type="Mesh",this.geometry=void 0!==t?t:new Q,this.material=void 0!==e?e:new ut({color:16777215*Math.random()}),this.drawMode=ha,this.updateMorphTargets()}function dt(t,e,i,n){this.isPlaneBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="PlaneBufferGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:n};for(var r=t/2,a=e/2,o=Math.floor(i)||1,s=Math.floor(n)||1,h=o+1,c=s+1,l=t/o,u=e/s,p=new Float32Array(h*c*3),d=new Float32Array(h*c*3),f=new Float32Array(h*c*2),m=0,g=0,v=0;v65535?Uint32Array:Uint16Array)(o*s*6),v=0;v=0){var l=a[h];if(void 0!==l){var u=ee.FLOAT,p=l.array,d=l.normalized;p instanceof Float32Array?u=ee.FLOAT:p instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):p instanceof Uint16Array?u=ee.UNSIGNED_SHORT:p instanceof Int16Array?u=ee.SHORT:p instanceof Uint32Array?u=ee.UNSIGNED_INT:p instanceof Int32Array?u=ee.INT:p instanceof Int8Array?u=ee.BYTE:p instanceof Uint8Array&&(u=ee.UNSIGNED_BYTE);var f=l.itemSize,m=he.getAttributeBuffer(l);if(l&&l.isInterleavedBufferAttribute){var g=l.data,v=g.stride,y=l.offset;g&&g.isInstancedInterleavedBuffer?(ae.enableAttributeAndDivisor(c,g.meshPerAttribute,r),void 0===i.maxInstancedCount&&(i.maxInstancedCount=g.meshPerAttribute*g.count)):ae.enableAttribute(c),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(c,f,u,d,v*g.array.BYTES_PER_ELEMENT,(n*v+y)*g.array.BYTES_PER_ELEMENT)}else l&&l.isInstancedBufferAttribute?(ae.enableAttributeAndDivisor(c,l.meshPerAttribute,r),void 0===i.maxInstancedCount&&(i.maxInstancedCount=l.meshPerAttribute*l.count)):ae.enableAttribute(c),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(c,f,u,d,0,n*f*l.array.BYTES_PER_ELEMENT)}else if(void 0!==s){var x=s[h];if(void 0!==x)switch(x.length){case 2:ee.vertexAttrib2fv(c,x);break;case 3:ee.vertexAttrib3fv(c,x);break;case 4:ee.vertexAttrib4fv(c,x);break;default:ee.vertexAttrib1fv(c,x)}}}}ae.disableUnusedAttributes()}function y(t,e){return Math.abs(e[0])-Math.abs(t[0])}function x(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.material.program&&e.material.program&&t.material.program!==e.material.program?t.material.program.id-e.material.program.id:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function b(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function M(t,e,i,n,r){var a,o;i.transparent?(a=wt,o=++Mt):(a=bt,o=++_t);var s=a[o];void 0!==s?(s.id=t.id,s.object=t,s.geometry=e,s.material=i,s.z=Kt.z,s.group=r):(s={id:t.id,object:t,geometry:e,material:i,z:Kt.z,group:r},a.push(s))}function E(t){var e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),Jt.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),A(Jt)}function S(t){return Jt.center.set(0,0,0),Jt.radius=.7071067811865476,Jt.applyMatrix4(t.matrixWorld),A(Jt)}function A(t){if(!Xt.intersectsSphere(t))return!1;var e=Yt.numPlanes;if(0===e)return!0;var i=At.clippingPlanes,n=t.center,r=-t.radius,a=0;do if(i[a].distanceToPoint(n)=0&&e.numSupportedMorphTargets++}if(e.morphNormals){e.numSupportedMorphNormals=0;for(var p=0;p=0&&e.numSupportedMorphNormals++}var d=r.__webglShader.uniforms;(e&&e.isShaderMaterial||e&&e.isRawShaderMaterial)&&e.clipping!==!0||(r.numClippingPlanes=Yt.numPlanes,d.clippingPlanes=Yt.uniform),e.lights&&(r.lightsHash=$t.hash,d.ambientLightColor.value=$t.ambient,d.directionalLights.value=$t.directional,d.spotLights.value=$t.spot,d.pointLights.value=$t.point,d.hemisphereLights.value=$t.hemi,d.directionalShadowMap.value=$t.directionalShadowMap,d.directionalShadowMatrix.value=$t.directionalShadowMatrix,d.spotShadowMap.value=$t.spotShadowMap, +d.spotShadowMatrix.value=$t.spotShadowMatrix,d.pointShadowMap.value=$t.pointShadowMap,d.pointShadowMatrix.value=$t.pointShadowMatrix);var f=r.program.getUniforms(),m=t.WebGLUniforms.seqWithValue(f.seq,d);r.uniformsList=m,r.dynamicUniforms=t.WebGLUniforms.splitDynamic(m,d)}function N(t){t.side!==xn?ae.enable(ee.CULL_FACE):ae.disable(ee.CULL_FACE),ae.setFlipSided(t.side===yn),t.transparent===!0?ae.setBlending(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.premultipliedAlpha):ae.setBlending(Tn),ae.setDepthFunc(t.depthFunc),ae.setDepthTest(t.depthTest),ae.setDepthWrite(t.depthWrite),ae.setColorWrite(t.colorWrite),ae.setPolygonOffset(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits)}function O(e,i,n,r){Ft=0;var a=oe.get(n);if(qt){if(Zt||e!==It){var o=e===It&&n.id===Ct;Yt.setState(n.clippingPlanes,n.clipShadows,e,a,o)}void 0!==a.numClippingPlanes&&a.numClippingPlanes!==Yt.numPlanes&&(n.needsUpdate=!0)}void 0===a.program&&(n.needsUpdate=!0),void 0!==a.lightsHash&&a.lightsHash!==$t.hash&&(n.needsUpdate=!0),n.needsUpdate&&(D(n,i,r),n.needsUpdate=!1);var s=!1,h=!1,c=!1,l=a.program,u=l.getUniforms(),p=a.__webglShader.uniforms;if(l.id!==Lt&&(ee.useProgram(l.program),Lt=l.id,s=!0,h=!0,c=!0),n.id!==Ct&&(Ct=n.id,h=!0),s||e!==It){if(u.set(ee,e,"projectionMatrix"),re.logarithmicDepthBuffer&&u.setValue(ee,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),e!==It&&(It=e,h=!0,c=!0),n&&n.isShaderMaterial||n&&n.isMeshPhongMaterial||n&&n.isMeshStandardMaterial||n.envMap){var d=u.map.cameraPosition;void 0!==d&&d.setValue(ee,Kt.setFromMatrixPosition(e.matrixWorld))}(n&&n.isMeshPhongMaterial||n&&n.isMeshLambertMaterial||n&&n.isMeshBasicMaterial||n&&n.isMeshStandardMaterial||n&&n.isShaderMaterial||n.skinning)&&u.setValue(ee,"viewMatrix",e.matrixWorldInverse),u.set(ee,At,"toneMappingExposure"),u.set(ee,At,"toneMappingWhitePoint")}if(n.skinning){u.setOptional(ee,r,"bindMatrix"),u.setOptional(ee,r,"bindMatrixInverse");var f=r.skeleton;f&&(re.floatVertexTextures&&f.useVertexTexture?(u.set(ee,f,"boneTexture"),u.set(ee,f,"boneTextureWidth"),u.set(ee,f,"boneTextureHeight")):u.setOptional(ee,f,"boneMatrices"))}h&&(n.lights&&X(p,c),i&&n.fog&&H(p,i),(n&&n.isMeshBasicMaterial||n&&n.isMeshLambertMaterial||n&&n.isMeshPhongMaterial||n&&n.isMeshStandardMaterial||n&&n.isMeshDepthMaterial)&&F(p,n),n&&n.isLineBasicMaterial?B(p,n):n&&n.isLineDashedMaterial?(B(p,n),z(p,n)):n&&n.isPointsMaterial?G(p,n):n&&n.isMeshLambertMaterial?V(p,n):n&&n.isMeshPhongMaterial?k(p,n):n&&n.isMeshPhysicalMaterial?W(p,n):n&&n.isMeshStandardMaterial?j(p,n):n&&n.isMeshDepthMaterial?n.displacementMap&&(p.displacementMap.value=n.displacementMap,p.displacementScale.value=n.displacementScale,p.displacementBias.value=n.displacementBias):n&&n.isMeshNormalMaterial&&(p.opacity.value=n.opacity),t.WebGLUniforms.upload(ee,a.uniformsList,p,At)),u.set(ee,r,"modelViewMatrix"),u.set(ee,r,"normalMatrix"),u.setValue(ee,"modelMatrix",r.matrixWorld);var m=a.dynamicUniforms;return null!==m&&(t.WebGLUniforms.evalDynamic(m,p,r,e),t.WebGLUniforms.upload(ee,m,p,At)),l}function F(t,e){t.opacity.value=e.opacity,t.diffuse.value=e.color,e.emissive&&t.emissive.value.copy(e.emissive).multiplyScalar(e.emissiveIntensity),t.map.value=e.map,t.specularMap.value=e.specularMap,t.alphaMap.value=e.alphaMap,e.aoMap&&(t.aoMap.value=e.aoMap,t.aoMapIntensity.value=e.aoMapIntensity);var i;if(e.map?i=e.map:e.specularMap?i=e.specularMap:e.displacementMap?i=e.displacementMap:e.normalMap?i=e.normalMap:e.bumpMap?i=e.bumpMap:e.roughnessMap?i=e.roughnessMap:e.metalnessMap?i=e.metalnessMap:e.alphaMap?i=e.alphaMap:e.emissiveMap&&(i=e.emissiveMap),void 0!==i){i&&i.isWebGLRenderTarget&&(i=i.texture);var n=i.offset,r=i.repeat;t.offsetRepeat.value.set(n.x,n.y,r.x,r.y)}t.envMap.value=e.envMap,t.flipEnvMap.value=e.envMap&&e.envMap.isCubeTexture?-1:1,t.reflectivity.value=e.reflectivity,t.refractionRatio.value=e.refractionRatio}function B(t,e){t.diffuse.value=e.color,t.opacity.value=e.opacity}function z(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}function G(t,e){if(t.diffuse.value=e.color,t.opacity.value=e.opacity,t.size.value=e.size*Vt,t.scale.value=.5*K.clientHeight,t.map.value=e.map,null!==e.map){var i=e.map.offset,n=e.map.repeat;t.offsetRepeat.value.set(i.x,i.y,n.x,n.y)}}function H(t,e){t.fogColor.value=e.color,e&&e.isFog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e&&e.isFogExp2&&(t.fogDensity.value=e.density)}function V(t,e){e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap)}function k(t,e){t.specular.value=e.specular,t.shininess.value=Math.max(e.shininess,1e-4),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}function j(t,e){t.roughness.value=e.roughness,t.metalness.value=e.metalness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap),e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias),e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}function W(t,e){t.clearCoat.value=e.clearCoat,t.clearCoatRoughness.value=e.clearCoatRoughness,j(t,e)}function X(t,e){t.ambientLightColor.needsUpdate=e,t.directionalLights.needsUpdate=e,t.pointLights.needsUpdate=e,t.spotLights.needsUpdate=e,t.hemisphereLights.needsUpdate=e}function Y(t){for(var e=0,i=0,n=t.length;i=re.maxTextures&&console.warn("WebGLRenderer: trying to use "+t+" texture units while this GPU supports only "+re.maxTextures),Ft+=1,t}function J(t){var e;if(t===vr)return ee.REPEAT;if(t===yr)return ee.CLAMP_TO_EDGE;if(t===xr)return ee.MIRRORED_REPEAT;if(t===br)return ee.NEAREST;if(t===_r)return ee.NEAREST_MIPMAP_NEAREST;if(t===wr)return ee.NEAREST_MIPMAP_LINEAR;if(t===Mr)return ee.LINEAR;if(t===Er)return ee.LINEAR_MIPMAP_NEAREST;if(t===Tr)return ee.LINEAR_MIPMAP_LINEAR;if(t===Sr)return ee.UNSIGNED_BYTE;if(t===Dr)return ee.UNSIGNED_SHORT_4_4_4_4;if(t===Nr)return ee.UNSIGNED_SHORT_5_5_5_1;if(t===Or)return ee.UNSIGNED_SHORT_5_6_5;if(t===Ar)return ee.BYTE;if(t===Lr)return ee.SHORT;if(t===Rr)return ee.UNSIGNED_SHORT;if(t===Pr)return ee.INT;if(t===Cr)return ee.UNSIGNED_INT;if(t===Ur)return ee.FLOAT;if(e=ne.get("OES_texture_half_float"),null!==e&&t===Ir)return e.HALF_FLOAT_OES;if(t===Fr)return ee.ALPHA;if(t===Br)return ee.RGB;if(t===zr)return ee.RGBA;if(t===Gr)return ee.LUMINANCE;if(t===Hr)return ee.LUMINANCE_ALPHA;if(t===kr)return ee.DEPTH_COMPONENT;if(t===Cn)return ee.FUNC_ADD;if(t===Un)return ee.FUNC_SUBTRACT;if(t===In)return ee.FUNC_REVERSE_SUBTRACT;if(t===On)return ee.ZERO;if(t===Fn)return ee.ONE;if(t===Bn)return ee.SRC_COLOR;if(t===zn)return ee.ONE_MINUS_SRC_COLOR;if(t===Gn)return ee.SRC_ALPHA;if(t===Hn)return ee.ONE_MINUS_SRC_ALPHA;if(t===Vn)return ee.DST_ALPHA;if(t===kn)return ee.ONE_MINUS_DST_ALPHA;if(t===jn)return ee.DST_COLOR;if(t===Wn)return ee.ONE_MINUS_DST_COLOR;if(t===Xn)return ee.SRC_ALPHA_SATURATE;if(e=ne.get("WEBGL_compressed_texture_s3tc"),null!==e){if(t===jr)return e.COMPRESSED_RGB_S3TC_DXT1_EXT;if(t===Wr)return e.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(t===Xr)return e.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(t===Yr)return e.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e=ne.get("WEBGL_compressed_texture_pvrtc"),null!==e){if(t===qr)return e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(t===Zr)return e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(t===Jr)return e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(t===Qr)return e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e=ne.get("WEBGL_compressed_texture_etc1"),null!==e&&t===Kr)return e.COMPRESSED_RGB_ETC1_WEBGL;if(e=ne.get("EXT_blend_minmax"),null!==e){if(t===Dn)return e.MIN_EXT;if(t===Nn)return e.MAX_EXT}return 0}this.isWebGLRenderer=!0,console.log("THREE.WebGLRenderer","79dev"),e=e||{};var K=void 0!==e.canvas?e.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),ot=void 0!==e.context?e.context:null,ht=void 0!==e.alpha&&e.alpha,ct=void 0===e.depth||e.depth,lt=void 0===e.stencil||e.stencil,ft=void 0!==e.antialias&&e.antialias,vt=void 0===e.premultipliedAlpha||e.premultipliedAlpha,yt=void 0!==e.preserveDrawingBuffer&&e.preserveDrawingBuffer,xt=[],bt=[],_t=-1,wt=[],Mt=-1,Et=new Float32Array(8),Tt=[],St=[];this.domElement=K,this.context=null,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.gammaFactor=2,this.gammaInput=!1,this.gammaOutput=!1,this.physicallyCorrectLights=!1,this.toneMapping=ar,this.toneMappingExposure=1,this.toneMappingWhitePoint=1,this.maxMorphTargets=8,this.maxMorphNormals=4;var At=this,Lt=null,Rt=null,Pt=null,Ct=-1,Ut="",It=null,Dt=new d,Nt=null,Ot=new d,Ft=0,Bt=new w(0),zt=0,Gt=K.width,Ht=K.height,Vt=1,kt=new d(0,0,Gt,Ht),jt=!1,Wt=new d(0,0,Gt,Ht),Xt=new L,Yt=new rt,qt=!1,Zt=!1,Jt=new T,Qt=new a,Kt=new s,$t={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},te={calls:0,vertices:0,faces:0,points:0};this.info={render:te,memory:{geometries:0,textures:0},programs:null};var ee;try{var ie={alpha:ht,depth:ct,stencil:lt,antialias:ft,premultipliedAlpha:vt,preserveDrawingBuffer:yt};if(ee=ot||K.getContext("webgl",ie)||K.getContext("experimental-webgl",ie),null===ee)throw null!==K.getContext("webgl")?"Error creating WebGL context with your selected attributes.":"Error creating WebGL context.";void 0===ee.getShaderPrecisionFormat&&(ee.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}}),K.addEventListener("webglcontextlost",c,!1)}catch(t){console.error("THREE.WebGLRenderer: "+t)}var ne=new it(ee);ne.get("WEBGL_depth_texture"),ne.get("OES_texture_float"),ne.get("OES_texture_float_linear"),ne.get("OES_texture_half_float"),ne.get("OES_texture_half_float_linear"),ne.get("OES_standard_derivatives"),ne.get("ANGLE_instanced_arrays"),ne.get("OES_element_index_uint")&&(Q.MaxIndex=4294967296);var re=new et(ee,ne,e),ae=new f(ee,ne,J),oe=new P,se=new p(ee,ne,ae,oe,re,J,this.info),he=new $(ee,oe,this.info),ce=new C(this,re),le=new tt;this.info.programs=ce.programs;var ue=new at(ee,ne,te),pe=new nt(ee,ne,te),de=new gt((-1),1,1,(-1),0,1),fe=new mt,me=new pt(new dt(2,2),new ut({depthTest:!1,depthWrite:!1,fog:!1})),ge=t.ShaderLib.cube,ve=new pt(new st(5,5,5),new _({uniforms:ge.uniforms,vertexShader:ge.vertexShader,fragmentShader:ge.fragmentShader,side:yn,depthTest:!1,depthWrite:!1,fog:!1}));r(),this.context=ee,this.capabilities=re,this.extensions=ne,this.properties=oe,this.state=ae;var ye=new R(this,$t,he,re);this.shadowMap=ye;var xe=new h(this,Tt),be=new l(this,St);this.getContext=function(){return ee},this.getContextAttributes=function(){return ee.getContextAttributes()},this.forceContextLoss=function(){ne.get("WEBGL_lose_context").loseContext()},this.getMaxAnisotropy=function(){return re.getMaxAnisotropy()},this.getPrecision=function(){return re.precision},this.getPixelRatio=function(){return Vt},this.setPixelRatio=function(t){void 0!==t&&(Vt=t,this.setSize(Wt.z,Wt.w,!1))},this.getSize=function(){return{width:Gt,height:Ht}},this.setSize=function(t,e,i){Gt=t,Ht=e,K.width=t*Vt,K.height=e*Vt,i!==!1&&(K.style.width=t+"px",K.style.height=e+"px"),this.setViewport(0,0,t,e)},this.setViewport=function(t,e,i,n){ae.viewport(Wt.set(t,e,i,n))},this.setScissor=function(t,e,i,n){ae.scissor(kt.set(t,e,i,n))},this.setScissorTest=function(t){ae.setScissorTest(jt=t)},this.getClearColor=function(){return Bt},this.setClearColor=function(t,e){Bt.set(t),zt=void 0!==e?e:1,n(Bt.r,Bt.g,Bt.b,zt)},this.getClearAlpha=function(){return zt},this.setClearAlpha=function(t){zt=t,n(Bt.r,Bt.g,Bt.b,zt)},this.clear=function(t,e,i){var n=0;(void 0===t||t)&&(n|=ee.COLOR_BUFFER_BIT),(void 0===e||e)&&(n|=ee.DEPTH_BUFFER_BIT),(void 0===i||i)&&(n|=ee.STENCIL_BUFFER_BIT),ee.clear(n)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.clearTarget=function(t,e,i,n){this.setRenderTarget(t),this.clear(e,i,n)},this.resetGLState=o,this.dispose=function(){wt=[],Mt=-1,bt=[],_t=-1,K.removeEventListener("webglcontextlost",c,!1)},this.renderBufferImmediate=function(t,e,i){ae.initAttributes();var n=oe.get(t);t.hasPositions&&!n.position&&(n.position=ee.createBuffer()),t.hasNormals&&!n.normal&&(n.normal=ee.createBuffer()),t.hasUvs&&!n.uv&&(n.uv=ee.createBuffer()),t.hasColors&&!n.color&&(n.color=ee.createBuffer());var r=e.getAttributes();if(t.hasPositions&&(ee.bindBuffer(ee.ARRAY_BUFFER,n.position),ee.bufferData(ee.ARRAY_BUFFER,t.positionArray,ee.DYNAMIC_DRAW),ae.enableAttribute(r.position),ee.vertexAttribPointer(r.position,3,ee.FLOAT,!1,0,0)),t.hasNormals){if(ee.bindBuffer(ee.ARRAY_BUFFER,n.normal),"MeshPhongMaterial"!==i.type&&"MeshStandardMaterial"!==i.type&&"MeshPhysicalMaterial"!==i.type&&i.shading===bn)for(var a=0,o=3*t.count;a8&&(u.length=8);for(var m=n.morphAttributes,p=0,d=u.length;p0&&b.renderInstances(n,A,R):b.render(A,R)},this.render=function(t,e,i,r){if((e&&e.isCamera)===!1)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");var a=t.fog;Ut="",Ct=-1,It=null,t.autoUpdate===!0&&t.updateMatrixWorld(),null===e.parent&&e.updateMatrixWorld(),e.matrixWorldInverse.getInverse(e.matrixWorld),Qt.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Xt.setFromMatrix(Qt),xt.length=0,_t=-1,Mt=-1,Tt.length=0,St.length=0,Zt=this.localClippingEnabled,qt=Yt.init(this.clippingPlanes,Zt,e),U(t,e),bt.length=_t+1,wt.length=Mt+1,At.sortObjects===!0&&(bt.sort(x),wt.sort(b)),qt&&Yt.beginShadows(),Y(xt),ye.render(t,e),q(xt,e),qt&&Yt.endShadows(),te.calls=0,te.vertices=0,te.faces=0,te.points=0,void 0===i&&(i=null),this.setRenderTarget(i);var o=t.background;if(null===o?n(Bt.r,Bt.g,Bt.b,zt):o&&o.isColor&&n(o.r,o.g,o.b,1),(this.autoClear||r)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil),o&&o.isCubeTexture?(fe.projectionMatrix.copy(e.projectionMatrix),fe.matrixWorld.extractRotation(e.matrixWorld),fe.matrixWorldInverse.getInverse(fe.matrixWorld),ve.material.uniforms.tCube.value=o,ve.modelViewMatrix.multiplyMatrices(fe.matrixWorldInverse,ve.matrixWorld),he.update(ve),At.renderBufferDirect(fe,null,ve.geometry,ve.material,ve,null)):o&&o.isTexture&&(me.material.map=o,he.update(me),At.renderBufferDirect(de,null,me.geometry,me.material,me,null)),t.overrideMaterial){var s=t.overrideMaterial;I(bt,e,a,s),I(wt,e,a,s)}else ae.setBlending(Tn),I(bt,e,a),I(wt,e,a);xe.render(t,e),be.render(t,e,Ot),i&&se.updateRenderTargetMipmap(i),ae.setDepthTest(!0),ae.setDepthWrite(!0),ae.setColorWrite(!0)},this.setFaceCulling=function(t,e){ae.setCullFace(t),ae.setFlipSided(e===pn)},this.allocTextureUnit=Z,this.setTexture2D=function(){var t=!1;return function(e,i){e&&e.isWebGLRenderTarget&&(t||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),se.setTexture2D(e,i)}}(),this.setTexture=function(){var t=!1;return function(e,i){t||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),t=!0),se.setTexture2D(e,i)}}(),this.setTextureCube=function(){var t=!1;return function(e,i){e&&e.isWebGLRenderTargetCube&&(t||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),e&&e.isCubeTexture||Array.isArray(e.image)&&6===e.image.length?se.setTextureCube(e,i):se.setTextureCubeDynamic(e,i)}}(),this.getCurrentRenderTarget=function(){return Rt},this.setRenderTarget=function(t){Rt=t,t&&void 0===oe.get(t).__webglFramebuffer&&se.setupRenderTarget(t);var e,i=t&&t.isWebGLRenderTargetCube;if(t){var n=oe.get(t);e=i?n.__webglFramebuffer[t.activeCubeFace]:n.__webglFramebuffer,Dt.copy(t.scissor),Nt=t.scissorTest,Ot.copy(t.viewport)}else e=null,Dt.copy(kt).multiplyScalar(Vt),Nt=jt,Ot.copy(Wt).multiplyScalar(Vt);if(Pt!==e&&(ee.bindFramebuffer(ee.FRAMEBUFFER,e),Pt=e),ae.scissor(Dt),ae.setScissorTest(Nt),ae.viewport(Ot),i){var r=oe.get(t.texture);ee.framebufferTexture2D(ee.FRAMEBUFFER,ee.COLOR_ATTACHMENT0,ee.TEXTURE_CUBE_MAP_POSITIVE_X+t.activeCubeFace,r.__webglTexture,t.activeMipMapLevel)}},this.readRenderTargetPixels=function(t,e,i,n,r,a){if((t&&t.isWebGLRenderTarget)===!1)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");var o=oe.get(t).__webglFramebuffer;if(o){var s=!1;o!==Pt&&(ee.bindFramebuffer(ee.FRAMEBUFFER,o),s=!0);try{var h=t.texture;if(h.format!==zr&&J(h.format)!==ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!(h.type===Sr||J(h.type)===ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_TYPE)||h.type===Ur&&ne.get("WEBGL_color_buffer_float")||h.type===Ir&&ne.get("EXT_color_buffer_half_float")))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");ee.checkFramebufferStatus(ee.FRAMEBUFFER)===ee.FRAMEBUFFER_COMPLETE?e>=0&&e<=t.width-n&&i>=0&&i<=t.height-r&&ee.readPixels(e,i,n,r,J(h.format),J(h.type),a):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{s&&ee.bindFramebuffer(ee.FRAMEBUFFER,Pt)}}}}function yt(t,e){this.isFogExp2=!0,this.name="",this.color=new w(t),this.density=void 0!==e?e:25e-5}function xt(t,e,i){this.isFog=!0,this.name="",this.color=new w(t),this.near=void 0!==e?e:1,this.far=void 0!==i?i:1e3}function bt(){this.isScene=this.isObject3D=!0,X.call(this),this.type="Scene",this.background=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0}function _t(t,e,i,n,r){this.isLensFlare=!0,X.call(this),this.lensFlares=[],this.positionScreen=new s,this.customUpdateCallback=void 0,void 0!==t&&this.add(t,e,i,n,r)}function wt(t){this.isSpriteMaterial=this.isMaterial=!0,x.call(this),this.type="SpriteMaterial",this.color=new w(16777215),this.map=null,this.rotation=0,this.fog=!1,this.lights=!1,this.setValues(t)}function Mt(t){this.isSprite=!0,X.call(this),this.type="Sprite",this.material=void 0!==t?t:new wt}function Et(){this.isLOD=!0,X.call(this),this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Tt(t,e,i,r,a,o,s,h,c,l,u,p){this.isDataTexture=this.isTexture=!0,n.call(this,null,o,s,h,c,l,r,a,u,p),this.image={data:t,width:e,height:i},this.magFilter=void 0!==c?c:br,this.minFilter=void 0!==l?l:br,this.flipY=!1,this.generateMipmaps=!1}function St(e,i,n){if(this.isSkeleton=!0,this.useVertexTexture=void 0===n||n,this.identityMatrix=new a,e=e||[],this.bones=e.slice(0),this.useVertexTexture){var r=Math.sqrt(4*this.bones.length);r=t.Math.nextPowerOfTwo(Math.ceil(r)),r=Math.max(r,4),this.boneTextureWidth=r,this.boneTextureHeight=r,this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new Tt(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,zr,Ur)}else this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===i)this.calculateInverses();else if(this.bones.length===i.length)this.boneInverses=i.slice(0);else{console.warn("THREE.Skeleton bonInverses is the wrong length."),this.boneInverses=[];for(var o=0,s=this.bones.length;o=t.HAVE_CURRENT_DATA&&(u.needsUpdate=!0)}this.isVideoTexture=this.isTexture=!0,n.call(this,t,e,i,r,a,o,s,h,c),this.generateMipmaps=!1;var u=this;l()}function Ot(t,e,i,r,a,o,s,h,c,l,u,p){this.isCompressedTexture=this.isTexture=!0,n.call(this,null,o,s,h,c,l,r,a,u,p),this.image={width:e,height:i},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}function Ft(t,e,i,r,a,o,s,h,c){this.isCanvasTexture=this.isTexture=!0,n.call(this,t,e,i,r,a,o,s,h,c),this.needsUpdate=!0}function Bt(t,e,i,r,a,o,s,h,c){this.isDepthTexture=this.isTexture=!0,n.call(this,null,r,a,o,s,h,kr,i,c),this.image={width:t,height:e},this.type=void 0!==i?i:Rr,this.magFilter=void 0!==s?s:br,this.minFilter=void 0!==h?h:br,this.flipY=!1,this.generateMipmaps=!1}function zt(){this.isShadowMaterial=this.isShaderMaterial=this.isMaterial=!0,_.call(this,{uniforms:t.UniformsUtils.merge([t.UniformsLib.lights,{opacity:{value:1}}]),vertexShader:ws.shadow_vert,fragmentShader:ws.shadow_frag}),this.lights=!0,this.transparent=!0,Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(t){this.uniforms.opacity.value=t}}})}function Gt(t){this.isRawShaderMaterial=this.isShaderMaterial=this.isMaterial=!0,_.call(this,t),this.type="RawShaderMaterial"}function Ht(e){this.isMultiMaterial=!0,this.uuid=t.Math.generateUUID(),this.type="MultiMaterial",this.materials=e instanceof Array?e:[],this.visible=!0}function Vt(t){this.isMeshStandardMaterial=this.isMaterial=!0,x.call(this),this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new w(16777215),this.roughness=.5,this.metalness=.5,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new i(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function kt(t){this.isMeshPhysicalMaterial=this.isMeshStandardMaterial=this.isMaterial=!0,Vt.call(this),this.defines={PHYSICAL:""},this.type="MeshPhysicalMaterial",this.reflectivity=.5,this.clearCoat=0,this.clearCoatRoughness=0,this.setValues(t)}function jt(t){this.isMeshPhongMaterial=this.isMaterial=!0,x.call(this),this.type="MeshPhongMaterial",this.color=new w(16777215),this.specular=new w(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new i(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Wt(t){this.isMeshNormalMaterial=this.isMaterial=!0,x.call(this,t),this.type="MeshNormalMaterial",this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.morphTargets=!1,this.setValues(t)}function Xt(t){this.isMeshLambertMaterial=this.isMaterial=!0,x.call(this),this.type="MeshLambertMaterial",this.color=new w(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Yt(t){this.isLineDashedMaterial=this.isMaterial=!0,x.call(this),this.type="LineDashedMaterial",this.color=new w(16777215),this.linewidth=1,this.scale=1,this.dashSize=3,this.gapSize=1,this.lights=!1,this.setValues(t)}function qt(t,e,i){this.isLoadingManager=!0;var n=this,r=!1,a=0,o=0;this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=i,this.itemStart=function(t){o++,r===!1&&void 0!==n.onStart&&n.onStart(t,a,o),r=!0},this.itemEnd=function(t){a++,void 0!==n.onProgress&&n.onProgress(t,a,o),a===o&&(r=!1,void 0!==n.onLoad&&n.onLoad())},this.itemError=function(t){void 0!==n.onError&&n.onError(t)}}function Zt(e){this.isXHRLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function Jt(e){this.isCompressedTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Qt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Kt(e){this.isImageLoader=!0, +this.manager=void 0!==e?e:t.DefaultLoadingManager}function $t(e){this.isCubeTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function te(e){this.isTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function ee(t,e){this.isLight=!0,X.call(this),this.type="Light",this.color=new w(t),this.intensity=void 0!==e?e:1,this.receiveShadow=void 0}function ie(t,e,i){this.isHemisphereLight=!0,ee.call(this,t,i),this.type="HemisphereLight",this.castShadow=void 0,this.position.copy(X.DefaultUp),this.updateMatrix(),this.groundColor=new w(e)}function ne(t){this.isLightShadow=!0,this.camera=t,this.bias=0,this.radius=1,this.mapSize=new i(512,512),this.map=null,this.matrix=new a}function re(){this.isSpotLightShadow=!0,ne.call(this,new mt(50,1,.5,500))}function ae(t,e,i,n,r,a){this.isSpotLight=!0,ee.call(this,t,e),this.type="SpotLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(t){this.intensity=t/Math.PI}}),this.distance=void 0!==i?i:0,this.angle=void 0!==n?n:Math.PI/3,this.penumbra=void 0!==r?r:0,this.decay=void 0!==a?a:1,this.shadow=new re}function oe(t,e,i,n){this.isPointLight=!0,ee.call(this,t,e),this.type="PointLight",Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(t){this.intensity=t/(4*Math.PI)}}),this.distance=void 0!==i?i:0,this.decay=void 0!==n?n:1,this.shadow=new ne(new mt(90,1,.5,500))}function se(t){this.isDirectionalLightShadow=!0,ne.call(this,new gt((-5),5,5,(-5),.5,500))}function he(t,e){this.isDirectionalLight=!0,ee.call(this,t,e),this.type="DirectionalLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,this.shadow=new se}function ce(t,e){this.isAmbientLight=!0,ee.call(this,t,e),this.type="AmbientLight",this.castShadow=void 0}function le(t,e,i,n){this.isInterpolant=!0,this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==n?n:new e.constructor(i),this.sampleValues=e,this.valueSize=i}function ue(t,e,i,n){this.isCubicInterpolant=!0,le.call(this,t,e,i,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0}function pe(t,e,i,n){this.isLinearInterpolant=!0,le.call(this,t,e,i,n)}function de(t,e,i,n){this.isDiscreteInterpolant=!0,le.call(this,t,e,i,n)}function fe(e,i,n,r){if(this.isKeyframeTrack=!0,void 0===e)throw new Error("track name is undefined");if(void 0===i||0===i.length)throw new Error("no keyframes in track named "+e);this.name=e,this.times=t.AnimationUtils.convertArray(i,this.TimeBufferType),this.values=t.AnimationUtils.convertArray(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation),this.validate(),this.optimize()}function me(t,e,i,n){this.isVectorKeyframeTrack=!0,fe.call(this,t,e,i,n)}function ge(t,e,i,n){this.isQuaternionLinearInterpolant=!0,le.call(this,t,e,i,n)}function ve(t,e,i,n){this.isQuaternionKeyframeTrack=!0,fe.call(this,t,e,i,n)}function ye(t,e,i,n){this.isNumberKeyframeTrack=!0,fe.call(this,t,e,i,n)}function xe(t,e,i,n){this.isStringKeyframeTrack=!0,fe.call(this,t,e,i,n)}function be(t,e,i){this.isBooleanKeyframeTrack=!0,fe.call(this,t,e,i)}function _e(t,e,i,n){this.isColorKeyframeTrack=!0,fe.call(this,t,e,i,n)}function we(t,e,i,n){fe.apply(this,arguments)}function Me(e,i,n){this.isAnimationClip=!0,this.name=e,this.tracks=n,this.duration=void 0!==i?i:-1,this.uuid=t.Math.generateUUID(),this.duration<0&&this.resetDuration(),this.trim(),this.optimize()}function Ee(e){this.isMaterialLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this.textures={}}function Te(e){this.isBufferGeometryLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function Se(){this.isLoader=!0,this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){}}function Ae(e){this.isJSONLoader=!0,"boolean"==typeof e&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),e=void 0),this.manager=void 0!==e?e:t.DefaultLoadingManager,this.withCredentials=!1}function Le(e){this.isObjectLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this.texturePath=""}function Re(){this.isCurve=!0}function Pe(t,e){this.isLineCurve=this.isCurve=!0,this.v1=t,this.v2=e}function Ce(){this.isCurvePath=!0,this.curves=[],this.autoClose=!1}function Ue(t,e,i,n,r,a,o,s){this.isEllipseCurve=this.isCurve=!0,this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=n,this.aStartAngle=r,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s||0}function Ie(t){this.isSplineCurve=this.isCurve=!0,this.points=void 0==t?[]:t}function De(t,e,i,n){this.isCubicBezierCurve=this.isCurve=!0,this.v0=t,this.v1=e,this.v2=i,this.v3=n}function Ne(t,e,i){this.isQuadraticBezierCurve=this.isCurve=!0,this.v0=t,this.v1=e,this.v2=i}function Oe(t,e,n,r,a,o){function h(t,e,i){return C.vertices.push(new s(t,e,i))-1}this.isTubeGeometry=this.isGeometry=!0,q.call(this),this.type="TubeGeometry",this.parameters={path:t,segments:e,radius:n,radialSegments:r,closed:a,taper:o},e=e||64,n=n||1,r=r||8,a=a||!1,o=o||Oe.NoTaper;var c,l,u,p,d,f,m,g,v,y,x,b,_,w,M,E,T,S,A,L,R,P=[],C=this,U=e+1,I=new s,D=new Oe.FrenetFrames(t,e,a),N=D.tangents,O=D.normals,F=D.binormals;for(this.tangents=N,this.normals=O,this.binormals=F,y=0;ythis.points.length-2?this.points.length-1:n+1,p[3]=n>this.points.length-3?this.points.length-1:n+2,h=this.points[p[0]],c=this.points[p[1]],l=this.points[p[2]],u=this.points[p[3]],a=r*r,o=r*a,d.x=e(h.x,c.x,l.x,u.x,r,a,o),d.y=e(h.y,c.y,l.y,u.y,r,a,o),d.z=e(h.z,c.z,l.z,u.z,r,a,o),d},this.getControlPointsArray=function(){var t,e,i=this.points.length,n=[];for(t=0;t0)&&E.push(S,A,R),(g!==i-1||h65535?z:F)(E,1)),this.addAttribute("position",l),this.addAttribute("normal",u),this.addAttribute("uv",p),this.boundingSphere=new T(new s,t)}function Mi(t,e){this.isPointLightHelper=this.isMesh=!0,this.light=t,this.light.updateMatrixWorld();var i=new wi(e,4,2),n=new ut({wireframe:!0,fog:!1});n.color.copy(this.light.color).multiplyScalar(this.light.intensity),pt.call(this,i,n),this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1}function Ei(t,e,i,n,r,a,o){this.isSphereGeometry=this.isGeometry=!0,q.call(this),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:i,phiStart:n,phiLength:r,thetaStart:a,thetaLength:o},this.fromBufferGeometry(new wi(t,e,i,n,r,a,o))}function Ti(t,e){this.isHemisphereLightHelper=this.isObject3D=!0,X.call(this),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.colors=[new w,new w];var i=new Ei(e,4,2);i.rotateX(-Math.PI/2);for(var n=0,r=8;n0&&m++,e>0&&m++);var g=l(),v=u(),y=new U(new(v>65535?Uint32Array:Uint16Array)(v),1),x=new U(new Float32Array(3*g),3),b=new U(new Float32Array(3*g),3),_=new U(new Float32Array(2*g),2),w=0,M=0,E=[],T=n/2,S=0;p(),o===!1&&(t>0&&d(!0),e>0&&d(!1)),this.setIndex(y),this.addAttribute("position",x),this.addAttribute("normal",b),this.addAttribute("uv",_)}function Oi(t){this.isAxisHelper=this.isLineSegments=!0,t=t||1;var e=new Float32Array([0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t]),i=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]),n=new Q;n.addAttribute("position",new U(e,3)),n.addAttribute("color",new U(i,3));var r=new Rt({vertexColors:En});Ct.call(this,n,r)}function Fi(t,e,n){this.isParametricGeometry=this.isGeometry=!0,q.call(this),this.type="ParametricGeometry",this.parameters={func:t,slices:e,stacks:n};var r,a,o,s,h,c=this.vertices,l=this.faces,u=this.faceVertexUvs[0],p=e+1;for(r=0;r<=n;r++)for(h=r/n,a=0;a<=e;a++)s=a/e,o=t(s,h),c.push(o);var d,f,m,g,v,y,x,b;for(r=0;r.9&&L<.1&&(M<.2&&(w[0].x+=1),E<.2&&(w[1].x+=1),S<.2&&(w[2].x+=1))}for(var d=0,f=this.vertices.length;d65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=new s,b=new s,_=new i,w=new s,M=new s,E=new s,T=new s,S=new s;for(c=0;c<=n;++c){var A=c/n*a*Math.PI*2;for(h(A,a,o,t,w),h(A+.01,a,o,t,M),T.subVectors(M,w),S.addVectors(M,w),E.crossVectors(T,S),S.crossVectors(E,T),E.normalize(),S.normalize(),l=0;l<=r;++l){var L=l/r*Math.PI*2,R=-e*Math.cos(L),P=e*Math.sin(L);x.x=w.x+(R*S.x+P*E.x),x.y=w.y+(R*S.y+P*E.y),x.z=w.z+(R*S.z+P*E.z),f.setXYZ(v,x.x,x.y,x.z),b.subVectors(x,w).normalize(),m.setXYZ(v,b.x,b.y,b.z),_.x=c/n,_.y=l/r,g.setXY(v,_.x,_.y),v++}}for(l=1;l<=n;l++)for(c=1;c<=r;c++){var C=(r+1)*(l-1)+(c-1),I=(r+1)*l+(c-1),D=(r+1)*l+c,N=(r+1)*(l-1)+c;d.setX(y,C),y++,d.setX(y,I),y++,d.setX(y,N),y++,d.setX(y,I),y++,d.setX(y,D),y++,d.setX(y,N),y++}this.setIndex(d),this.addAttribute("position",f),this.addAttribute("normal",m),this.addAttribute("uv",g)}function ji(t,e,i,n,r,a,o){this.isTorusKnotGeometry=this.isGeometry=!0,q.call(this),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,tubularSegments:i,radialSegments:n,p:r,q:a},void 0!==o&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead."),this.fromBufferGeometry(new ki(t,e,i,n,r,a)),this.mergeVertices()}function Wi(t,e,i,n,r){this.isTorusBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="TorusBufferGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:r},t=t||100,e=e||40,i=Math.floor(i)||8,n=Math.floor(n)||6,r=r||2*Math.PI;var a,o,h=(i+1)*(n+1),c=i*n*2*3,l=new(c>65535?Uint32Array:Uint16Array)(c),u=new Float32Array(3*h),p=new Float32Array(3*h),d=new Float32Array(2*h),f=0,m=0,g=0,v=new s,y=new s,x=new s;for(a=0;a<=i;a++)for(o=0;o<=n;o++){var b=o/n*r,_=a/i*Math.PI*2;y.x=(t+e*Math.cos(_))*Math.cos(b),y.y=(t+e*Math.cos(_))*Math.sin(b),y.z=e*Math.sin(_),u[f]=y.x,u[f+1]=y.y,u[f+2]=y.z,v.x=t*Math.cos(b),v.y=t*Math.sin(b),x.subVectors(y,v).normalize(),p[f]=x.x,p[f+1]=x.y,p[f+2]=x.z,d[m]=o/n,d[m+1]=a/i,f+=3,m+=2}for(a=1;a<=i;a++)for(o=1;o<=n;o++){var w=(n+1)*a+o-1,M=(n+1)*(a-1)+o-1,E=(n+1)*(a-1)+o,T=(n+1)*a+o;l[g]=w,l[g+1]=M,l[g+2]=T,l[g+3]=M,l[g+4]=E,l[g+5]=T,g+=6}this.setIndex(new U(l,1)), +this.addAttribute("position",new U(u,3)),this.addAttribute("normal",new U(p,3)),this.addAttribute("uv",new U(d,2))}function Xi(t,e,i,n,r){this.isTorusGeometry=this.isGeometry=!0,q.call(this),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:r},this.fromBufferGeometry(new Wi(t,e,i,n,r))}function Yi(t,e){this.isTextGeometry=this.isExtrudeGeometry=this.isGeometry=!0,e=e||{};var i=e.font;if((i&&i.isFont)===!1)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new q;var n=i.generateShapes(t,e.size,e.curveSegments);e.amount=void 0!==e.height?e.height:50,void 0===e.bevelThickness&&(e.bevelThickness=10),void 0===e.bevelSize&&(e.bevelSize=8),void 0===e.bevelEnabled&&(e.bevelEnabled=!1),Fe.call(this,n,e),this.type="TextGeometry"}function qi(t,e,n,r,a,o){this.isRingBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="RingBufferGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:n,phiSegments:r,thetaStart:a,thetaLength:o},t=t||20,e=e||50,a=void 0!==a?a:0,o=void 0!==o?o:2*Math.PI,n=void 0!==n?Math.max(3,n):8,r=void 0!==r?Math.max(1,r):1;var h,c,l,u=(n+1)*(r+1),p=n*r*2*3,d=new U(new(p>65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=t,b=(e-t)/r,_=new s,w=new i;for(c=0;c<=r;c++){for(l=0;l<=n;l++)h=a+l/n*o,_.x=x*Math.cos(h),_.y=x*Math.sin(h),f.setXYZ(v,_.x,_.y,_.z),m.setXYZ(v,0,0,1),w.x=(_.x/e+1)/2,w.y=(_.y/e+1)/2,g.setXY(v,w.x,w.y),v++;x+=b}for(c=0;c65535?Uint32Array:Uint16Array)(u),1),d=new U(new Float32Array(3*l),3),f=new U(new Float32Array(2*l),2),m=0,g=0,v=(1/(e.length-1),1/n),y=new s,x=new i;for(h=0;h<=n;h++){var b=r+h*v*a,_=Math.sin(b),w=Math.cos(b);for(c=0;c<=e.length-1;c++)y.x=e[c].x*_,y.y=e[c].y,y.z=e[c].x*w,d.setXYZ(m,y.x,y.y,y.z),x.x=h/n,x.y=c/(e.length-1),f.setXY(m,x.x,x.y),m++}for(h=0;h>=4,i[r]=e[19===r?3&t|8:t]);return i.join("")}}(),clamp:function(t,e,i){return Math.max(e,Math.min(i,t))},euclideanModulo:function(t,e){return(t%e+e)%e},mapLinear:function(t,e,i,n,r){return n+(t-e)*(r-n)/(i-e)},smoothstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*(3-2*t))},smootherstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*t*(t*(6*t-15)+10))},random16:function(){return console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead."),Math.random()},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},degToRad:function(e){return e*t.Math.DEG2RAD},radToDeg:function(e){return e*t.Math.RAD2DEG},isPowerOfTwo:function(t){return 0===(t&t-1)&&0!==t},nearestPowerOfTwo:function(t){return Math.pow(2,Math.round(Math.log(t)/Math.LN2))},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}},i.prototype={constructor:i,get width(){return this.x},set width(t){this.x=t},get height(){return this.y},set height(t){this.y=t},set:function(t,e){return this.x=t,this.y=e,this},setScalar:function(t){return this.x=t,this.y=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(t){return this.x=t.x,this.y=t.y,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)},addScalar:function(t){return this.x+=t,this.y+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)},subScalar:function(t){return this.x-=t,this.y-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t):(this.x=0,this.y=0),this},divide:function(t){return this.x/=t.x,this.y/=t.y,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this},clampScalar:function(){var t,e;return function(n,r){return void 0===t&&(t=new i,e=new i),t.set(n,n),e.set(r,r),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(t){return this.x*t.x+this.y*t.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var t=Math.atan2(this.y,this.x);return t<0&&(t+=2*Math.PI),t},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y;return e*e+i*i},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},equals:function(t){return t.x===this.x&&t.y===this.y},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this},rotateAround:function(t,e){var i=Math.cos(e),n=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*i-a*n+t.x,this.y=r*n+a*i+t.y,this}},n.DEFAULT_IMAGE=void 0,n.DEFAULT_MAPPING=cr,n.prototype={constructor:n,set needsUpdate(t){t===!0&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.encoding=t.encoding,this},toJSON:function(e){function i(t){var e;return void 0!==t.toDataURL?e=t:(e=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0,t.width,t.height)),e.width>2048||e.height>2048?e.toDataURL("image/jpeg",.6):e.toDataURL("image/png")}if(void 0!==e.textures[this.uuid])return e.textures[this.uuid];var n={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var r=this.image;void 0===r.uuid&&(r.uuid=t.Math.generateUUID()),void 0===e.images[r.uuid]&&(e.images[r.uuid]={uuid:r.uuid,url:i(r)}),n.image=r.uuid}return e.textures[this.uuid]=n,n},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(t){if(this.mapping===cr){if(t.multiply(this.repeat),t.add(this.offset),t.x<0||t.x>1)switch(this.wrapS){case vr:t.x=t.x-Math.floor(t.x);break;case yr:t.x=t.x<0?0:1;break;case xr:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case vr:t.y=t.y-Math.floor(t.y);break;case yr:t.y=t.y<0?0:1;break;case xr:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}this.flipY&&(t.y=1-t.y)}}},Object.assign(n.prototype,e.prototype);var _a=0;a.prototype={constructor:a,set:function(t,e,i,n,r,a,o,s,h,c,l,u,p,d,f,m){var g=this.elements;return g[0]=t,g[4]=e,g[8]=i,g[12]=n,g[1]=r,g[5]=a,g[9]=o,g[13]=s,g[2]=h,g[6]=c,g[10]=l,g[14]=u,g[3]=p,g[7]=d,g[11]=f,g[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},clone:function(){return(new a).fromArray(this.elements)},copy:function(t){return this.elements.set(t.elements),this},copyPosition:function(t){var e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this},extractBasis:function(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this},makeBasis:function(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this},extractRotation:function(){var t;return function(e){void 0===t&&(t=new s);var i=this.elements,n=e.elements,r=1/t.setFromMatrixColumn(e,0).length(),a=1/t.setFromMatrixColumn(e,1).length(),o=1/t.setFromMatrixColumn(e,2).length();return i[0]=n[0]*r,i[1]=n[1]*r,i[2]=n[2]*r,i[4]=n[4]*a,i[5]=n[5]*a,i[6]=n[6]*a,i[8]=n[8]*o,i[9]=n[9]*o,i[10]=n[10]*o,this}}(),makeRotationFromEuler:function(t){(t&&t.isEuler)===!1&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var e=this.elements,i=t.x,n=t.y,r=t.z,a=Math.cos(i),o=Math.sin(i),s=Math.cos(n),h=Math.sin(n),c=Math.cos(r),l=Math.sin(r);if("XYZ"===t.order){var u=a*c,p=a*l,d=o*c,f=o*l;e[0]=s*c,e[4]=-s*l,e[8]=h,e[1]=p+d*h,e[5]=u-f*h,e[9]=-o*s,e[2]=f-u*h,e[6]=d+p*h,e[10]=a*s}else if("YXZ"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m+y*o,e[4]=v*o-g,e[8]=a*h,e[1]=a*l,e[5]=a*c,e[9]=-o,e[2]=g*o-v,e[6]=y+m*o,e[10]=a*s}else if("ZXY"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m-y*o,e[4]=-a*l,e[8]=v+g*o,e[1]=g+v*o,e[5]=a*c,e[9]=y-m*o,e[2]=-a*h,e[6]=o,e[10]=a*s}else if("ZYX"===t.order){var u=a*c,p=a*l,d=o*c,f=o*l;e[0]=s*c,e[4]=d*h-p,e[8]=u*h+f,e[1]=s*l,e[5]=f*h+u,e[9]=p*h-d,e[2]=-h,e[6]=o*s,e[10]=a*s}else if("YZX"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=w-x*l,e[8]=_*l+b,e[1]=l,e[5]=a*c,e[9]=-o*c,e[2]=-h*c,e[6]=b*l+_,e[10]=x-w*l}else if("XZY"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=-l,e[8]=h*c,e[1]=x*l+w,e[5]=a*c,e[9]=b*l-_,e[2]=_*l-b,e[6]=o*c,e[10]=w*l+x}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},makeRotationFromQuaternion:function(t){var e=this.elements,i=t.x,n=t.y,r=t.z,a=t.w,o=i+i,s=n+n,h=r+r,c=i*o,l=i*s,u=i*h,p=n*s,d=n*h,f=r*h,m=a*o,g=a*s,v=a*h;return e[0]=1-(p+f),e[4]=l-v,e[8]=u+g,e[1]=l+v,e[5]=1-(c+f),e[9]=d-m,e[2]=u-g,e[6]=d+m,e[10]=1-(c+p),e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},lookAt:function(){var t,e,i;return function(n,r,a){void 0===t&&(t=new s,e=new s,i=new s);var o=this.elements;return i.subVectors(n,r).normalize(),0===i.lengthSq()&&(i.z=1),t.crossVectors(a,i).normalize(),0===t.lengthSq()&&(i.z+=1e-4,t.crossVectors(a,i).normalize()),e.crossVectors(i,t),o[0]=t.x,o[4]=e.x,o[8]=i.x,o[1]=t.y,o[5]=e.y,o[9]=i.y,o[2]=t.z,o[6]=e.z,o[10]=i.z,this}}(),multiply:function(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)},premultiply:function(t){return this.multiplyMatrices(t,this)},multiplyMatrices:function(t,e){var i=t.elements,n=e.elements,r=this.elements,a=i[0],o=i[4],s=i[8],h=i[12],c=i[1],l=i[5],u=i[9],p=i[13],d=i[2],f=i[6],m=i[10],g=i[14],v=i[3],y=i[7],x=i[11],b=i[15],_=n[0],w=n[4],M=n[8],E=n[12],T=n[1],S=n[5],A=n[9],L=n[13],R=n[2],P=n[6],C=n[10],U=n[14],I=n[3],D=n[7],N=n[11],O=n[15];return r[0]=a*_+o*T+s*R+h*I,r[4]=a*w+o*S+s*P+h*D,r[8]=a*M+o*A+s*C+h*N,r[12]=a*E+o*L+s*U+h*O,r[1]=c*_+l*T+u*R+p*I,r[5]=c*w+l*S+u*P+p*D,r[9]=c*M+l*A+u*C+p*N,r[13]=c*E+l*L+u*U+p*O,r[2]=d*_+f*T+m*R+g*I,r[6]=d*w+f*S+m*P+g*D,r[10]=d*M+f*A+m*C+g*N,r[14]=d*E+f*L+m*U+g*O,r[3]=v*_+y*T+x*R+b*I,r[7]=v*w+y*S+x*P+b*D,r[11]=v*M+y*A+x*C+b*N,r[15]=v*E+y*L+x*U+b*O,this},multiplyToArray:function(t,e,i){var n=this.elements;return this.multiplyMatrices(t,e),i[0]=n[0],i[1]=n[1],i[2]=n[2],i[3]=n[3],i[4]=n[4],i[5]=n[5],i[6]=n[6],i[7]=n[7],i[8]=n[8],i[9]=n[9],i[10]=n[10],i[11]=n[11],i[12]=n[12],i[13]=n[13],i[14]=n[14],i[15]=n[15],this},multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r0?(e=.5/Math.sqrt(p+1),this._w=.25/e,this._x=(l-h)*e,this._y=(a-c)*e,this._z=(o-r)*e):n>s&&n>u?(e=2*Math.sqrt(1+n-s-u),this._w=(l-h)/e,this._x=.25*e,this._y=(r+o)/e,this._z=(a+c)/e):s>u?(e=2*Math.sqrt(1+s-n-u),this._w=(a-c)/e,this._x=(r+o)/e,this._y=.25*e,this._z=(h+l)/e):(e=2*Math.sqrt(1+u-n-s),this._w=(o-r)/e,this._x=(a+c)/e,this._y=(h+l)/e,this._z=.25*e),this.onChangeCallback(),this},setFromUnitVectors:function(){var t,e,i=1e-6;return function(n,r){return void 0===t&&(t=new s),e=n.dot(r)+1,eMath.abs(n.z)?t.set(-n.y,n.x,0):t.set(0,-n.z,n.y)):t.crossVectors(n,r),this._x=t.x,this._y=t.y,this._z=t.z,this._w=e,this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this.onChangeCallback(),this},dot:function(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this.onChangeCallback(),this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)},premultiply:function(t){return this.multiplyQuaternions(t,this)},multiplyQuaternions:function(t,e){var i=t._x,n=t._y,r=t._z,a=t._w,o=e._x,s=e._y,h=e._z,c=e._w;return this._x=i*c+a*o+n*h-r*s,this._y=n*c+a*s+r*o-i*h,this._z=r*c+a*h+i*s-n*o,this._w=a*c-i*o-n*s-r*h,this.onChangeCallback(),this},slerp:function(t,e){if(0===e)return this;if(1===e)return this.copy(t);var i=this._x,n=this._y,r=this._z,a=this._w,o=a*t._w+i*t._x+n*t._y+r*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=a,this._x=i,this._y=n,this._z=r,this;var s=Math.sqrt(1-o*o);if(Math.abs(s)<.001)return this._w=.5*(a+this._w),this._x=.5*(i+this._x),this._y=.5*(n+this._y),this._z=.5*(r+this._z),this;var h=Math.atan2(s,o),c=Math.sin((1-e)*h)/s,l=Math.sin(e*h)/s;return this._w=a*c+this._w*l,this._x=i*c+this._x*l,this._y=n*c+this._y*l,this._z=r*c+this._z*l,this.onChangeCallback(),this},equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w},fromArray:function(t,e){return void 0===e&&(e=0),this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this.onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t},onChange:function(t){return this.onChangeCallback=t,this},onChangeCallback:function(){}},Object.assign(o,{slerp:function(t,e,i,n){return i.copy(t).slerp(e,n)},slerpFlat:function(t,e,i,n,r,a,o){var s=i[n+0],h=i[n+1],c=i[n+2],l=i[n+3],u=r[a+0],p=r[a+1],d=r[a+2],f=r[a+3];if(l!==f||s!==u||h!==p||c!==d){var m=1-o,g=s*u+h*p+c*d+l*f,v=g>=0?1:-1,y=1-g*g;if(y>Number.EPSILON){var x=Math.sqrt(y),b=Math.atan2(x,g*v);m=Math.sin(m*b)/x,o=Math.sin(o*b)/x}var _=o*v;if(s=s*m+u*_,h=h*m+p*_,c=c*m+d*_,l=l*m+f*_,m===1-o){var w=1/Math.sqrt(s*s+h*h+c*c+l*l);s*=w,h*=w,c*=w,l*=w}}t[e]=s,t[e+1]=h,t[e+2]=c,t[e+3]=l}}),s.prototype={constructor:s,set:function(t,e,i){return this.x=t,this.y=e,this.z=i,this},setScalar:function(t){return this.x=t,this.y=t,this.z=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x,this.y*=t.y,this.z*=t.z,this)},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t,this.z*=t):(this.x=0,this.y=0,this.z=0),this},multiplyVectors:function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},applyEuler:function(){var t;return function(e){return(e&&e.isEuler)===!1&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),void 0===t&&(t=new o),this.applyQuaternion(t.setFromEuler(e))}}(),applyAxisAngle:function(){var t;return function(e,i){return void 0===t&&(t=new o),this.applyQuaternion(t.setFromAxisAngle(e,i)); +}}(),applyMatrix3:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[3]*i+r[6]*n,this.y=r[1]*e+r[4]*i+r[7]*n,this.z=r[2]*e+r[5]*i+r[8]*n,this},applyMatrix4:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12],this.y=r[1]*e+r[5]*i+r[9]*n+r[13],this.z=r[2]*e+r[6]*i+r[10]*n+r[14],this},applyProjection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements,a=1/(r[3]*e+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*n+r[12])*a,this.y=(r[1]*e+r[5]*i+r[9]*n+r[13])*a,this.z=(r[2]*e+r[6]*i+r[10]*n+r[14])*a,this},applyQuaternion:function(t){var e=this.x,i=this.y,n=this.z,r=t.x,a=t.y,o=t.z,s=t.w,h=s*e+a*n-o*i,c=s*i+o*e-r*n,l=s*n+r*i-a*e,u=-r*e-a*i-o*n;return this.x=h*s+u*-r+c*-o-l*-a,this.y=c*s+u*-a+l*-r-h*-o,this.z=l*s+u*-o+h*-a-c*-r,this},project:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.projectionMatrix,t.getInverse(e.matrixWorld)),this.applyProjection(t)}}(),unproject:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.matrixWorld,t.getInverse(e.projectionMatrix)),this.applyProjection(t)}}(),transformDirection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n,this.y=r[1]*e+r[5]*i+r[9]*n,this.z=r[2]*e+r[6]*i+r[10]*n,this.normalize()},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this},clampScalar:function(){var t,e;return function(i,n){return void 0===t&&(t=new s,e=new s),t.set(i,i,i),e.set(n,n,n),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},cross:function(t,e){if(void 0!==e)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e);var i=this.x,n=this.y,r=this.z;return this.x=n*t.z-r*t.y,this.y=r*t.x-i*t.z,this.z=i*t.y-n*t.x,this},crossVectors:function(t,e){var i=t.x,n=t.y,r=t.z,a=e.x,o=e.y,s=e.z;return this.x=n*s-r*o,this.y=r*a-i*s,this.z=i*o-n*a,this},projectOnVector:function(t){var e=t.dot(this)/t.lengthSq();return this.copy(t).multiplyScalar(e)},projectOnPlane:function(){var t;return function(e){return void 0===t&&(t=new s),t.copy(this).projectOnVector(e),this.sub(t)}}(),reflect:function(){var t;return function(e){return void 0===t&&(t=new s),this.sub(t.copy(e).multiplyScalar(2*this.dot(e)))}}(),angleTo:function(e){var i=this.dot(e)/Math.sqrt(this.lengthSq()*e.lengthSq());return Math.acos(t.Math.clamp(i,-1,1))},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)},setFromSpherical:function(t){var e=Math.sin(t.phi)*t.radius;return this.x=e*Math.sin(t.theta),this.y=Math.cos(t.phi)*t.radius,this.z=e*Math.cos(t.theta),this},setFromMatrixPosition:function(t){return this.setFromMatrixColumn(t,3)},setFromMatrixScale:function(t){var e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=n,this},setFromMatrixColumn:function(t,e){if("number"==typeof t){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var i=t;t=e,e=i}return this.fromArray(t.elements,4*e)},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this.z=t.array[e+2],this}},c.prototype={constructor:c,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y},getParameter:function(t,e){var n=e||new i;return n.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)},clampPoint:function(t,e){var n=e||new i;return n.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new i;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},u.prototype=Object.create(n.prototype),u.prototype.constructor=u,Object.defineProperty(u.prototype,"images",{get:function(){return this.image},set:function(t){this.image=t}}),t.WebGLUniforms=function(){var t=new n,e=new u,i=function(){this.seq=[],this.map={}},r=[],a=[],o=function(t,e,i){var n=t[0];if(n<=0||n>0)return t;var a=e*i,o=r[a];if(void 0===o&&(o=new Float32Array(a),r[a]=o),0!==e){n.toArray(o,0);for(var s=1,h=0;s!==e;++s)h+=i,t[s].toArray(o,h)}return o},s=function(t,e){var i=a[e];void 0===i&&(i=new Int32Array(e),a[e]=i);for(var n=0;n!==e;++n)i[n]=t.allocTextureUnit();return i},h=function(t,e){t.uniform1f(this.addr,e)},c=function(t,e){t.uniform1i(this.addr,e)},l=function(t,e){void 0===e.x?t.uniform2fv(this.addr,e):t.uniform2f(this.addr,e.x,e.y)},p=function(t,e){void 0!==e.x?t.uniform3f(this.addr,e.x,e.y,e.z):void 0!==e.r?t.uniform3f(this.addr,e.r,e.g,e.b):t.uniform3fv(this.addr,e)},d=function(t,e){void 0===e.x?t.uniform4fv(this.addr,e):t.uniform4f(this.addr,e.x,e.y,e.z,e.w)},f=function(t,e){t.uniformMatrix2fv(this.addr,!1,e.elements||e)},m=function(t,e){t.uniformMatrix3fv(this.addr,!1,e.elements||e)},g=function(t,e){t.uniformMatrix4fv(this.addr,!1,e.elements||e)},v=function(e,i,n){var r=n.allocTextureUnit();e.uniform1i(this.addr,r),n.setTexture2D(i||t,r)},y=function(t,i,n){var r=n.allocTextureUnit();t.uniform1i(this.addr,r),n.setTextureCube(i||e,r)},x=function(t,e){t.uniform2iv(this.addr,e)},b=function(t,e){t.uniform3iv(this.addr,e)},_=function(t,e){t.uniform4iv(this.addr,e)},w=function(t){switch(t){case 5126:return h;case 35664:return l;case 35665:return p;case 35666:return d;case 35674:return f;case 35675:return m;case 35676:return g;case 35678:return v;case 35680:return y;case 5124:case 35670:return c;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},M=function(t,e){t.uniform1fv(this.addr,e)},E=function(t,e){t.uniform1iv(this.addr,e)},T=function(t,e){t.uniform2fv(this.addr,o(e,this.size,2))},S=function(t,e){t.uniform3fv(this.addr,o(e,this.size,3))},A=function(t,e){t.uniform4fv(this.addr,o(e,this.size,4))},L=function(t,e){t.uniformMatrix2fv(this.addr,!1,o(e,this.size,4))},R=function(t,e){t.uniformMatrix3fv(this.addr,!1,o(e,this.size,9))},P=function(t,e){t.uniformMatrix4fv(this.addr,!1,o(e,this.size,16))},C=function(e,i,n){var r=i.length,a=s(n,r);e.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTexture2D(i[o]||t,a[o])},U=function(t,i,n){var r=i.length,a=s(n,r);t.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTextureCube(i[o]||e,a[o])},I=function(t){switch(t){case 5126:return M;case 35664:return T;case 35665:return S;case 35666:return A;case 35674:return L;case 35675:return R;case 35676:return P;case 35678:return C;case 35680:return U;case 5124:case 35670:return E;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},D=function(t,e,i){this.id=t,this.addr=i,this.setValue=w(e.type)},N=function(t,e,i){this.id=t,this.addr=i,this.size=e.size,this.setValue=I(e.type)},O=function(t){this.id=t,i.call(this)};O.prototype.setValue=function(t,e){for(var i=this.seq,n=0,r=i.length;n!==r;++n){var a=i[n];a.setValue(t,e[a.id])}};var F=/([\w\d_]+)(\])?(\[|\.)?/g,B=function(t,e){t.seq.push(e),t.map[e.id]=e},z=function(t,e,i){var n=t.name,r=n.length;for(F.lastIndex=0;;){var a=F.exec(n),o=F.lastIndex,s=a[1],h="]"===a[2],c=a[3];if(h&&(s=0|s),void 0===c||"["===c&&o+2===r){B(i,void 0===c?new D(s,t,e):new N(s,t,e));break}var l=i.map,u=l[s];void 0===u&&(u=new O(s),B(i,u)),i=u}},G=function(t,e,n){i.call(this),this.renderer=n;for(var r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),a=0;a!==r;++a){var o=t.getActiveUniform(e,a),s=o.name,h=t.getUniformLocation(e,s);z(o,h,this)}};return G.prototype.setValue=function(t,e,i){var n=this.map[e];void 0!==n&&n.setValue(t,i,this.renderer)},G.prototype.set=function(t,e,i){var n=this.map[i];void 0!==n&&n.setValue(t,e[i],this.renderer)},G.prototype.setOptional=function(t,e,i){var n=e[i];void 0!==n&&this.setValue(t,i,n)},G.upload=function(t,e,i,n){for(var r=0,a=e.length;r!==a;++r){var o=e[r],s=i[o.id];s.needsUpdate!==!1&&o.setValue(t,s.value,n)}},G.seqWithValue=function(t,e){for(var i=[],n=0,r=t.length;n!==r;++n){var a=t[n];a.id in e&&i.push(a)}return i},G.splitDynamic=function(t,e){for(var i=null,n=t.length,r=0,a=0;a!==n;++a){var o=t[a],s=e[o.id];s&&s.dynamic===!0?(null===i&&(i=[]),i.push(o)):(ry&&v>x?vx?y0&&(n.alphaTest=this.alphaTest),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=this.premultipliedAlpha),this.wireframe===!0&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),i){var r=e(t.textures),a=e(t.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n},clone:function(){return(new this.constructor).copy(this)},copy:function(t){this.name=t.name,this.fog=t.fog,this.lights=t.lights,this.blending=t.blending,this.side=t.side,this.shading=t.shading,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.alphaTest=t.alphaTest,this.premultipliedAlpha=t.premultipliedAlpha,this.overdraw=t.overdraw,this.visible=t.visible,this.clipShadows=t.clipShadows;var e=t.clippingPlanes,i=null;if(null!==e){var n=e.length;i=new Array(n);for(var r=0;r!==n;++r)i[r]=e[r].clone()}return this.clippingPlanes=i,this},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}},Object.assign(x.prototype,e.prototype);var wa=0;t.UniformsUtils={merge:function(t){for(var e={},i=0;i>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this},setRGB:function(t,e,i){return this.r=t,this.g=e,this.b=i,this},setHSL:function(){function e(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+6*(e-t)*(2/3-i):t}return function(i,n,r){if(i=t.Math.euclideanModulo(i,1),n=t.Math.clamp(n,0,1),r=t.Math.clamp(r,0,1),0===n)this.r=this.g=this.b=r;else{var a=r<=.5?r*(1+n):r+n-r*n,o=2*r-a;this.r=e(o,a,i+1/3),this.g=e(o,a,i),this.b=e(o,a,i-1/3)}return this}}(),setStyle:function(e){function i(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}var n;if(n=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(e)){var r,a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(r=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(255,parseInt(r[1],10))/255,this.g=Math.min(255,parseInt(r[2],10))/255,this.b=Math.min(255,parseInt(r[3],10))/255,i(r[5]),this;if(r=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(100,parseInt(r[1],10))/100,this.g=Math.min(100,parseInt(r[2],10))/100,this.b=Math.min(100,parseInt(r[3],10))/100,i(r[5]),this;break;case"hsl":case"hsla":if(r=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o)){var s=parseFloat(r[1])/360,h=parseInt(r[2],10)/100,c=parseInt(r[3],10)/100;return i(r[5]),this.setHSL(s,h,c)}}}else if(n=/^\#([A-Fa-f0-9]+)$/.exec(e)){var l=n[1],u=l.length;if(3===u)return this.r=parseInt(l.charAt(0)+l.charAt(0),16)/255,this.g=parseInt(l.charAt(1)+l.charAt(1),16)/255,this.b=parseInt(l.charAt(2)+l.charAt(2),16)/255,this;if(6===u)return this.r=parseInt(l.charAt(0)+l.charAt(1),16)/255,this.g=parseInt(l.charAt(2)+l.charAt(3),16)/255,this.b=parseInt(l.charAt(4)+l.charAt(5),16)/255,this}if(e&&e.length>0){var l=t.ColorKeywords[e];void 0!==l?this.setHex(l):console.warn("THREE.Color: Unknown color "+e)}return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},copyGammaToLinear:function(t,e){return void 0===e&&(e=2),this.r=Math.pow(t.r,e),this.g=Math.pow(t.g,e),this.b=Math.pow(t.b,e),this},copyLinearToGamma:function(t,e){void 0===e&&(e=2);var i=e>0?1/e:1;return this.r=Math.pow(t.r,i),this.g=Math.pow(t.g,i),this.b=Math.pow(t.b,i),this},convertGammaToLinear:function(){var t=this.r,e=this.g,i=this.b;return this.r=t*t,this.g=e*e,this.b=i*i,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(t){var e,i,n=t||{h:0,s:0,l:0},r=this.r,a=this.g,o=this.b,s=Math.max(r,a,o),h=Math.min(r,a,o),c=(h+s)/2;if(h===s)e=0,i=0;else{var l=s-h;switch(i=c<=.5?l/(s+h):l/(2-s-h),s){case r:e=(a-o)/l+(ar&&(r=c),l>a&&(a=l),u>o&&(o=u)}this.min.set(e,i,n),this.max.set(r,a,o)},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z},getParameter:function(t,e){var i=e||new s;return i.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)},intersectsSphere:function(){var t;return function(e){return void 0===t&&(t=new s),this.clampPoint(e.center,t),t.distanceToSquared(e.center)<=e.radius*e.radius}}(),intersectsPlane:function(t){var e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=t.constant&&i>=t.constant},clampPoint:function(t,e){var i=e||new s;return i.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new s;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),getBoundingSphere:function(){var t=new s;return function(e){var i=e||new T;return i.center=this.center(),i.radius=.5*this.size(t).length(),i}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},applyMatrix4:function(){var t=[new s,new s,new s,new s,new s,new s,new s,new s];return function(e){return this.isEmpty()?this:(t[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),t[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),t[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),t[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),t[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),t[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),t[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),t[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(t),this)}}(),translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},T.prototype={constructor:T,set:function(t,e){return this.center.copy(t),this.radius=e,this},setFromPoints:function(){var t=new E;return function(e,i){var n=this.center;void 0!==i?n.copy(i):t.setFromPoints(e).center(n);for(var r=0,a=0,o=e.length;athis.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n},getBoundingBox:function(t){var e=t||new E;return e.set(this.center,this.center),e.expandByScalar(this.radius),e},applyMatrix4:function(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this},translate:function(t){return this.center.add(t),this},equals:function(t){return t.center.equals(this.center)&&t.radius===this.radius}},S.prototype={constructor:S,set:function(t,e,i,n,r,a,o,s,h){var c=this.elements;return c[0]=t,c[1]=n,c[2]=o,c[3]=e,c[4]=r,c[5]=s,c[6]=i,c[7]=a,c[8]=h,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(t){var e=t.elements;return this.set(e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]),this},setFromMatrix4:function(t){var e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r1))return n.copy(r).multiplyScalar(o).add(e.start)}else if(0===this.distanceToPoint(e.start))return n.copy(e.start)}}(),intersectsLine:function(t){var e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0},intersectsBox:function(t){return t.intersectsPlane(this)},intersectsSphere:function(t){return t.intersectsPlane(this)},coplanarPoint:function(t){var e=t||new s;return e.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var t=new s,e=new S;return function(i,n){var r=this.coplanarPoint(t).applyMatrix4(i),a=n||e.getNormalMatrix(i),o=this.normal.applyMatrix3(a).normalize();return this.constant=-r.dot(o),this}}(),translate:function(t){return this.constant=this.constant-t.dot(this.normal),this},equals:function(t){return t.normal.equals(this.normal)&&t.constant===this.constant}},L.prototype={constructor:L,set:function(t,e,i,n,r,a){var o=this.planes;return o[0].copy(t),o[1].copy(e),o[2].copy(i),o[3].copy(n),o[4].copy(r),o[5].copy(a),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){for(var e=this.planes,i=0;i<6;i++)e[i].copy(t.planes[i]);return this},setFromMatrix:function(t){var e=this.planes,i=t.elements,n=i[0],r=i[1],a=i[2],o=i[3],s=i[4],h=i[5],c=i[6],l=i[7],u=i[8],p=i[9],d=i[10],f=i[11],m=i[12],g=i[13],v=i[14],y=i[15];return e[0].setComponents(o-n,l-s,f-u,y-m).normalize(),e[1].setComponents(o+n,l+s,f+u,y+m).normalize(),e[2].setComponents(o+r,l+h,f+p,y+g).normalize(),e[3].setComponents(o-r,l-h,f-p,y-g).normalize(),e[4].setComponents(o-a,l-c,f-d,y-v).normalize(),e[5].setComponents(o+a,l+c,f+d,y+v).normalize(),this},intersectsObject:function(){var t=new T;return function(e){var i=e.geometry;return null===i.boundingSphere&&i.computeBoundingSphere(),t.copy(i.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSprite:function(){var t=new T;return function(e){return t.center.set(0,0,0),t.radius=.7071067811865476,t.applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSphere:function(t){for(var e=this.planes,i=t.center,n=-t.radius,r=0;r<6;r++){var a=e[r].distanceToPoint(i);if(a0?i.min.x:i.max.x,e.x=a.normal.x>0?i.max.x:i.min.x,t.y=a.normal.y>0?i.min.y:i.max.y,e.y=a.normal.y>0?i.max.y:i.min.y,t.z=a.normal.z>0?i.min.z:i.max.z,e.z=a.normal.z>0?i.max.z:i.min.z;var o=a.distanceToPoint(t),s=a.distanceToPoint(e);if(o<0&&s<0)return!1}return!0}}(),containsPoint:function(t){for(var e=this.planes,i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}},t.WebGLShader=function(){function t(t){for(var e=t.split("\n"),i=0;i");return l(i)}var i=/#include +<([\w\d.]+)>/g;return t.replace(i,e)}function u(t){function e(t,e,i,n){for(var r="",a=parseInt(e);a0?e.gammaFactor:1,L=a(v,m,e.extensions),R=o(y),P=g.createProgram();f&&f.isRawShaderMaterial?(T=[R].filter(h).join("\n"),S=[R].filter(h).join("\n")):(T=["precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+A,"#define MAX_BONES "+m.maxBones,m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+M:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.displacementMap&&m.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.skinning?"#define USE_SKINNING":"",m.useVertexTexture?"#define BONE_TEXTURE":"",m.morphTargets?"#define USE_MORPHTARGETS":"",m.morphNormals&&m.flatShading===!1?"#define USE_MORPHNORMALS":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+_:"",m.sizeAttenuation?"#define USE_SIZEATTENUATION":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(h).join("\n"), +S=[L,"precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.alphaTest?"#define ALPHATEST "+m.alphaTest:"","#define GAMMA_FACTOR "+A,m.useFog&&m.fog?"#define USE_FOG":"",m.useFog&&m.fogExp?"#define FOG_EXP2":"",m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+w:"",m.envMap?"#define "+M:"",m.envMap?"#define "+E:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+_:"",m.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",m.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",m.envMap&&e.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",m.toneMapping!==rr?"#define TONE_MAPPING":"",m.toneMapping!==rr?ws.tonemapping_pars_fragment:"",m.toneMapping!==rr?r("toneMapping",m.toneMapping):"",m.outputEncoding||m.mapEncoding||m.envMapEncoding||m.emissiveMapEncoding?ws.encodings_pars_fragment:"",m.mapEncoding?i("mapTexelToLinear",m.mapEncoding):"",m.envMapEncoding?i("envMapTexelToLinear",m.envMapEncoding):"",m.emissiveMapEncoding?i("emissiveMapTexelToLinear",m.emissiveMapEncoding):"",m.outputEncoding?n("linearToOutputTexel",m.outputEncoding):"",m.depthPacking?"#define DEPTH_PACKING "+f.depthPacking:"","\n"].filter(h).join("\n")),x=l(x,m),x=c(x,m),b=l(b,m),b=c(b,m),(f&&f.isShaderMaterial)===!1&&(x=u(x),b=u(b));var C=T+x,U=S+b,I=t.WebGLShader(g,g.VERTEX_SHADER,C),D=t.WebGLShader(g,g.FRAGMENT_SHADER,U);g.attachShader(P,I),g.attachShader(P,D),void 0!==f.index0AttributeName?g.bindAttribLocation(P,0,f.index0AttributeName):m.morphTargets===!0&&g.bindAttribLocation(P,0,"position"),g.linkProgram(P);var N=g.getProgramInfoLog(P),O=g.getShaderInfoLog(I),F=g.getShaderInfoLog(D),B=!0,z=!0;g.getProgramParameter(P,g.LINK_STATUS)===!1?(B=!1,console.error("THREE.WebGLProgram: shader error: ",g.getError(),"gl.VALIDATE_STATUS",g.getProgramParameter(P,g.VALIDATE_STATUS),"gl.getProgramInfoLog",N,O,F)):""!==N?console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",N):""!==O&&""!==F||(z=!1),z&&(this.diagnostics={runnable:B,material:f,programLog:N,vertexShader:{log:O,prefix:T},fragmentShader:{log:F,prefix:S}}),g.deleteShader(I),g.deleteShader(D);var G;this.getUniforms=function(){return void 0===G&&(G=new t.WebGLUniforms(g,P,e)),G};var H;return this.getAttributes=function(){return void 0===H&&(H=s(g,P)),H},this.destroy=function(){g.deleteProgram(P),this.program=void 0},Object.defineProperties(this,{uniforms:{get:function(){return console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms()."),this.getUniforms()}},attributes:{get:function(){return console.warn("THREE.WebGLProgram: .attributes is now .getAttributes()."),this.getAttributes()}}}),this.id=p++,this.code=d,this.usedTimes=1,this.program=P,this.vertexShader=I,this.fragmentShader=D,this}}(),U.prototype={constructor:U,get count(){return this.array.length/this.itemSize},set needsUpdate(t){t===!0&&this.version++},setDynamic:function(t){return this.dynamic=t,this},copy:function(t){return this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.dynamic=t.dynamic,this},copyAt:function(t,e,i){t*=this.itemSize,i*=e.itemSize;for(var n=0,r=this.itemSize;n1){for(var e=0;e1)for(var e=0;e0){r.children=[];for(var a=0;a0&&(n.geometries=o),s.length>0&&(n.materials=s),h.length>0&&(n.textures=h),c.length>0&&(n.images=c)}return n.object=r,n},clone:function(t){return(new this.constructor).copy(this,t)},copy:function(t,e){if(void 0===e&&(e=!0),this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(var i=0;i0)for(var m=0;m0&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var t,e,i,n,r;for(i=0,n=this.faces.length;i0&&(t+=e[i].distanceTo(e[i-1])),this.lineDistances[i]=t},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E),this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new T),this.boundingSphere.setFromPoints(this.vertices)},merge:function(t,e,i){if((t&&t.isGeometry)===!1)return void console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",t);var n,r=this.vertices.length,a=this.vertices,o=t.vertices,s=this.faces,h=t.faces,c=this.faceVertexUvs[0],l=t.faceVertexUvs[0];void 0===i&&(i=0),void 0!==e&&(n=(new S).getNormalMatrix(e));for(var u=0,p=o.length;u=0;i--){var g=d[i];for(this.faces.splice(g,1),o=0,s=this.faceVertexUvs.length;o0,w=v.vertexNormals.length>0,M=1!==v.color.r||1!==v.color.g||1!==v.color.b,E=v.vertexColors.length>0,T=0;if(T=t(T,0,0),T=t(T,1,y),T=t(T,2,x),T=t(T,3,b),T=t(T,4,_),T=t(T,5,w),T=t(T,6,M),T=t(T,7,E),l.push(T),l.push(v.a,v.b,v.c),l.push(v.materialIndex),b){var S=this.faceVertexUvs[0][h];l.push(n(S[0]),n(S[1]),n(S[2]))}if(_&&l.push(e(v.normal)),w){var A=v.vertexNormals;l.push(e(A[0]),e(A[1]),e(A[2]))}if(M&&l.push(i(v.color)),E){var L=v.vertexColors;l.push(i(L[0]),i(L[1]),i(L[2]))}}return r.data={},r.data.vertices=s,r.data.normals=u,d.length>0&&(r.data.colors=d),m.length>0&&(r.data.uvs=[m]),r.data.faces=l,r},clone:function(){return(new q).copy(this)},copy:function(t){this.vertices=[],this.faces=[],this.faceVertexUvs=[[]];for(var e=t.vertices,i=0,n=e.length;i0,s=a[1]&&a[1].length>0,h=t.morphTargets,c=h.length;if(c>0){e=[];for(var l=0;l0){u=[];for(var l=0;l0){var i=new Float32Array(3*t.normals.length);this.addAttribute("normal",new U(i,3).copyVector3sArray(t.normals))}if(t.colors.length>0){var n=new Float32Array(3*t.colors.length);this.addAttribute("color",new U(n,3).copyColorsArray(t.colors))}if(t.uvs.length>0){var r=new Float32Array(2*t.uvs.length);this.addAttribute("uv",new U(r,2).copyVector2sArray(t.uvs))}if(t.uvs2.length>0){var a=new Float32Array(2*t.uvs2.length);this.addAttribute("uv2",new U(a,2).copyVector2sArray(t.uvs2))}if(t.indices.length>0){var o=t.vertices.length>65535?Uint32Array:Uint16Array,s=new o(3*t.indices.length);this.setIndex(new U(s,1).copyIndicesArray(t.indices))}this.groups=t.groups;for(var h in t.morphTargets){for(var c=[],l=t.morphTargets[h],u=0,p=l.length;u0){var m=new G(4*t.skinIndices.length,4);this.addAttribute("skinIndex",m.copyVector4sArray(t.skinIndices))}if(t.skinWeights.length>0){var g=new G(4*t.skinWeights.length,4);this.addAttribute("skinWeight",g.copyVector4sArray(t.skinWeights))}return null!==t.boundingSphere&&(this.boundingSphere=t.boundingSphere.clone()),null!==t.boundingBox&&(this.boundingBox=t.boundingBox.clone()),this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E);var t=this.attributes.position.array;void 0!==t?this.boundingBox.setFromArray(t):this.boundingBox.makeEmpty(),(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var t=new E,e=new s;return function(){null===this.boundingSphere&&(this.boundingSphere=new T);var i=this.attributes.position;if(i){var n=i.array,r=this.boundingSphere.center;t.setFromArray(n),t.center(r);for(var a=0,o=0,s=n.length;o0&&(t.data.groups=JSON.parse(JSON.stringify(s)));var h=this.boundingSphere;return null!==h&&(t.data.boundingSphere={center:h.center.toArray(),radius:h.radius}),t},clone:function(){return(new Q).copy(this)},copy:function(t){var e=t.index;null!==e&&this.setIndex(e.clone());var i=t.attributes;for(var n in i){var r=i[n];this.addAttribute(n,r.clone())}for(var a=t.groups,o=0,s=a.length;o0)if(s=p*f-d,h=p*d-f,l=u*g,s>=0)if(h>=-l)if(h<=l){var v=1/g;s*=v,h*=v,c=s*(s+p*h+2*d)+h*(p*s+h+2*f)+m}else h=u,s=Math.max(0,-(p*h+d)),c=-s*s+h*(h+2*f)+m;else h=-u,s=Math.max(0,-(p*h+d)),c=-s*s+h*(h+2*f)+m;else h<=-l?(s=Math.max(0,-(-p*u+d)),h=s>0?-u:Math.min(Math.max(-u,-f),u),c=-s*s+h*(h+2*f)+m):h<=l?(s=0,h=Math.min(Math.max(-u,-f),u),c=h*(h+2*f)+m):(s=Math.max(0,-(p*u+d)),h=s>0?u:Math.min(Math.max(-u,-f),u),c=-s*s+h*(h+2*f)+m);else h=p>0?-u:u,s=Math.max(0,-(p*h+d)),c=-s*s+h*(h+2*f)+m;return a&&a.copy(this.direction).multiplyScalar(s).add(this.origin),o&&o.copy(e).multiplyScalar(h).add(t),c}}(),intersectSphere:function(){var t=new s;return function(e,i){t.subVectors(e.center,this.origin);var n=t.dot(this.direction),r=t.dot(t)-n*n,a=e.radius*e.radius;if(r>a)return null;var o=Math.sqrt(a-r),s=n-o,h=n+o;return s<0&&h<0?null:s<0?this.at(h,i):this.at(s,i)}}(),intersectsSphere:function(t){return this.distanceToPoint(t.center)<=t.radius},distanceToPlane:function(t){var e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;var i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null},intersectPlane:function(t,e){var i=this.distanceToPlane(t);return null===i?null:this.at(i,e)},intersectsPlane:function(t){var e=t.distanceToPoint(this.origin);if(0===e)return!0;var i=t.normal.dot(this.direction);return i*e<0},intersectBox:function(t,e){var i,n,r,a,o,s,h=1/this.direction.x,c=1/this.direction.y,l=1/this.direction.z,u=this.origin;return h>=0?(i=(t.min.x-u.x)*h,n=(t.max.x-u.x)*h):(i=(t.max.x-u.x)*h,n=(t.min.x-u.x)*h),c>=0?(r=(t.min.y-u.y)*c,a=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,a=(t.min.y-u.y)*c),i>a||r>n?null:((r>i||i!==i)&&(i=r),(a=0?(o=(t.min.z-u.z)*l,s=(t.max.z-u.z)*l):(o=(t.max.z-u.z)*l,s=(t.min.z-u.z)*l),i>s||o>n?null:((o>i||i!==i)&&(i=o),(s=0?i:n,e)))},intersectsBox:function(){var t=new s;return function(e){return null!==this.intersectBox(e,t)}}(),intersectTriangle:function(){var t=new s,e=new s,i=new s,n=new s;return function(r,a,o,s,h){e.subVectors(a,r),i.subVectors(o,r),n.crossVectors(e,i);var c,l=this.direction.dot(n);if(l>0){if(s)return null;c=1}else{if(!(l<0))return null;c=-1,l=-l}t.subVectors(this.origin,r);var u=c*this.direction.dot(i.crossVectors(t,i));if(u<0)return null;var p=c*this.direction.dot(e.cross(t));if(p<0)return null;if(u+p>l)return null;var d=-c*t.dot(n);return d<0?null:this.at(d/l,h)}}(),applyMatrix4:function(t){return this.direction.add(this.origin).applyMatrix4(t),this.origin.applyMatrix4(t),this.direction.sub(this.origin),this.direction.normalize(),this},equals:function(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}},ct.prototype={constructor:ct,set:function(t,e){return this.start.copy(t),this.end.copy(e),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.start.copy(t.start),this.end.copy(t.end),this},center:function(t){var e=t||new s;return e.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(t){var e=t||new s;return e.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(t,e){var i=e||new s;return this.delta(i).multiplyScalar(t).add(this.start)},closestPointToPointParameter:function(){var e=new s,i=new s;return function(n,r){e.subVectors(n,this.start),i.subVectors(this.end,this.start);var a=i.dot(i),o=i.dot(e),s=o/a;return r&&(s=t.Math.clamp(s,0,1)),s}}(),closestPointToPoint:function(t,e,i){var n=this.closestPointToPointParameter(t,e),r=i||new s;return this.delta(r).multiplyScalar(n).add(this.start)},applyMatrix4:function(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this},equals:function(t){return t.start.equals(this.start)&&t.end.equals(this.end)}},lt.normal=function(){var t=new s;return function(e,i,n,r){var a=r||new s;a.subVectors(n,i),t.subVectors(e,i),a.cross(t);var o=a.lengthSq();return o>0?a.multiplyScalar(1/Math.sqrt(o)):a.set(0,0,0)}}(),lt.barycoordFromPoint=function(){var t=new s,e=new s,i=new s;return function(n,r,a,o,h){t.subVectors(o,r),e.subVectors(a,r),i.subVectors(n,r);var c=t.dot(t),l=t.dot(e),u=t.dot(i),p=e.dot(e),d=e.dot(i),f=c*p-l*l,m=h||new s;if(0===f)return m.set(-2,-1,-1);var g=1/f,v=(p*u-l*d)*g,y=(c*d-l*u)*g;return m.set(1-v-y,y,v)}}(),lt.containsPoint=function(){var t=new s;return function(e,i,n,r){var a=lt.barycoordFromPoint(e,i,n,r,t);return a.x>=0&&a.y>=0&&a.x+a.y<=1}}(),lt.prototype={constructor:lt,set:function(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this},setFromPointsAndIndices:function(t,e,i,n){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[n]),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this},area:function(){var t=new s,e=new s;return function(){return t.subVectors(this.c,this.b),e.subVectors(this.a,this.b),.5*t.cross(e).length()}}(),midpoint:function(t){var e=t||new s;return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(t){return lt.normal(this.a,this.b,this.c,t)},plane:function(t){var e=t||new A;return e.setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(t,e){return lt.barycoordFromPoint(t,this.a,this.b,this.c,e)},containsPoint:function(t){return lt.containsPoint(t,this.a,this.b,this.c)},closestPointToPoint:function(){var t,e,i,n;return function(r,a){void 0===t&&(t=new A,e=[new ct,new ct,new ct],i=new s,n=new s);var o=a||new s,h=1/0;if(t.setFromCoplanarPoints(this.a,this.b,this.c),t.projectPoint(r,i),this.containsPoint(i)===!0)o.copy(i);else{e[0].set(this.a,this.b),e[1].set(this.b,this.c),e[2].set(this.c,this.a);for(var c=0;c0){this.morphTargetBase=-1,this.morphTargetInfluences=[],this.morphTargetDictionary={};for(var t=0,e=this.geometry.morphTargets.length;te.far?null:{distance:c,point:b.clone(),object:t}}function n(i,n,r,a,o,s,h,p){c.fromArray(a,3*s),l.fromArray(a,3*h),u.fromArray(a,3*p);var d=e(i,n,r,c,l,u,x);return d&&(o&&(m.fromArray(o,2*s),g.fromArray(o,2*h),v.fromArray(o,2*p),d.uv=t(x,c,l,u,m,g,v)),d.face=new k(s,h,p,lt.normal(c,l,u)),d.faceIndex=s),d}var r=new a,o=new ht,h=new T,c=new s,l=new s,u=new s,p=new s,d=new s,f=new s,m=new i,g=new i,v=new i,y=new s,x=new s,b=new s;return function(i,a){var s=this.geometry,y=this.material,b=this.matrixWorld;if(void 0!==y&&(null===s.boundingSphere&&s.computeBoundingSphere(),h.copy(s.boundingSphere),h.applyMatrix4(b),i.ray.intersectsSphere(h)!==!1&&(r.getInverse(b),o.copy(i.ray).applyMatrix4(r),null===s.boundingBox||o.intersectsBox(s.boundingBox)!==!1))){var _,w;if(s&&s.isBufferGeometry){var M,E,T,S=s.index,A=s.attributes,L=A.position.array;if(void 0!==A.uv&&(_=A.uv.array),null!==S)for(var R=S.array,P=0,C=R.length;P0&&(_=z);for(var G=0,H=B.length;Gr||i.push({distance:Math.sqrt(n),point:this.position,face:null,object:this})}}(),clone:function(){return new this.constructor(this.material).copy(this)}}),Et.prototype=Object.assign(Object.create(X.prototype),{constructor:Et,copy:function(t){X.prototype.copy.call(this,t,!1);for(var e=t.levels,i=0,n=e.length;i1){t.setFromMatrixPosition(i.matrixWorld),e.setFromMatrixPosition(this.matrixWorld);var r=t.distanceTo(e);n[0].object.visible=!0;for(var a=1,o=n.length;a=n[a].distance;a++)n[a-1].object.visible=!1,n[a].object.visible=!0;for(;ao)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}else for(var x=0,b=v.length/3-1;xo)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}else if(h&&h.isGeometry)for(var T=h.vertices,S=T.length,x=0;xo)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}}),Ct.prototype=Object.assign(Object.create(Pt.prototype),{constructor:Ct}),Ut.prototype=Object.create(x.prototype),Ut.prototype.constructor=Ut,Ut.prototype.copy=function(t){return x.prototype.copy.call(this,t),this.color.copy(t.color),this.map=t.map,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this},It.prototype=Object.assign(Object.create(X.prototype),{constructor:It,raycast:function(){var t=new a,e=new ht,i=new T;return function(n,r){function a(t,i){var a=e.distanceSqToPoint(t);if(an.far)return;r.push({distance:h,distanceToRay:Math.sqrt(a),point:s.clone(),index:i,face:null,object:o})}}var o=this,h=this.geometry,c=this.matrixWorld,l=n.params.Points.threshold;if(null===h.boundingSphere&&h.computeBoundingSphere(),i.copy(h.boundingSphere),i.applyMatrix4(c),n.ray.intersectsSphere(i)!==!1){t.getInverse(c),e.copy(n.ray).applyMatrix4(t);var u=l/((this.scale.x+this.scale.y+this.scale.z)/3),p=u*u,d=new s;if(h&&h.isBufferGeometry){var f=h.index,m=h.attributes,g=m.position.array;if(null!==f)for(var v=f.array,y=0,x=v.length;y0||0===t.search(/^data\:image\/jpeg/);a.format=n?Br:zr,a.image=i,a.needsUpdate=!0,void 0!==e&&e(a)},i,r),a},setCrossOrigin:function(t){return this.crossOrigin=t,this},setPath:function(t){return this.path=t,this}}),ee.prototype=Object.assign(Object.create(X.prototype),{constructor:ee,copy:function(t){return X.prototype.copy.call(this,t),this.color.copy(t.color),this.intensity=t.intensity,this},toJSON:function(t){var e=X.prototype.toJSON.call(this,t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),e}}),ie.prototype=Object.assign(Object.create(ee.prototype),{constructor:ie,copy:function(t){return ee.prototype.copy.call(this,t),this.groundColor.copy(t.groundColor),this}}),Object.assign(ne.prototype,{copy:function(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this},clone:function(){return(new this.constructor).copy(this)}}),re.prototype=Object.assign(Object.create(ne.prototype),{constructor:re,update:function(e){var i=2*t.Math.RAD2DEG*e.angle,n=this.mapSize.width/this.mapSize.height,r=e.distance||500,a=this.camera;i===a.fov&&n===a.aspect&&r===a.far||(a.fov=i,a.aspect=n,a.far=r,a.updateProjectionMatrix())}}),ae.prototype=Object.assign(Object.create(ee.prototype),{constructor:ae,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),oe.prototype=Object.assign(Object.create(ee.prototype),{constructor:oe,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}),se.prototype=Object.assign(Object.create(ne.prototype),{constructor:se}),he.prototype=Object.assign(Object.create(ee.prototype),{constructor:he,copy:function(t){return ee.prototype.copy.call(this,t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),ce.prototype=Object.assign(Object.create(ee.prototype),{constructor:ce}),t.AnimationUtils={arraySlice:function(e,i,n){return t.AnimationUtils.isTypedArray(e)?new e.constructor(e.subarray(i,n)):e.slice(i,n)},convertArray:function(t,e,i){return!t||!i&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)},isTypedArray:function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},getKeyframeOrder:function(t){function e(e,i){return t[e]-t[i]}for(var i=t.length,n=new Array(i),r=0;r!==i;++r)n[r]=r;return n.sort(e),n},sortedArray:function(t,e,i){for(var n=t.length,r=new t.constructor(n),a=0,o=0;o!==n;++a)for(var s=i[a]*e,h=0;h!==e;++h)r[o++]=t[s+h];return r},flattenJSON:function(t,e,i,n){for(var r=1,a=t[0];void 0!==a&&void 0===a[n];)a=t[r++];if(void 0!==a){var o=a[n];if(void 0!==o)if(Array.isArray(o)){do o=a[n],void 0!==o&&(e.push(a.time),i.push.apply(i,o)),a=t[r++];while(void 0!==a)}else if(void 0!==o.toArray){do o=a[n],void 0!==o&&(e.push(a.time),o.toArray(i,i.length)),a=t[r++];while(void 0!==a)}else do o=a[n],void 0!==o&&(e.push(a.time),i.push(o)),a=t[r++];while(void 0!==a)}}},le.prototype={constructor:le,evaluate:function(t){var e=this.parameterPositions,i=this._cachedIndex,n=e[i],r=e[i-1];t:{e:{var a;i:{n:if(!(t=r)break t;var s=e[1];t=r)break e}a=i,i=0}}for(;i>>1;ti;)--o;if(++o,0!==a||o!==r){a>=o&&(o=Math.max(o,1),a=o-1);var s=this.getValueSize();this.times=t.AnimationUtils.arraySlice(n,a,o),this.values=t.AnimationUtils.arraySlice(this.values,a*s,o*s)}return this},validate:function(){var e=!0,i=this.getValueSize();i-Math.floor(i)!==0&&(console.error("invalid value size in track",this),e=!1);var n=this.times,r=this.values,a=n.length;0===a&&(console.error("track is empty",this),e=!1);for(var o=null,s=0;s!==a;s++){var h=n[s];if("number"==typeof h&&isNaN(h)){console.error("time is not a valid number",this,s,h),e=!1;break}if(null!==o&&o>h){console.error("out of order keys",this,s,h,o),e=!1;break}o=h}if(void 0!==r&&t.AnimationUtils.isTypedArray(r))for(var s=0,c=r.length;s!==c;++s){var l=r[s];if(isNaN(l)){console.error("value is not a valid number",this,s,l),e=!1;break}}return e},optimize:function(){for(var e=this.times,i=this.values,n=this.getValueSize(),r=1,a=1,o=e.length-1;a<=o;++a){var s=!1,h=e[a],c=e[a+1];if(h!==c&&(1!==a||h!==h[0]))for(var l=a*n,u=l-n,p=l+n,d=0;d!==n;++d){var f=i[l+d];if(f!==i[u+d]||f!==i[p+d]){s=!0;break}}if(s){if(a!==r){e[r]=e[a];for(var m=a*n,g=r*n,d=0;d!==n;++d)i[g+d]=i[m+d]}++r}}return r!==e.length&&(this.times=t.AnimationUtils.arraySlice(e,0,r),this.values=t.AnimationUtils.arraySlice(i,0,r*n)),this}},me.prototype=Object.assign(Object.create(Ss),{constructor:me,ValueTypeName:"vector"}),ge.prototype=Object.assign(Object.create(le.prototype),{constructor:ge,interpolate_:function(t,e,i,n){for(var r=this.resultBuffer,a=this.sampleValues,s=this.valueSize,h=t*s,c=(i-e)/(n-e),l=h+s;h!==l;h+=4)o.slerpFlat(r,0,a,h-s,a,h,c);return r}}),ve.prototype=Object.assign(Object.create(Ss),{constructor:ve,ValueTypeName:"quaternion",DefaultInterpolation:na,InterpolantFactoryMethodLinear:function(t){return new ge(this.times,this.values,this.getValueSize(),t)},InterpolantFactoryMethodSmooth:void 0}),ye.prototype=Object.assign(Object.create(Ss),{constructor:ye,ValueTypeName:"number"}),xe.prototype=Object.assign(Object.create(Ss),{constructor:xe,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:ia,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),be.prototype=Object.assign(Object.create(Ss),{constructor:be,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:ia,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),_e.prototype=Object.assign(Object.create(Ss),{constructor:_e,ValueTypeName:"color"}),we.prototype=Ss,Ss.constructor=we,Object.assign(we,{parse:function(e){if(void 0===e.type)throw new Error("track type undefined, can not parse");var i=we._getTrackTypeForValueTypeName(e.type);if(void 0===e.times){var n=[],r=[];t.AnimationUtils.flattenJSON(e.keys,n,r,"value"),e.times=n,e.values=r}return void 0!==i.parse?i.parse(e):new i(e.name,e.times,e.values,e.interpolation)},toJSON:function(e){var i,n=e.constructor;if(void 0!==n.toJSON)i=n.toJSON(e);else{i={name:e.name,times:t.AnimationUtils.convertArray(e.times,Array),values:t.AnimationUtils.convertArray(e.values,Array)};var r=e.getInterpolation();r!==e.DefaultInterpolation&&(i.interpolation=r)}return i.type=e.ValueTypeName,i},_getTrackTypeForValueTypeName:function(t){switch(t.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return ye;case"vector":case"vector2":case"vector3":case"vector4":return me;case"color":return _e;case"quaternion":return ve;case"bool":case"boolean":return be;case"string":return xe}throw new Error("Unsupported typeName: "+t)}}),Me.prototype={constructor:Me,resetDuration:function(){for(var t=this.tracks,e=0,i=0,n=t.length;i!==n;++i){var r=this.tracks[i];e=Math.max(e,r.times[r.times.length-1])}this.duration=e},trim:function(){for(var t=0;t1){var c=h[1],l=n[c];l||(n[c]=l=[]),l.push(s)}}var u=[];for(var c in n)u.push(Me.CreateFromMorphTargetSequence(c,n[c],e,i));return u},parseAnimation:function(e,i,n){if(!e)return console.error(" no animation in JSONLoader data"),null;for(var r=function(e,i,n,r,a){if(0!==n.length){var o=[],s=[];t.AnimationUtils.flattenJSON(n,o,s,r),0!==o.length&&a.push(new e(i,o,s))}},a=[],o=e.name||"default",s=e.length||-1,h=e.fps||30,c=e.hierarchy||[],l=0;l1?t.skinWeights[i+1]:0,o=e>2?t.skinWeights[i+2]:0,s=e>3?t.skinWeights[i+3]:0;h.skinWeights.push(new d(r,a,o,s))}if(t.skinIndices)for(var i=0,n=t.skinIndices.length;i1?t.skinIndices[i+1]:0,u=e>2?t.skinIndices[i+2]:0,p=e>3?t.skinIndices[i+3]:0;h.skinIndices.push(new d(c,l,u,p))}h.bones=t.bones,h.bones&&h.bones.length>0&&(h.skinWeights.length!==h.skinIndices.length||h.skinIndices.length!==h.vertices.length)&&console.warn("When skinning, number of vertices ("+h.vertices.length+"), skinIndices ("+h.skinIndices.length+"), and skinWeights ("+h.skinWeights.length+") should match.")}function a(e){if(void 0!==t.morphTargets)for(var i=0,n=t.morphTargets.length;i0){console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.');for(var u=h.faces,p=t.morphColors[0].colors,i=0,n=u.length;i0&&(h.animations=e)}var h=new q,c=void 0!==t.scale?1/t.scale:1;if(n(c),r(),a(c),o(),h.computeFaceNormals(),h.computeBoundingSphere(),void 0===t.materials||0===t.materials.length)return{geometry:h};var l=Se.prototype.initMaterials(t.materials,e,this.crossOrigin);return{geometry:h,materials:l}}}),Object.assign(Le.prototype,{load:function(t,e,i,n){""===this.texturePath&&(this.texturePath=t.substring(0,t.lastIndexOf("/")+1));var r=this,a=new Zt(r.manager);a.load(t,function(t){r.parse(JSON.parse(t),e)},i,n)},setTexturePath:function(t){this.texturePath=t},setCrossOrigin:function(t){this.crossOrigin=t},parse:function(t,e){var i=this.parseGeometries(t.geometries),n=this.parseImages(t.images,function(){void 0!==e&&e(o)}),r=this.parseTextures(t.textures,n),a=this.parseMaterials(t.materials,r),o=this.parseObject(t.object,i,a);return t.animations&&(o.animations=this.parseAnimations(t.animations)),void 0!==t.images&&0!==t.images.length||void 0!==e&&e(o),o},parseGeometries:function(t){var e={};if(void 0!==t)for(var i=new Ae,n=new Te,r=0,a=t.length;r0){var a=new qt(e),o=new Kt(a);o.setCrossOrigin(this.crossOrigin);for(var s=0,h=t.length;s0?new Lt(s,h):new pt(s,h);break;case"LOD":o=new Et;break;case"Line":o=new Pt(r(e.geometry),a(e.material),e.mode);break;case"PointCloud":case"Points":o=new It(r(e.geometry),a(e.material));break;case"Sprite":o=new Mt(a(e.material));break;case"Group":o=new Dt;break;default:o=new X}if(o.uuid=e.uuid,void 0!==e.name&&(o.name=e.name),void 0!==e.matrix?(t.fromArray(e.matrix),t.decompose(o.position,o.quaternion,o.scale)):(void 0!==e.position&&o.position.fromArray(e.position),void 0!==e.rotation&&o.rotation.fromArray(e.rotation),void 0!==e.scale&&o.scale.fromArray(e.scale)),void 0!==e.castShadow&&(o.castShadow=e.castShadow),void 0!==e.receiveShadow&&(o.receiveShadow=e.receiveShadow),void 0!==e.visible&&(o.visible=e.visible),void 0!==e.userData&&(o.userData=e.userData),void 0!==e.children)for(var c in e.children)o.add(this.parseObject(e.children[c],i,n));if("LOD"===e.type)for(var l=e.levels,u=0;u(c-s)*(p-h)-(l-h)*(u-s))return!1;var m,g,v,y,x,b,_,w,M,E,T,S,A,L,R;for(m=u-c,g=p-l,v=s-u,y=h-p,x=c-s,b=l-h,o=0;o=-Number.EPSILON&&L>=-Number.EPSILON&&A>=-Number.EPSILON))return!1;return!0}return function(i,n){var r=i.length;if(r<3)return null;var a,o,s,h=[],c=[],l=[];if(t.ShapeUtils.area(i)>0)for(o=0;o2;){if(p--<=0)return console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()"),n?l:h;if(a=o,u<=a&&(a=0),o=a+1,u<=o&&(o=0),s=o+1,u<=s&&(s=0),e(i,a,o,s,u,c)){var d,f,m,g,v;for(d=c[a],f=c[o],m=c[s],h.push([i[d],i[f],i[m]]),l.push([c[a],c[o],c[s]]),g=o,v=o+1;v2&&t[e-1].equals(t[0])&&t.pop()}function r(t,e,i){return t.x!==e.x?t.xNumber.EPSILON){var f;if(p>0){if(d<0||d>p)return[];if(f=c*l-h*u,f<0||f>p)return[]}else{if(d>0||d0||fT?[]:b===T?a?[]:[y]:_<=T?[y,x]:[y,M]}function o(t,e,i,n){var r=e.x-t.x,a=e.y-t.y,o=i.x-t.x,s=i.y-t.y,h=n.x-t.x,c=n.y-t.y,l=r*s-a*o,u=r*c-a*h;if(Math.abs(l)>Number.EPSILON){var p=h*s-c*o;return l>0?u>=0&&p>=0:u>=0||p>=0}return u>0}function s(t,e){function i(t,e){var i=y.length-1,n=t-1;n<0&&(n=i);var r=t+1;r>i&&(r=0);var a=o(y[t],y[n],y[r],s[e]);if(!a)return!1;var h=s.length-1,c=e-1;c<0&&(c=h);var l=e+1;return l>h&&(l=0),a=o(s[e],s[c],s[l],y[t]),!!a}function n(t,e){var i,n,r;for(i=0;i0)return!0;return!1}function r(t,i){var n,r,o,s,h;for(n=0;n0)return!0;return!1}for(var s,h,c,l,u,p,d,f,m,g,v,y=t.concat(),x=[],b=[],_=0,w=e.length;_0;){if(E--,E<0){console.log("Infinite Loop! Holes left:"+x.length+", Probably Hole outside Shape!");break}for(c=M;c=0)break;b[d]=!0}if(h>=0)break}}return y}n(e),i.forEach(n);for(var h,c,l,u,p,d,f={},m=e.concat(),g=0,v=i.length;g0)){h=r;break}h=r-1}if(r=h,n[r]===i){var c=r/(a-1);return c}var l=n[r],u=n[r+1],p=u-l,d=(i-l)/p,c=(r+d)/(a-1);return c},getTangent:function(t){var e=1e-4,i=t-e,n=t+e;i<0&&(i=0),n>1&&(n=1);var r=this.getPoint(i),a=this.getPoint(n),o=a.clone().sub(r);return o.normalize()},getTangentAt:function(t){var e=this.getUtoTmapping(t);return this.getTangent(e)}},Re.create=function(t,e){return t.prototype=Object.create(Re.prototype),t.prototype.constructor=t,t.prototype.getPoint=e,t},Pe.prototype=Object.create(Re.prototype),Pe.prototype.constructor=Pe,Pe.prototype.getPoint=function(t){if(1===t)return this.v2.clone();var e=this.v2.clone().sub(this.v1);return e.multiplyScalar(t).add(this.v1),e},Pe.prototype.getPointAt=function(t){return this.getPoint(t)},Pe.prototype.getTangent=function(t){var e=this.v2.clone().sub(this.v1);return e.normalize()},Ce.prototype=Object.assign(Object.create(Re.prototype),{constructor:Ce,add:function(t){this.curves.push(t)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);t.equals(e)||this.curves.push(new Pe(e,t))},getPoint:function(t){for(var e=t*this.getLength(),i=this.getCurveLengths(),n=0;n=e){var r=i[n]-e,a=this.curves[n],o=a.getLength(),s=0===o?0:1-r/o;return a.getPointAt(s)}n++}return null},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},updateArcLengths:function(){this.needsUpdate=!0,this.cacheLengths=null,this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var t=[],e=0,i=0,n=this.curves.length;i1&&!i[i.length-1].equals(i[0])&&i.push(i[0]),i},createPointsGeometry:function(t){var e=this.getPoints(t);return this.createGeometry(e)},createSpacedPointsGeometry:function(t){var e=this.getSpacedPoints(t);return this.createGeometry(e)},createGeometry:function(t){for(var e=new q,i=0,n=t.length;ie;)n-=e;nn.length-2?n.length-1:a+1],l=n[a>n.length-3?n.length-1:a+2],u=t.CurveUtils.interpolate;return new i(u(s.x,h.x,c.x,l.x,o),u(s.y,h.y,c.y,l.y,o))},De.prototype=Object.create(Re.prototype),De.prototype.constructor=De,De.prototype.getPoint=function(e){var n=t.ShapeUtils.b3;return new i(n(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y))},De.prototype.getTangent=function(e){var n=t.CurveUtils.tangentCubicBezier;return new i(n(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y)).normalize()},Ne.prototype=Object.create(Re.prototype),Ne.prototype.constructor=Ne,Ne.prototype.getPoint=function(e){var n=t.ShapeUtils.b2;return new i(n(e,this.v0.x,this.v1.x,this.v2.x),n(e,this.v0.y,this.v1.y,this.v2.y))},Ne.prototype.getTangent=function(e){var n=t.CurveUtils.tangentQuadraticBezier;return new i(n(e,this.v0.x,this.v1.x,this.v2.x),n(e,this.v0.y,this.v1.y,this.v2.y)).normalize()};var As;As=Object.assign(Object.create(Ce.prototype),{fromPoints:function(t){this.moveTo(t[0].x,t[0].y);for(var e=1,i=t.length;e0){var c=h.getPoint(0);c.equals(this.currentPoint)||this.lineTo(c.x,c.y)}this.curves.push(h);var l=h.getPoint(1);this.currentPoint.copy(l)}}),Oe.prototype=Object.create(q.prototype),Oe.prototype.constructor=Oe,Oe.NoTaper=function(t){return 1},Oe.SinusoidalTaper=function(t){return Math.sin(Math.PI*t)},Oe.FrenetFrames=function(e,i,n){function r(){g[0]=new s,v[0]=new s,h=Number.MAX_VALUE,c=Math.abs(m[0].x),l=Math.abs(m[0].y),u=Math.abs(m[0].z),c<=h&&(h=c,f.set(1,0,0)),l<=h&&(h=l,f.set(0,1,0)),u<=h&&f.set(0,0,1),y.crossVectors(m[0],f).normalize(),g[0].crossVectors(m[0],y),v[0].crossVectors(m[0],g[0])}var o,h,c,l,u,p,d,f=new s,m=[],g=[],v=[],y=new s,x=new a,b=i+1;for(this.tangents=m,this.normals=g,this.binormals=v,p=0;pNumber.EPSILON&&(y.normalize(),o=Math.acos(t.Math.clamp(m[p-1].dot(m[p]),-1,1)),g[p].applyMatrix4(x.makeRotationAxis(y,o))),v[p].crossVectors(m[p],g[p]);if(n)for(o=Math.acos(t.Math.clamp(g[0].dot(g[b-1]),-1,1)),o/=b-1,m[0].dot(y.crossVectors(g[0],g[b-1]))>0&&(o=-o),p=1;pNumber.EPSILON){var d=Math.sqrt(u),f=Math.sqrt(c*c+l*l),m=e.x-h/d,g=e.y+s/d,v=n.x-l/f,y=n.y+c/f,x=((v-m)*l-(y-g)*c)/(s*l-h*c);r=m+s*x-t.x,a=g+h*x-t.y;var b=r*r+a*a;if(b<=2)return new i(r,a);o=Math.sqrt(b/2)}else{var _=!1;s>Number.EPSILON?c>Number.EPSILON&&(_=!0):s<-Number.EPSILON?c<-Number.EPSILON&&(_=!0):Math.sign(h)===Math.sign(l)&&(_=!0),_?(r=-h,a=s,o=Math.sqrt(u)):(r=s,a=h,o=Math.sqrt(u/2))}return new i(r/o,a/o)}function o(){if(w){var t=0,e=X*t;for(Z=0;Z=0;){i=Z,n=Z-1,n<0&&(n=t.length-1);var r=0,a=E+2*_;for(r=0;r=0;z--){for(H=z/_,V=x*(1-H),G=b*Math.sin(H*Math.PI/2),Z=0,J=B.length;ZNumber.EPSILON){if(c<0&&(o=e[a],h=-h,s=e[r],c=-c),t.ys.y)continue;if(t.y===o.y){if(t.x===o.x)return!0}else{var l=c*(t.x-o.x)-h*(t.y-o.y);if(0===l)return!0;if(l<0)continue;n=!n}}else{if(t.y!==o.y)continue;if(s.x<=t.x&&t.x<=o.x||o.x<=t.x&&t.x<=s.x)return!0}}return n}var a=t.ShapeUtils.isClockWise,o=this.subPaths;if(0===o.length)return[];if(i===!0)return n(o);var s,h,c,l=[];if(1===o.length)return h=o[0],c=new ze,c.curves=h.curves,l.push(c),l;var u=!a(o[0].getPoints());u=e?!u:u;var p,d=[],f=[],m=[],g=0;f[g]=void 0,m[g]=[];for(var v=0,y=o.length;v1){for(var x=!1,b=[],_=0,w=f.length;_0&&(x||(m=d))}for(var L,v=0,R=f.length;v0){this.source.connect(this.filters[0]);for(var t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(var t=1,e=this.filters.length;t=.5)for(var a=0;a!==r;++a)t[e+a]=t[i+a]},_slerp:function(t,e,i,n,r){o.slerpFlat(t,e,t,e,t,i,n)},_lerp:function(t,e,i,n,r){for(var a=1-n,o=0;o!==r;++o){var s=e+o;t[s]=t[s]*a+t[i+o]*n}}},$e.prototype={constructor:$e,getValue:function(t,e){this.bind(),this.getValue(t,e)},setValue:function(t,e){this.bind(),this.setValue(t,e)},bind:function(){var t=this.node,e=this.parsedPath,i=e.objectName,n=e.propertyName,r=e.propertyIndex;if(t||(t=$e.findNode(this.rootNode,e.nodeName)||this.rootNode,this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t)return void console.error(" trying to update node for track: "+this.path+" but it wasn't found.");if(i){var a=e.objectIndex;switch(i){case"materials":if(!t.material)return void console.error(" can not bind to material as node does not have a material",this);if(!t.material.materials)return void console.error(" can not bind to material.materials as node.material does not have a materials array",this);t=t.material.materials;break;case"bones":if(!t.skeleton)return void console.error(" can not bind to bones as node does not have a skeleton",this);t=t.skeleton.bones;for(var o=0;o=i){var u=i++,p=e[u];n[p.uuid]=l,e[l]=p,n[c]=u,e[u]=h;for(var d=0,f=a;d!==f;++d){var m=r[d],g=m[u],v=m[l];m[l]=g,m[u]=v}}}this.nCachedObjects_=i},uncache:function(t){for(var e=this._objects,i=e.length,n=this.nCachedObjects_,r=this._indicesByUUID,a=this._bindings,o=a.length,s=0,h=arguments.length;s!==h;++s){var c=arguments[s],l=c.uuid,u=r[l];if(void 0!==u)if(delete r[l],u0)for(var h=this._interpolants,c=this._propertyBindings,l=0,u=h.length;l!==u;++l)h[l].evaluate(o),c[l].accumulate(n,s)},_updateWeight:function(t){var e=0;if(this.enabled){e=this.weight;var i=this._weightInterpolant;if(null!==i){var n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopFading(),0===n&&(this.enabled=!1))}}return this._effectiveWeight=e,e},_updateTimeScale:function(t){var e=0;if(!this.paused){e=this.timeScale;var i=this._timeScaleInterpolant;if(null!==i){var n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e},_updateTime:function(t){var e=this.time+t;if(0===t)return e;var i=this._clip.duration,n=this.loop,r=this._loopCount;if(n===$r){r===-1&&(this.loopCount=0,this._setEndings(!0,!0,!1));t:{if(e>=i)e=i;else{if(!(e<0))break t;e=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{var a=n===ea;if(r===-1&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,a)):this._setEndings(0===this.repetitions,!0,a)),e>=i||e<0){var o=Math.floor(e/i);e-=i*o,r+=Math.abs(o);var s=this.repetitions-r;if(s<0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,e=t>0?i:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(0===s){var h=t<0;this._setEndings(h,!h,a)}else this._setEndings(!1,!1,a);this._loopCount=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}if(a&&1===(1&r))return this.time=e,i-e}return this.time=e,e},_setEndings:function(t,e,i){var n=this._interpolantSettings;i?(n.endingStart=oa,n.endingEnd=oa):(t?n.endingStart=this.zeroSlopeAtStart?oa:aa:n.endingStart=sa,e?n.endingEnd=this.zeroSlopeAtEnd?oa:aa:n.endingEnd=sa)},_scheduleFading:function(t,e,i){var n=this._mixer,r=n.time,a=this._weightInterpolant;null===a&&(a=n._lendControlInterpolant(),this._weightInterpolant=a);var o=a.parameterPositions,s=a.sampleValues;return o[0]=r,s[0]=e,o[1]=r+t,s[1]=i,this}},Object.assign(ii.prototype,e.prototype,{clipAction:function(t,e){var i=e||this._root,n=i.uuid,r="string"==typeof t?Me.findByName(i,t):t,a=null!==r?r.uuid:t,o=this._actionsByClip[a],s=null;if(void 0!==o){var h=o.actionByRoot[n];if(void 0!==h)return h;s=o.knownActions[0],null===r&&(r=s._clip)}if(null===r)return null;var c=new ii._Action(this,r,e);return this._bindAction(c,s),this._addInactiveAction(c,a,n),c},existingAction:function(t,e){var i=e||this._root,n=i.uuid,r="string"==typeof t?Me.findByName(i,t):t,a=r?r.uuid:t,o=this._actionsByClip[a];return void 0!==o?o.actionByRoot[n]||null:null},stopAllAction:function(){var t=this._actions,e=this._nActiveActions,i=this._bindings,n=this._nActiveBindings;this._nActiveActions=0,this._nActiveBindings=0;for(var r=0;r!==e;++r)t[r].reset();for(var r=0;r!==n;++r)i[r].useCount=0;return this},update:function(t){t*=this.timeScale;for(var e=this._actions,i=this._nActiveActions,n=this.time+=t,r=Math.sign(t),a=this._accuIndex^=1,o=0;o!==i;++o){var s=e[o];s.enabled&&s._update(n,t,r,a)}for(var h=this._bindings,c=this._nActiveBindings,o=0;o!==c;++o)h[o].apply(a);return this},getRoot:function(){return this._root},uncacheClip:function(t){var e=this._actions,i=t.uuid,n=this._actionsByClip,r=n[i];if(void 0!==r){for(var a=r.knownActions,o=0,s=a.length;o!==s;++o){var h=a[o];this._deactivateAction(h);var c=h._cacheIndex,l=e[e.length-1];h._cacheIndex=null,h._byClipCacheIndex=null,l._cacheIndex=c,e[c]=l,e.pop(),this._removeInactiveBindingsForAction(h)}delete n[i]}},uncacheRoot:function(t){var e=t.uuid,i=this._actionsByClip;for(var n in i){var r=i[n].actionByRoot,a=r[e];void 0!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}var o=this._bindingsByRootAndName,s=o[e];if(void 0!==s)for(var h in s){var c=s[h];c.restoreOriginalState(),this._removeInactiveBinding(c)}},uncacheAction:function(t,e){var i=this.existingAction(t,e);null!==i&&(this._deactivateAction(i),this._removeInactiveAction(i))}}),ii._Action=ei._new,Object.assign(ii.prototype,{_bindAction:function(t,e){var i=t._localRoot||this._root,n=t._clip.tracks,r=n.length,a=t._propertyBindings,o=t._interpolants,s=i.uuid,h=this._bindingsByRootAndName,c=h[s];void 0===c&&(c={},h[s]=c);for(var l=0;l!==r;++l){var u=n[l],p=u.name,d=c[p];if(void 0!==d)a[l]=d;else{if(d=a[l],void 0!==d){null===d._cacheIndex&&(++d.referenceCount,this._addInactiveBinding(d,s,p));continue}var f=e&&e._propertyBindings[l].binding.parsedPath;d=new Ke($e.create(i,p,f),u.ValueTypeName,u.getValueSize()),++d.referenceCount,this._addInactiveBinding(d,s,p),a[l]=d}o[l].resultBuffer=d.buffer}},_activateAction:function(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){var e=(t._localRoot||this._root).uuid,i=t._clip.uuid,n=this._actionsByClip[i];this._bindAction(t,n&&n.knownActions[0]),this._addInactiveAction(t,i,e)}for(var r=t._propertyBindings,a=0,o=r.length;a!==o;++a){var s=r[a];0===s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(t)}},_deactivateAction:function(t){if(this._isActiveAction(t)){for(var e=t._propertyBindings,i=0,n=e.length;i!==n;++i){var r=e[i];0===--r.useCount&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(t)}},_initMemoryManager:function(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;var t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}},_isActiveAction:function(t){var e=t._cacheIndex;return null!==e&&e1){var c=h[1];n[c]||(n[c]={start:1/0,end:-(1/0)});var l=n[c];al.end&&(l.end=a),e||(e=c)}}for(var c in n){var l=n[c];this.createAnimation(c,l.start,l.end,t)}this.firstAnimation=e},mi.prototype.setAnimationDirectionForward=function(t){var e=this.animationsMap[t];e&&(e.direction=1,e.directionBackwards=!1)},mi.prototype.setAnimationDirectionBackward=function(t){var e=this.animationsMap[t];e&&(e.direction=-1,e.directionBackwards=!0)},mi.prototype.setAnimationFPS=function(t,e){var i=this.animationsMap[t];i&&(i.fps=e,i.duration=(i.end-i.start)/i.fps)},mi.prototype.setAnimationDuration=function(t,e){var i=this.animationsMap[t];i&&(i.duration=e,i.fps=(i.end-i.start)/i.duration)},mi.prototype.setAnimationWeight=function(t,e){var i=this.animationsMap[t];i&&(i.weight=e)},mi.prototype.setAnimationTime=function(t,e){var i=this.animationsMap[t];i&&(i.time=e)},mi.prototype.getAnimationTime=function(t){var e=0,i=this.animationsMap[t];return i&&(e=i.time),e},mi.prototype.getAnimationDuration=function(t){var e=-1,i=this.animationsMap[t];return i&&(e=i.duration),e},mi.prototype.playAnimation=function(t){var e=this.animationsMap[t];e?(e.time=0,e.active=!0):console.warn("THREE.MorphBlendMesh: animation["+t+"] undefined in .playAnimation()")},mi.prototype.stopAnimation=function(t){var e=this.animationsMap[t];e&&(e.active=!1)},mi.prototype.update=function(e){for(var i=0,n=this.animationsList.length;ir.duration||r.time<0)&&(r.direction*=-1,r.time>r.duration&&(r.time=r.duration,r.directionBackwards=!0),r.time<0&&(r.time=0,r.directionBackwards=!1)):(r.time=r.time%r.duration,r.time<0&&(r.time+=r.duration));var o=r.start+t.Math.clamp(Math.floor(r.time/a),0,r.length-1),s=r.weight;o!==r.currentFrame&&(this.morphTargetInfluences[r.lastFrame]=0,this.morphTargetInfluences[r.currentFrame]=1*s,this.morphTargetInfluences[o]=0,r.lastFrame=r.currentFrame,r.currentFrame=o);var h=r.time%a/a;r.directionBackwards&&(h=1-h),r.currentFrame!==r.lastFrame?(this.morphTargetInfluences[r.currentFrame]=h*s,this.morphTargetInfluences[r.lastFrame]=(1-h)*s):this.morphTargetInfluences[r.currentFrame]=s}}},gi.prototype=Object.create(X.prototype),gi.prototype.constructor=gi,vi.prototype=Object.create(Q.prototype),vi.prototype.constructor=vi,yi.prototype=Object.create(Ct.prototype),yi.prototype.constructor=yi,xi.prototype=Object.create(Ct.prototype),xi.prototype.constructor=xi,xi.prototype.update=function(){var t=new s,e=new s,i=new S;return function(){var n=["a","b","c"];this.object.updateMatrixWorld(!0),i.getNormalMatrix(this.object.matrixWorld);var r=this.object.matrixWorld,a=this.geometry.attributes.position,o=this.object.geometry;if(o&&o.isGeometry)for(var s=o.vertices,h=o.faces,c=0,l=0,u=h.length;l.99999?this.quaternion.set(0,0,0,1):i.y<-.99999?this.quaternion.set(1,0,0,0):(e.set(i.z,0,-i.x).normalize(),t=Math.acos(i.y),this.quaternion.setFromAxisAngle(e,t))}}(),t.ArrowHelper.prototype.setLength=function(t,e,i){void 0===e&&(e=.2*t),void 0===i&&(i=.2*e),this.line.scale.set(1,Math.max(0,t-e),1),this.line.updateMatrix(),this.cone.scale.set(i,e,i),this.cone.position.y=t,this.cone.updateMatrix()},t.ArrowHelper.prototype.setColor=function(t){this.line.material.color.copy(t),this.cone.material.color.copy(t)},Oi.prototype=Object.create(Ct.prototype),Oi.prototype.constructor=Oi,Fi.prototype=Object.create(q.prototype),Fi.prototype.constructor=Fi,Bi.prototype=Object.create(q.prototype),Bi.prototype.constructor=Bi,zi.prototype=Object.create(Bi.prototype),zi.prototype.constructor=zi,Gi.prototype=Object.create(Bi.prototype),Gi.prototype.constructor=Gi,Hi.prototype=Object.create(Bi.prototype),Hi.prototype.constructor=Hi,Vi.prototype=Object.create(Bi.prototype),Vi.prototype.constructor=Vi,ki.prototype=Object.create(Q.prototype),ki.prototype.constructor=ki,ji.prototype=Object.create(q.prototype),ji.prototype.constructor=ji,Wi.prototype=Object.create(Q.prototype),Wi.prototype.constructor=Wi,Xi.prototype=Object.create(q.prototype),Xi.prototype.constructor=Xi,Yi.prototype=Object.create(Fe.prototype),Yi.prototype.constructor=Yi,qi.prototype=Object.create(Q.prototype),qi.prototype.constructor=qi,Zi.prototype=Object.create(q.prototype),Zi.prototype.constructor=Zi,Ji.prototype=Object.create(q.prototype),Ji.prototype.constructor=Ji,Qi.prototype=Object.create(Q.prototype),Qi.prototype.constructor=Qi,Ki.prototype=Object.create(q.prototype),Ki.prototype.constructor=Ki,$i.prototype=Object.create(q.prototype),$i.prototype.constructor=$i,tn.prototype=Object.create($i.prototype),tn.prototype.constructor=tn,en.prototype=Object.create(Q.prototype),en.prototype.constructor=en,nn.prototype=Object.create(Q.prototype),nn.prototype.constructor=nn,rn.prototype=Object.create(q.prototype),rn.prototype.constructor=rn,t.CatmullRomCurve3=function(){function t(){}var e=new s,i=new t,n=new t,r=new t;return t.prototype.init=function(t,e,i,n){this.c0=t,this.c1=i,this.c2=-3*t+3*e-2*i-n,this.c3=2*t-2*e+i+n},t.prototype.initNonuniformCatmullRom=function(t,e,i,n,r,a,o){var s=(e-t)/r-(i-t)/(r+a)+(i-e)/a,h=(i-e)/a-(n-e)/(a+o)+(n-i)/o;s*=a,h*=a,this.init(e,i,s,h)},t.prototype.initCatmullRom=function(t,e,i,n,r){this.init(e,i,r*(i-t),r*(n-e))},t.prototype.calc=function(t){var e=t*t,i=e*t;return this.c0+this.c1*t+this.c2*e+this.c3*i},Re.create(function(t){this.points=t||[],this.closed=!1},function(t){var a,o,h,c,l=this.points;c=l.length,c<2&&console.log("duh, you need at least 2 points"),a=(c-(this.closed?0:1))*t,o=Math.floor(a),h=a-o,this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/l.length)+1)*l.length:0===h&&o===c-1&&(o=c-2,h=1);var u,p,d,f;if(this.closed||o>0?u=l[(o-1)%c]:(e.subVectors(l[0],l[1]).add(l[0]),u=e),p=l[o%c],d=l[(o+1)%c],this.closed||o+2i.length-2?i.length-1:r+1],l=i[r>i.length-3?i.length-1:r+2],u=t.CurveUtils.interpolate;return new s(u(o.x,h.x,c.x,l.x,a),u(o.y,h.y,c.y,l.y,a),u(o.z,h.z,c.z,l.z,a))}),t.CubicBezierCurve3=Re.create(function(t,e,i,n){this.v0=t,this.v1=e,this.v2=i,this.v3=n},function(e){var i=t.ShapeUtils.b3;return new s(i(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),i(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y),i(e,this.v0.z,this.v1.z,this.v2.z,this.v3.z))}),t.QuadraticBezierCurve3=Re.create(function(t,e,i){this.v0=t,this.v1=e,this.v2=i},function(e){var i=t.ShapeUtils.b2;return new s(i(e,this.v0.x,this.v1.x,this.v2.x),i(e,this.v0.y,this.v1.y,this.v2.y),i(e,this.v0.z,this.v1.z,this.v2.z))}),t.LineCurve3=Re.create(function(t,e){this.v1=t,this.v2=e},function(t){if(1===t)return this.v2.clone();var e=new s;return e.subVectors(this.v2,this.v1),e.multiplyScalar(t),e.add(this.v1),e}),on.prototype=Object.create(Ue.prototype),on.prototype.constructor=on,t.SceneUtils={createMultiMaterialObject:function(t,e){for(var i=new Dt,n=0,r=e.length;n 0.0 ) { + +#if defined ( PHYSICALLY_CORRECT_LIGHTS ) + + // based upon Frostbite 3 Moving to Physically-based Rendering + // page 32, equation 26: E[window1] + // http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf + // this is intended to be used on spot and point lights who are represented as luminous intensity + // but who must be converted to luminous irradiance for surface lighting calculation + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + float maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + return distanceFalloff * maxDistanceCutoffFactor; + +#else + + return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent ); + +#endif + + } + + return 1.0; +} + +vec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) { + + return RECIPROCAL_PI * diffuseColor; + +} // validated + + +vec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) { + + // Original approximation by Christophe Schlick '94 + //;float fresnel = pow( 1.0 - dotLH, 5.0 ); + + // Optimized variant (presented by Epic at SIGGRAPH '13) + float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH ); + + return ( 1.0 - specularColor ) * fresnel + specularColor; + +} // validated + + +// Microfacet Models for Refraction through Rough Surfaces - equation (34) +// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html +// alpha is "roughness squared" in Disney’s reparameterization +float G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) { + + // geometry term = G(l)⋅G(v) / 4(n⋅l)(n⋅v) + + float a2 = pow2( alpha ); + + float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + + return 1.0 / ( gl * gv ); + +} // validated + +// from page 12, listing 2 of http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf +float G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + + float a2 = pow2( alpha ); + + // dotNL and dotNV are explicitly swapped. This is not a mistake. + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + + return 0.5 / max( gv + gl, EPSILON ); +} + + + +// Microfacet Models for Refraction through Rough Surfaces - equation (33) +// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html +// alpha is "roughness squared" in Disney’s reparameterization +float D_GGX( const in float alpha, const in float dotNH ) { + + float a2 = pow2( alpha ); + + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1 + + return RECIPROCAL_PI * a2 / pow2( denom ); + +} + + +// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility +vec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) { + + float alpha = pow2( roughness ); // UE4's roughness + + vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir ); + + float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) ); + float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) ); + float dotNH = saturate( dot( geometry.normal, halfDir ) ); + float dotLH = saturate( dot( incidentLight.direction, halfDir ) ); + + vec3 F = F_Schlick( specularColor, dotLH ); + + float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + + float D = D_GGX( alpha, dotNH ); + + return F * ( G * D ); + +} // validated + + +// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile +vec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) { + + float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) ); + + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + + vec4 r = roughness * c0 + c1; + + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + + vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw; + + return specularColor * AB.x + AB.y; + +} // validated + + +float G_BlinnPhong_Implicit( /* const in float dotNL, const in float dotNV */ ) { + + // geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v) + return 0.25; + +} + +float D_BlinnPhong( const in float shininess, const in float dotNH ) { + + return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); + +} + +vec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) { + + vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir ); + + //float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) ); + //float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) ); + float dotNH = saturate( dot( geometry.normal, halfDir ) ); + float dotLH = saturate( dot( incidentLight.direction, halfDir ) ); + + vec3 F = F_Schlick( specularColor, dotLH ); + + float G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ ); + + float D = D_BlinnPhong( shininess, dotNH ); + + return F * ( G * D ); + +} // validated + +// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html +float GGXRoughnessToBlinnExponent( const in float ggxRoughness ) { + return ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 ); +} + +float BlinnExponentToGGXRoughness( const in float blinnExponent ) { + return sqrt( 2.0 / ( blinnExponent + 2.0 ) ); +} diff --git a/src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl new file mode 100644 index 00000000000000..c901f0b0135cc5 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl @@ -0,0 +1,40 @@ +#ifdef USE_BUMPMAP + + uniform sampler2D bumpMap; + uniform float bumpScale; + + // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen + // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html + + // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2) + + vec2 dHdxy_fwd() { + + vec2 dSTdx = dFdx( vUv ); + vec2 dSTdy = dFdy( vUv ); + + float Hll = bumpScale * texture2D( bumpMap, vUv ).x; + float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll; + float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll; + + return vec2( dBx, dBy ); + + } + + vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) { + + vec3 vSigmaX = dFdx( surf_pos ); + vec3 vSigmaY = dFdy( surf_pos ); + vec3 vN = surf_norm; // normalized + + vec3 R1 = cross( vSigmaY, vN ); + vec3 R2 = cross( vN, vSigmaX ); + + float fDet = dot( vSigmaX, R1 ); + + vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); + return normalize( abs( fDet ) * surf_norm - vGrad ); + + } + +#endif diff --git a/src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl b/src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl new file mode 100644 index 00000000000000..cc3008fcbfd6d0 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl @@ -0,0 +1,10 @@ +#if NUM_CLIPPING_PLANES > 0 + + for ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) { + + vec4 plane = clippingPlanes[ i ]; + if ( dot( vViewPosition, plane.xyz ) > plane.w ) discard; + + } + +#endif diff --git a/src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl new file mode 100644 index 00000000000000..3eb44cdadebebb --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl @@ -0,0 +1,9 @@ +#if NUM_CLIPPING_PLANES > 0 + + #if ! defined( PHYSICAL ) && ! defined( PHONG ) + varying vec3 vViewPosition; + #endif + + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl new file mode 100644 index 00000000000000..d83f96d56c1994 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl @@ -0,0 +1,3 @@ +#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG ) + varying vec3 vViewPosition; +#endif diff --git a/src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl b/src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl new file mode 100644 index 00000000000000..d3fa83858ea6c4 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl @@ -0,0 +1,4 @@ +#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG ) + vViewPosition = - mvPosition.xyz; +#endif + diff --git a/src/renderers/shaders/ShaderChunk/color_fragment.glsl b/src/renderers/shaders/ShaderChunk/color_fragment.glsl new file mode 100644 index 00000000000000..693fdf061c226f --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/color_fragment.glsl @@ -0,0 +1,5 @@ +#ifdef USE_COLOR + + diffuseColor.rgb *= vColor; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl new file mode 100644 index 00000000000000..4f59898b6ef7fd --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl @@ -0,0 +1,5 @@ +#ifdef USE_COLOR + + varying vec3 vColor; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl new file mode 100644 index 00000000000000..f3862c30b66d43 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl @@ -0,0 +1,5 @@ +#ifdef USE_COLOR + + varying vec3 vColor; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/color_vertex.glsl b/src/renderers/shaders/ShaderChunk/color_vertex.glsl new file mode 100644 index 00000000000000..7bd534d9cf170f --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/color_vertex.glsl @@ -0,0 +1,5 @@ +#ifdef USE_COLOR + + vColor.xyz = color.xyz; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/common.glsl b/src/renderers/shaders/ShaderChunk/common.glsl new file mode 100644 index 00000000000000..d62dafd587b63c --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/common.glsl @@ -0,0 +1,74 @@ +#define PI 3.14159265359 +#define PI2 6.28318530718 +#define RECIPROCAL_PI 0.31830988618 +#define RECIPROCAL_PI2 0.15915494 +#define LOG2 1.442695 +#define EPSILON 1e-6 + +#define saturate(a) clamp( a, 0.0, 1.0 ) +#define whiteCompliment(a) ( 1.0 - saturate( a ) ) + +float pow2( const in float x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); } +// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range. +// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/ +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract(sin(sn) * c); +} + +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; + +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; + +struct GeometricContext { + vec3 position; + vec3 normal; + vec3 viewDir; +}; + + +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + +} + +// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); + +} + +vec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) { + + float distance = dot( planeNormal, point - pointOnPlane ); + + return - distance * planeNormal + point; + +} + +float sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) { + + return sign( dot( point - pointOnPlane, planeNormal ) ); + +} + +vec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) { + + return lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine; + +} diff --git a/src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl b/src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl new file mode 100644 index 00000000000000..d23ab4596e13f4 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl @@ -0,0 +1,128 @@ +#ifdef ENVMAP_TYPE_CUBE_UV + +#define cubeUV_textureSize (1024.0) + +int getFaceFromDirection(vec3 direction) { + vec3 absDirection = abs(direction); + int face = -1; + if( absDirection.x > absDirection.z ) { + if(absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0 : 3; + else + face = direction.y > 0.0 ? 1 : 4; + } + else { + if(absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2 : 5; + else + face = direction.y > 0.0 ? 1 : 4; + } + return face; +} +#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0) +#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0)) + +vec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) { + float scale = exp2(cubeUV_maxLods1 - roughnessLevel); + float dxRoughness = dFdx(roughness); + float dyRoughness = dFdy(roughness); + vec3 dx = dFdx( vec * scale * dxRoughness ); + vec3 dy = dFdy( vec * scale * dyRoughness ); + float d = max( dot( dx, dx ), dot( dy, dy ) ); + // Clamp the value to the max mip level counts. hard coded to 6 mips + d = clamp(d, 1.0, cubeUV_rangeClamp); + float mipLevel = 0.5 * log2(d); + return vec2(floor(mipLevel), fract(mipLevel)); +} + +#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0) +#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize) + +vec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) { + mipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel; + float a = 16.0 * cubeUV_rcpTextureSize; + + vec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) ); + vec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed; + // float powScale = exp2(roughnessLevel + mipLevel); + float powScale = exp2_packed.x * exp2_packed.y; + // float scale = 1.0 / exp2(roughnessLevel + 2.0 + mipLevel); + float scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25; + // float mipOffset = 0.75*(1.0 - 1.0/exp2(mipLevel))/exp2(roughnessLevel); + float mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x; + + bool bRes = mipLevel == 0.0; + scale = bRes && (scale < a) ? a : scale; + + vec3 r; + vec2 offset; + int face = getFaceFromDirection(direction); + + float rcpPowScale = 1.0 / powScale; + + if( face == 0) { + r = vec3(direction.x, -direction.z, direction.y); + offset = vec2(0.0+mipOffset,0.75 * rcpPowScale); + offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y; + } + else if( face == 1) { + r = vec3(direction.y, direction.x, direction.z); + offset = vec2(scale+mipOffset, 0.75 * rcpPowScale); + offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y; + } + else if( face == 2) { + r = vec3(direction.z, direction.x, direction.y); + offset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale); + offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y; + } + else if( face == 3) { + r = vec3(direction.x, direction.z, direction.y); + offset = vec2(0.0+mipOffset,0.5 * rcpPowScale); + offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y; + } + else if( face == 4) { + r = vec3(direction.y, direction.x, -direction.z); + offset = vec2(scale+mipOffset, 0.5 * rcpPowScale); + offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y; + } + else { + r = vec3(direction.z, -direction.x, direction.y); + offset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale); + offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y; + } + r = normalize(r); + float texelOffset = 0.5 * cubeUV_rcpTextureSize; + vec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5; + vec2 base = offset + vec2( texelOffset ); + return base + s * ( scale - 2.0 * texelOffset ); +} + +#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0) + +vec4 textureCubeUV(vec3 reflectedDirection, float roughness ) { + float roughnessVal = roughness* cubeUV_maxLods3; + float r1 = floor(roughnessVal); + float r2 = r1 + 1.0; + float t = fract(roughnessVal); + vec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness); + float s = mipInfo.y; + float level0 = mipInfo.x; + float level1 = level0 + 1.0; + level1 = level1 > 5.0 ? 5.0 : level1; + + // round to nearest mipmap if we are not interpolating. + level0 += min( floor( s + 0.5 ), 5.0 ); + + // Tri linear interpolation. + vec2 uv_10 = getCubeUV(reflectedDirection, r1, level0); + vec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10)); + + vec2 uv_20 = getCubeUV(reflectedDirection, r2, level0); + vec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20)); + + vec4 result = mix(color10, color20, t); + + return vec4(result.rgb, 1.0); +} + +#endif diff --git a/src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl b/src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl new file mode 100644 index 00000000000000..d9fb04ee0a892a --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl @@ -0,0 +1,7 @@ +#ifdef FLIP_SIDED + + objectNormal = -objectNormal; + +#endif + +vec3 transformedNormal = normalMatrix * objectNormal; diff --git a/src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl new file mode 100644 index 00000000000000..5e771596b11f94 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl @@ -0,0 +1,7 @@ +#ifdef USE_DISPLACEMENTMAP + + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl b/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl new file mode 100644 index 00000000000000..b03c142c68721b --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl @@ -0,0 +1,5 @@ +#ifdef USE_DISPLACEMENTMAP + + transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias ); + +#endif diff --git a/src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl b/src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl new file mode 100644 index 00000000000000..1d65996de11701 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl @@ -0,0 +1,9 @@ +#ifdef USE_EMISSIVEMAP + + vec4 emissiveColor = texture2D( emissiveMap, vUv ); + + emissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb; + + totalEmissiveRadiance *= emissiveColor.rgb; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl new file mode 100644 index 00000000000000..c05bb7f55180a0 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl @@ -0,0 +1,5 @@ +#ifdef USE_EMISSIVEMAP + + uniform sampler2D emissiveMap; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/encodings_fragment.glsl b/src/renderers/shaders/ShaderChunk/encodings_fragment.glsl new file mode 100644 index 00000000000000..189d735b547723 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/encodings_fragment.glsl @@ -0,0 +1 @@ + gl_FragColor = linearToOutputTexel( gl_FragColor ); diff --git a/src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl new file mode 100644 index 00000000000000..925590e88e11cb --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl @@ -0,0 +1,78 @@ +// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/ + +vec4 LinearToLinear( in vec4 value ) { + return value; +} + +vec4 GammaToLinear( in vec4 value, in float gammaFactor ) { + return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w ); +} +vec4 LinearToGamma( in vec4 value, in float gammaFactor ) { + return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w ); +} + +vec4 sRGBToLinear( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w ); +} +vec4 LinearTosRGB( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w ); +} + +vec4 RGBEToLinear( in vec4 value ) { + return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 ); +} +vec4 LinearToRGBE( in vec4 value ) { + float maxComponent = max( max( value.r, value.g ), value.b ); + float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 ); + return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 ); +// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 ); +} + +// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html +vec4 RGBMToLinear( in vec4 value, in float maxRange ) { + return vec4( value.xyz * value.w * maxRange, 1.0 ); +} +vec4 LinearToRGBM( in vec4 value, in float maxRange ) { + float maxRGB = max( value.x, max( value.g, value.b ) ); + float M = clamp( maxRGB / maxRange, 0.0, 1.0 ); + M = ceil( M * 255.0 ) / 255.0; + return vec4( value.rgb / ( M * maxRange ), M ); +} + +// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html +vec4 RGBDToLinear( in vec4 value, in float maxRange ) { + return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 ); +} +vec4 LinearToRGBD( in vec4 value, in float maxRange ) { + float maxRGB = max( value.x, max( value.g, value.b ) ); + float D = max( maxRange / maxRGB, 1.0 ); + D = min( floor( D ) / 255.0, 1.0 ); + return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D ); +} + +// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html + +// M matrix, for encoding +const mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 ); +vec4 LinearToLogLuv( in vec4 value ) { + vec3 Xp_Y_XYZp = value.rgb * cLogLuvM; + Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6)); + vec4 vResult; + vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z; + float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0; + vResult.w = fract(Le); + vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0; + return vResult; +} + +// Inverse M matrix, for decoding +const mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 ); +vec4 LogLuvToLinear( in vec4 value ) { + float Le = value.z * 255.0 + value.w; + vec3 Xp_Y_XYZp; + Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0); + Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y; + Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z; + vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM; + return vec4( max(vRGB, 0.0), 1.0 ); +} diff --git a/src/renderers/shaders/ShaderChunk/envmap_fragment.glsl b/src/renderers/shaders/ShaderChunk/envmap_fragment.glsl new file mode 100644 index 00000000000000..ccb35fa6bdf724 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/envmap_fragment.glsl @@ -0,0 +1,60 @@ +#ifdef USE_ENVMAP + + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) + + vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition ); + + // Transforming Normal Vectors with the Inverse Transformation + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + + #ifdef ENVMAP_MODE_REFLECTION + + vec3 reflectVec = reflect( cameraToVertex, worldNormal ); + + #else + + vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio ); + + #endif + + #else + + vec3 reflectVec = vReflect; + + #endif + + #ifdef ENVMAP_TYPE_CUBE + + vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + + #elif defined( ENVMAP_TYPE_EQUIREC ) + + vec2 sampleUV; + sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 ); + sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5; + vec4 envColor = texture2D( envMap, sampleUV ); + + #elif defined( ENVMAP_TYPE_SPHERE ) + + vec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) ); + vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 ); + + #endif + + envColor = envMapTexelToLinear( envColor ); + + #ifdef ENVMAP_BLENDING_MULTIPLY + + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + + #elif defined( ENVMAP_BLENDING_MIX ) + + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + + #elif defined( ENVMAP_BLENDING_ADD ) + + outgoingLight += envColor.xyz * specularStrength * reflectivity; + + #endif + +#endif diff --git a/src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl new file mode 100644 index 00000000000000..575800944abc0e --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl @@ -0,0 +1,25 @@ +#if defined( USE_ENVMAP ) || defined( PHYSICAL ) + uniform float reflectivity; + uniform float envMapIntenstiy; +#endif + +#ifdef USE_ENVMAP + + #if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) ) + varying vec3 vWorldPosition; + #endif + + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + uniform float flipEnvMap; + + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL ) + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif + +#endif diff --git a/src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl new file mode 100644 index 00000000000000..7feab7532e506d --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl @@ -0,0 +1,13 @@ +#ifdef USE_ENVMAP + + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) + varying vec3 vWorldPosition; + + #else + + varying vec3 vReflect; + uniform float refractionRatio; + + #endif + +#endif diff --git a/src/renderers/shaders/ShaderChunk/envmap_vertex.glsl b/src/renderers/shaders/ShaderChunk/envmap_vertex.glsl new file mode 100644 index 00000000000000..ce32d522895622 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/envmap_vertex.glsl @@ -0,0 +1,25 @@ +#ifdef USE_ENVMAP + + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) + + vWorldPosition = worldPosition.xyz; + + #else + + vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + + #ifdef ENVMAP_MODE_REFLECTION + + vReflect = reflect( cameraToVertex, worldNormal ); + + #else + + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + + #endif + + #endif + +#endif diff --git a/src/renderers/shaders/ShaderChunk/fog_fragment.glsl b/src/renderers/shaders/ShaderChunk/fog_fragment.glsl new file mode 100644 index 00000000000000..38309ad7a28f3e --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/fog_fragment.glsl @@ -0,0 +1,25 @@ +#ifdef USE_FOG + + #ifdef USE_LOGDEPTHBUF_EXT + + float depth = gl_FragDepthEXT / gl_FragCoord.w; + + #else + + float depth = gl_FragCoord.z / gl_FragCoord.w; + + #endif + + #ifdef FOG_EXP2 + + float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) ); + + #else + + float fogFactor = smoothstep( fogNear, fogFar, depth ); + + #endif + + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); + +#endif diff --git a/src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl new file mode 100644 index 00000000000000..ab7a15081ebcfc --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl @@ -0,0 +1,15 @@ +#ifdef USE_FOG + + uniform vec3 fogColor; + + #ifdef FOG_EXP2 + + uniform float fogDensity; + + #else + + uniform float fogNear; + uniform float fogFar; + #endif + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl b/src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl new file mode 100644 index 00000000000000..1392a6097c96e5 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl @@ -0,0 +1,5 @@ +#ifdef USE_LIGHTMAP + + reflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage + +#endif diff --git a/src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl new file mode 100644 index 00000000000000..a75c38f7edc244 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl @@ -0,0 +1,6 @@ +#ifdef USE_LIGHTMAP + + uniform sampler2D lightMap; + uniform float lightMapIntensity; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl b/src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl new file mode 100644 index 00000000000000..87a787d3d4e4c2 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl @@ -0,0 +1,99 @@ +vec3 diffuse = vec3( 1.0 ); + +GeometricContext geometry; +geometry.position = mvPosition.xyz; +geometry.normal = normalize( transformedNormal ); +geometry.viewDir = normalize( -mvPosition.xyz ); + +GeometricContext backGeometry; +backGeometry.position = geometry.position; +backGeometry.normal = -geometry.normal; +backGeometry.viewDir = geometry.viewDir; + +vLightFront = vec3( 0.0 ); + +#ifdef DOUBLE_SIDED + vLightBack = vec3( 0.0 ); +#endif + +IncidentLight directLight; +float dotNL; +vec3 directLightColor_Diffuse; + +#if NUM_POINT_LIGHTS > 0 + + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + getPointDirectLightIrradiance( pointLights[ i ], geometry, directLight ); + + dotNL = dot( geometry.normal, directLight.direction ); + directLightColor_Diffuse = PI * directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( -dotNL ) * directLightColor_Diffuse; + + #endif + + } + +#endif + +#if NUM_SPOT_LIGHTS > 0 + + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + getSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight ); + + dotNL = dot( geometry.normal, directLight.direction ); + directLightColor_Diffuse = PI * directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( -dotNL ) * directLightColor_Diffuse; + + #endif + } + +#endif + +#if NUM_DIR_LIGHTS > 0 + + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + getDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight ); + + dotNL = dot( geometry.normal, directLight.direction ); + directLightColor_Diffuse = PI * directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( -dotNL ) * directLightColor_Diffuse; + + #endif + + } + +#endif + +#if NUM_HEMI_LIGHTS > 0 + + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + vLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry ); + + #ifdef DOUBLE_SIDED + + vLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry ); + + #endif + + } + +#endif diff --git a/src/renderers/shaders/ShaderChunk/lights_pars.glsl b/src/renderers/shaders/ShaderChunk/lights_pars.glsl new file mode 100644 index 00000000000000..53f569f6b02dc4 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/lights_pars.glsl @@ -0,0 +1,300 @@ +uniform vec3 ambientLightColor; + +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + + vec3 irradiance = ambientLightColor; + + #ifndef PHYSICALLY_CORRECT_LIGHTS + + irradiance *= PI; + + #endif + + return irradiance; + +} + +#if NUM_DIR_LIGHTS > 0 + + struct DirectionalLight { + vec3 direction; + vec3 color; + + int shadow; + float shadowBias; + float shadowRadius; + vec2 shadowMapSize; + }; + + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + + void getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) { + + directLight.color = directionalLight.color; + directLight.direction = directionalLight.direction; + directLight.visible = true; + + } + +#endif + + +#if NUM_POINT_LIGHTS > 0 + + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + + int shadow; + float shadowBias; + float shadowRadius; + vec2 shadowMapSize; + }; + + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + + // directLight is an out parameter as having it as a return value caused compiler errors on some devices + void getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) { + + vec3 lVector = pointLight.position - geometry.position; + directLight.direction = normalize( lVector ); + + float lightDistance = length( lVector ); + + if ( testLightInRange( lightDistance, pointLight.distance ) ) { + + directLight.color = pointLight.color; + directLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay ); + + directLight.visible = true; + + } else { + + directLight.color = vec3( 0.0 ); + directLight.visible = false; + + } + + } + +#endif + + +#if NUM_SPOT_LIGHTS > 0 + + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + + int shadow; + float shadowBias; + float shadowRadius; + vec2 shadowMapSize; + }; + + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + + // directLight is an out parameter as having it as a return value caused compiler errors on some devices + void getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) { + + vec3 lVector = spotLight.position - geometry.position; + directLight.direction = normalize( lVector ); + + float lightDistance = length( lVector ); + float angleCos = dot( directLight.direction, spotLight.direction ); + + if ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) { + + float spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + + directLight.color = spotLight.color; + directLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay ); + + directLight.visible = true; + + } else { + + directLight.color = vec3( 0.0 ); + directLight.visible = false; + + } + + } + +#endif + + +#if NUM_HEMI_LIGHTS > 0 + + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) { + + float dotNL = dot( geometry.normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + + #ifndef PHYSICALLY_CORRECT_LIGHTS + + irradiance *= PI; + + #endif + + return irradiance; + + } + +#endif + + +#if defined( USE_ENVMAP ) && defined( PHYSICAL ) + + vec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) { + + #include + + vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix ); + + #ifdef ENVMAP_TYPE_CUBE + + vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz ); + + // TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level + // of a specular cubemap, or just the default level of a specially created irradiance cubemap. + + #ifdef TEXTURE_LOD_EXT + + vec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) ); + + #else + + // force the bias high to get the last LOD level as it is the most blurred. + vec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) ); + + #endif + + envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb; + + #elif defined( ENVMAP_TYPE_CUBE_UV ) + + vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz ); + vec4 envMapColor = textureCubeUV( queryVec, 1.0 ); + + #else + + vec4 envMapColor = vec4( 0.0 ); + + #endif + + return PI * envMapColor.rgb * envMapIntensity; + + } + + // taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html + float getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) { + + //float envMapWidth = pow( 2.0, maxMIPLevelScalar ); + //float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 ); + + float maxMIPLevelScalar = float( maxMIPLevel ); + float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 ); + + // clamp to allowable LOD ranges. + return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar ); + + } + + vec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) { + + #ifdef ENVMAP_MODE_REFLECTION + + vec3 reflectVec = reflect( -geometry.viewDir, geometry.normal ); + + #else + + vec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio ); + + #endif + + #include + + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + + float specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel ); + + #ifdef ENVMAP_TYPE_CUBE + + vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ); + + #ifdef TEXTURE_LOD_EXT + + vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel ); + + #else + + vec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel ); + + #endif + + envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb; + + #elif defined( ENVMAP_TYPE_CUBE_UV ) + + vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ); + vec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent)); + + #elif defined( ENVMAP_TYPE_EQUIREC ) + + vec2 sampleUV; + sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 ); + sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5; + + #ifdef TEXTURE_LOD_EXT + + vec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel ); + + #else + + vec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel ); + + #endif + + envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb; + + #elif defined( ENVMAP_TYPE_SPHERE ) + + vec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) ); + + #ifdef TEXTURE_LOD_EXT + + vec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel ); + + #else + + vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel ); + + #endif + + envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb; + + #endif + + return envMapColor.rgb * envMapIntensity; + + } + +#endif diff --git a/src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl b/src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl new file mode 100644 index 00000000000000..3bc610a44da972 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl @@ -0,0 +1,5 @@ +BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength; diff --git a/src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl new file mode 100644 index 00000000000000..3a84818ddc4b9f --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl @@ -0,0 +1,45 @@ +varying vec3 vViewPosition; + +#ifndef FLAT_SHADED + + varying vec3 vNormal; + +#endif + + +struct BlinnPhongMaterial { + + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; + +}; + +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + + float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); + + vec3 irradiance = dotNL * directLight.color; + + #ifndef PHYSICALLY_CORRECT_LIGHTS + + irradiance *= PI; // punctual light + + #endif + + reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength; + +} + +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + + reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); + +} + +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong + +#define Material_LightProbeLOD( material ) (0) diff --git a/src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl b/src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl new file mode 100644 index 00000000000000..c72658008dd165 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl @@ -0,0 +1,10 @@ +PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +material.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 ); +#ifdef STANDARD + material.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor ); + material.clearCoat = saturate( clearCoat ); // Burley clearcoat model + material.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 ); +#endif diff --git a/src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl new file mode 100644 index 00000000000000..22534c3a19c367 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl @@ -0,0 +1,91 @@ +struct PhysicalMaterial { + + vec3 diffuseColor; + float specularRoughness; + vec3 specularColor; + + #ifndef STANDARD + float clearCoat; + float clearCoatRoughness; + #endif + +}; + +#define MAXIMUM_SPECULAR_COEFFICIENT 0.16 +#define DEFAULT_SPECULAR_COEFFICIENT 0.04 + +// Clear coat directional hemishperical reflectance (this approximation should be improved) +float clearCoatDHRApprox( const in float roughness, const in float dotNL ) { + + return DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) ); + +} + +void RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + + float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); + + vec3 irradiance = dotNL * directLight.color; + + #ifndef PHYSICALLY_CORRECT_LIGHTS + + irradiance *= PI; // punctual light + + #endif + + #ifndef STANDARD + float clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL ); + #else + float clearCoatDHR = 0.0; + #endif + + reflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness ); + reflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); + + #ifndef STANDARD + + reflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness ); + + #endif + +} + +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + + reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); + +} + +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + + #ifndef STANDARD + float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) ); + float dotNL = dotNV; + float clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL ); + #else + float clearCoatDHR = 0.0; + #endif + + reflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness ); + + #ifndef STANDARD + + reflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness ); + + #endif + +} + +#define RE_Direct RE_Direct_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical + +#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness ) +#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness ) + +// ref: http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); + +} diff --git a/src/renderers/shaders/ShaderChunk/lights_template.glsl b/src/renderers/shaders/ShaderChunk/lights_template.glsl new file mode 100644 index 00000000000000..0b8576da97799e --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/lights_template.glsl @@ -0,0 +1,136 @@ +// +// This is a template that can be used to light a material, it uses pluggable RenderEquations (RE) +// for specific lighting scenarios. +// +// Instructions for use: +// - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined +// - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ??? +// - Create a material parameter that is to be passed as the third parameter to your lighting functions. +// +// TODO: +// - Add area light support. +// - Add sphere light support. +// - Add diffuse light probe (irradiance cubemap) support. +// + +GeometricContext geometry; + +geometry.position = - vViewPosition; +geometry.normal = normal; +geometry.viewDir = normalize( vViewPosition ); + +IncidentLight directLight; + +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + + PointLight pointLight; + + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + pointLight = pointLights[ i ]; + + getPointDirectLightIrradiance( pointLight, geometry, directLight ); + + #ifdef USE_SHADOWMAP + directLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0; + #endif + + RE_Direct( directLight, geometry, material, reflectedLight ); + + } + +#endif + +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + + SpotLight spotLight; + + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + spotLight = spotLights[ i ]; + + getSpotDirectLightIrradiance( spotLight, geometry, directLight ); + + #ifdef USE_SHADOWMAP + directLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; + #endif + + RE_Direct( directLight, geometry, material, reflectedLight ); + + } + +#endif + +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + + DirectionalLight directionalLight; + + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + + getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight ); + + #ifdef USE_SHADOWMAP + directLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + + RE_Direct( directLight, geometry, material, reflectedLight ); + + } + +#endif + +#if defined( RE_IndirectDiffuse ) + + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + + #ifdef USE_LIGHTMAP + + vec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; + + #ifndef PHYSICALLY_CORRECT_LIGHTS + + lightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage + + #endif + + irradiance += lightMapIrradiance; + + #endif + + #if ( NUM_HEMI_LIGHTS > 0 ) + + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry ); + + } + + #endif + + #if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV ) + + // TODO, replace 8 with the real maxMIPLevel + irradiance += getLightProbeIndirectIrradiance( /*lightProbe,*/ geometry, 8 ); + + #endif + + RE_IndirectDiffuse( irradiance, geometry, material, reflectedLight ); + +#endif + +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + + // TODO, replace 8 with the real maxMIPLevel + vec3 radiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_BlinnShininessExponent( material ), 8 ); + + #ifndef STANDARD + vec3 clearCoatRadiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 ); + #else + vec3 clearCoatRadiance = vec3( 0.0 ); + #endif + + RE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight ); + +#endif diff --git a/src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl b/src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl new file mode 100644 index 00000000000000..2a93ae1c073e14 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl @@ -0,0 +1,5 @@ +#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT) + + gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl new file mode 100644 index 00000000000000..1752c5951495eb --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl @@ -0,0 +1,11 @@ +#ifdef USE_LOGDEPTHBUF + + uniform float logDepthBufFC; + + #ifdef USE_LOGDEPTHBUF_EXT + + varying float vFragDepth; + + #endif + +#endif diff --git a/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl new file mode 100644 index 00000000000000..41972fcead48bf --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl @@ -0,0 +1,11 @@ +#ifdef USE_LOGDEPTHBUF + + #ifdef USE_LOGDEPTHBUF_EXT + + varying float vFragDepth; + + #endif + + uniform float logDepthBufFC; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl b/src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl new file mode 100644 index 00000000000000..2066809f5e30f9 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl @@ -0,0 +1,15 @@ +#ifdef USE_LOGDEPTHBUF + + gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC; + + #ifdef USE_LOGDEPTHBUF_EXT + + vFragDepth = 1.0 + gl_Position.w; + + #else + + gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w; + + #endif + +#endif diff --git a/src/renderers/shaders/ShaderChunk/map_fragment.glsl b/src/renderers/shaders/ShaderChunk/map_fragment.glsl new file mode 100644 index 00000000000000..b5fb51b16c7ecf --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/map_fragment.glsl @@ -0,0 +1,8 @@ +#ifdef USE_MAP + + vec4 texelColor = texture2D( map, vUv ); + + texelColor = mapTexelToLinear( texelColor ); + diffuseColor *= texelColor; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl new file mode 100644 index 00000000000000..d9a03464ba71ec --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl @@ -0,0 +1,5 @@ +#ifdef USE_MAP + + uniform sampler2D map; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl b/src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl new file mode 100644 index 00000000000000..17c752a7e8b8db --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl @@ -0,0 +1,6 @@ +#ifdef USE_MAP + + vec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy ); + diffuseColor *= mapTexelToLinear( mapTexel ); + +#endif diff --git a/src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl new file mode 100644 index 00000000000000..cc3c236659a05a --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl @@ -0,0 +1,6 @@ +#ifdef USE_MAP + + uniform vec4 offsetRepeat; + uniform sampler2D map; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl b/src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl new file mode 100644 index 00000000000000..be8f3694c752f4 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl @@ -0,0 +1,8 @@ +float metalnessFactor = metalness; + +#ifdef USE_METALNESSMAP + + vec4 texelMetalness = texture2D( metalnessMap, vUv ); + metalnessFactor *= texelMetalness.r; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl new file mode 100644 index 00000000000000..1d9c869e0e10b4 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl @@ -0,0 +1,5 @@ +#ifdef USE_METALNESSMAP + + uniform sampler2D metalnessMap; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl b/src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl new file mode 100644 index 00000000000000..b14763b1909e97 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl @@ -0,0 +1,8 @@ +#ifdef USE_MORPHNORMALS + + objectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ]; + objectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ]; + objectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ]; + objectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ]; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl new file mode 100644 index 00000000000000..a6664a526a1cec --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl @@ -0,0 +1,13 @@ +#ifdef USE_MORPHTARGETS + + #ifndef USE_MORPHNORMALS + + uniform float morphTargetInfluences[ 8 ]; + + #else + + uniform float morphTargetInfluences[ 4 ]; + + #endif + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl b/src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl new file mode 100644 index 00000000000000..baa0d6d944d818 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl @@ -0,0 +1,17 @@ +#ifdef USE_MORPHTARGETS + + transformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ]; + transformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ]; + transformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ]; + transformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ]; + + #ifndef USE_MORPHNORMALS + + transformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ]; + transformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ]; + transformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ]; + transformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ]; + + #endif + +#endif diff --git a/src/renderers/shaders/ShaderChunk/normal_flip.glsl b/src/renderers/shaders/ShaderChunk/normal_flip.glsl new file mode 100644 index 00000000000000..7474ec2256e6f7 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/normal_flip.glsl @@ -0,0 +1,5 @@ +#ifdef DOUBLE_SIDED + float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 ); +#else + float flipNormal = 1.0; +#endif diff --git a/src/renderers/shaders/ShaderChunk/normal_fragment.glsl b/src/renderers/shaders/ShaderChunk/normal_fragment.glsl new file mode 100644 index 00000000000000..7baeb096e72168 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/normal_fragment.glsl @@ -0,0 +1,23 @@ +#ifdef FLAT_SHADED + + // Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ... + + vec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) ); + vec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) ); + vec3 normal = normalize( cross( fdx, fdy ) ); + +#else + + vec3 normal = normalize( vNormal ) * flipNormal; + +#endif + +#ifdef USE_NORMALMAP + + normal = perturbNormal2Arb( -vViewPosition, normal ); + +#elif defined( USE_BUMPMAP ) + + normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() ); + +#endif diff --git a/src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl new file mode 100644 index 00000000000000..54b93eb59fb3d4 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl @@ -0,0 +1,27 @@ +#ifdef USE_NORMALMAP + + uniform sampler2D normalMap; + uniform vec2 normalScale; + + // Per-Pixel Tangent Space Normal Mapping + // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html + + vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) { + + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( vUv.st ); + vec2 st1 = dFdy( vUv.st ); + + vec3 S = normalize( q0 * st1.t - q1 * st0.t ); + vec3 T = normalize( -q0 * st1.s + q1 * st0.s ); + vec3 N = normalize( surf_norm ); + + vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0; + mapN.xy = normalScale * mapN.xy; + mat3 tsn = mat3( S, T, N ); + return normalize( tsn * mapN ); + + } + +#endif diff --git a/src/renderers/shaders/ShaderChunk/packing.glsl b/src/renderers/shaders/ShaderChunk/packing.glsl new file mode 100644 index 00000000000000..e701776a7b06c1 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/packing.glsl @@ -0,0 +1,45 @@ +vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} + +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 1.0 - 2.0 * rgb.xyz; +} + +const float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1) +const float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1) + +const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. ); +const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. ); + +const float ShiftRight8 = 1. / 256.; + +vec4 packDepthToRGBA( const in float v ) { + + vec4 r = vec4( fract( v * PackFactors ), v ); + r.yzw -= r.xyz * ShiftRight8; // tidy overflow + return r * PackUpscale; + +} + +float unpackRGBAToDepth( const in vec4 v ) { + + return dot( v, UnpackFactors ); + +} + +// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions + +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) { + return linearClipZ * ( near - far ) - near; +} + +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return (( near + viewZ ) * far ) / (( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * invClipZ - far ); +} diff --git a/src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl b/src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl new file mode 100644 index 00000000000000..412731941c17b0 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl @@ -0,0 +1,6 @@ +#ifdef PREMULTIPLIED_ALPHA + + // Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation. + gl_FragColor.rgb *= gl_FragColor.a; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/project_vertex.glsl b/src/renderers/shaders/ShaderChunk/project_vertex.glsl new file mode 100644 index 00000000000000..7e04851492ccfa --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/project_vertex.glsl @@ -0,0 +1,11 @@ +#ifdef USE_SKINNING + + vec4 mvPosition = modelViewMatrix * skinned; + +#else + + vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 ); + +#endif + +gl_Position = projectionMatrix * mvPosition; diff --git a/src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl b/src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl new file mode 100644 index 00000000000000..a2d24ad8c9360f --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl @@ -0,0 +1,8 @@ +float roughnessFactor = roughness; + +#ifdef USE_ROUGHNESSMAP + + vec4 texelRoughness = texture2D( roughnessMap, vUv ); + roughnessFactor *= texelRoughness.r; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl new file mode 100644 index 00000000000000..0f257121d1a11a --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl @@ -0,0 +1,5 @@ +#ifdef USE_ROUGHNESSMAP + + uniform sampler2D roughnessMap; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl new file mode 100644 index 00000000000000..ce581c28ba9de8 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl @@ -0,0 +1,231 @@ +#ifdef USE_SHADOWMAP + + #if NUM_DIR_LIGHTS > 0 + + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ]; + + #endif + + #if NUM_SPOT_LIGHTS > 0 + + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ]; + varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ]; + + #endif + + #if NUM_POINT_LIGHTS > 0 + + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ]; + + #endif + + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + + } + + float texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) { + + const vec2 offset = vec2( 0.0, 1.0 ); + + vec2 texelSize = vec2( 1.0 ) / size; + vec2 centroidUV = floor( uv * size + 0.5 ) / size; + + float lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare ); + float lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare ); + float rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare ); + float rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare ); + + vec2 f = fract( uv * size + 0.5 ); + + float a = mix( lb, lt, f.y ); + float b = mix( rb, rt, f.y ); + float c = mix( a, b, f.x ); + + return c; + + } + + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + + // if ( something && something ) breaks ATI OpenGL shader compiler + // if ( all( something, something ) ) using this instead + + bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 ); + bool inFrustum = all( inFrustumVec ); + + bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 ); + + bool frustumTest = all( frustumTestVec ); + + if ( frustumTest ) { + + #if defined( SHADOWMAP_TYPE_PCF ) + + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + + return ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 9.0 ); + + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + + return ( + texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) + + texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 9.0 ); + + #else // no percentage-closer filtering: + + return texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + + #endif + + } + + return 1.0; + + } + + // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D + // vector suitable for 2D texture mapping. This code uses the following layout for the + // 2D texture: + // + // xzXZ + // y Y + // + // Y - Positive y direction + // y - Negative y direction + // X - Positive x direction + // x - Negative x direction + // Z - Positive z direction + // z - Negative z direction + // + // Source and test bed: + // https://gist.github.com/tschw/da10c43c467ce8afd0c4 + + vec2 cubeToUV( vec3 v, float texelSizeY ) { + + // Number of texels to avoid at the edge of each square + + vec3 absV = abs( v ); + + // Intersect unit cube + + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + + // Apply scale to avoid seams + + // two texels less per square (one texel will do for NEAREST) + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + + // Unwrap + + // space: -1 ... 1 range for each square + // + // #X## dim := ( 4 , 2 ) + // # # center := ( 1 , 1 ) + + vec2 planar = v.xy; + + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + + if ( absV.z >= almostOne ) { + + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + + } else if ( absV.x >= almostOne ) { + + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + + } else if ( absV.y >= almostOne ) { + + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + + } + + // Transform to UV space + + // scale := 0.5 / dim + // translate := ( center + 0.5 ) / dim + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + + } + + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + + // for point lights, the uniform @vShadowCoord is re-purposed to hold + // the distance from the light to the world-space position of the fragment. + vec3 lightToPosition = shadowCoord.xyz; + + // bd3D = base direction 3D + vec3 bd3D = normalize( lightToPosition ); + // dp = distance from light to fragment position + float dp = ( length( lightToPosition ) - shadowBias ) / 1000.0; + + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) + + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + + return ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + + #else // no percentage-closer filtering + + return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + + #endif + + } + +#endif diff --git a/src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl new file mode 100644 index 00000000000000..13c5d8004dd736 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl @@ -0,0 +1,24 @@ +#ifdef USE_SHADOWMAP + + #if NUM_DIR_LIGHTS > 0 + + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ]; + + #endif + + #if NUM_SPOT_LIGHTS > 0 + + uniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ]; + varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ]; + + #endif + + #if NUM_POINT_LIGHTS > 0 + + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ]; + + #endif + +#endif diff --git a/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl b/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl new file mode 100644 index 00000000000000..8248e61209cb06 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl @@ -0,0 +1,33 @@ +#ifdef USE_SHADOWMAP + + #if NUM_DIR_LIGHTS > 0 + + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition; + + } + + #endif + + #if NUM_SPOT_LIGHTS > 0 + + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + vSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition; + + } + + #endif + + #if NUM_POINT_LIGHTS > 0 + + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition; + + } + + #endif + +#endif diff --git a/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl new file mode 100644 index 00000000000000..04b2dda156b074 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl @@ -0,0 +1,50 @@ +float getShadowMask() { + + float shadow = 1.0; + + #ifdef USE_SHADOWMAP + + #if NUM_DIR_LIGHTS > 0 + + DirectionalLight directionalLight; + + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + shadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + + } + + #endif + + #if NUM_SPOT_LIGHTS > 0 + + SpotLight spotLight; + + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + spotLight = spotLights[ i ]; + shadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; + + } + + #endif + + #if NUM_POINT_LIGHTS > 0 + + PointLight pointLight; + + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + pointLight = pointLights[ i ]; + shadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0; + + } + + #endif + + #endif + + return shadow; + +} diff --git a/src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl b/src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl new file mode 100644 index 00000000000000..d1b3d3936fa72d --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl @@ -0,0 +1,8 @@ +#ifdef USE_SKINNING + + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl new file mode 100644 index 00000000000000..d7334f597568d0 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl @@ -0,0 +1,47 @@ +#ifdef USE_SKINNING + + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + + #ifdef BONE_TEXTURE + + uniform sampler2D boneTexture; + uniform int boneTextureWidth; + uniform int boneTextureHeight; + + mat4 getBoneMatrix( const in float i ) { + + float j = i * 4.0; + float x = mod( j, float( boneTextureWidth ) ); + float y = floor( j / float( boneTextureWidth ) ); + + float dx = 1.0 / float( boneTextureWidth ); + float dy = 1.0 / float( boneTextureHeight ); + + y = dy * ( y + 0.5 ); + + vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) ); + vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) ); + vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) ); + vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) ); + + mat4 bone = mat4( v1, v2, v3, v4 ); + + return bone; + + } + + #else + + uniform mat4 boneMatrices[ MAX_BONES ]; + + mat4 getBoneMatrix( const in float i ) { + + mat4 bone = boneMatrices[ int(i) ]; + return bone; + + } + + #endif + +#endif diff --git a/src/renderers/shaders/ShaderChunk/skinning_vertex.glsl b/src/renderers/shaders/ShaderChunk/skinning_vertex.glsl new file mode 100644 index 00000000000000..4d3e18f0bfc5fd --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/skinning_vertex.glsl @@ -0,0 +1,12 @@ +#ifdef USE_SKINNING + + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + skinned = bindMatrixInverse * skinned; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl b/src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl new file mode 100644 index 00000000000000..b378a67bd90559 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl @@ -0,0 +1,12 @@ +#ifdef USE_SKINNING + + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl b/src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl new file mode 100644 index 00000000000000..8afac608c5ee00 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl @@ -0,0 +1,12 @@ +float specularStrength; + +#ifdef USE_SPECULARMAP + + vec4 texelSpecular = texture2D( specularMap, vUv ); + specularStrength = texelSpecular.r; + +#else + + specularStrength = 1.0; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl new file mode 100644 index 00000000000000..3df2e4269f6ddb --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl @@ -0,0 +1,5 @@ +#ifdef USE_SPECULARMAP + + uniform sampler2D specularMap; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl b/src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl new file mode 100644 index 00000000000000..ce35d9ac329768 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl @@ -0,0 +1,5 @@ +#if defined( TONE_MAPPING ) + + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); + +#endif diff --git a/src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl new file mode 100644 index 00000000000000..e41267277c913e --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl @@ -0,0 +1,39 @@ +#define saturate(a) clamp( a, 0.0, 1.0 ) + +uniform float toneMappingExposure; +uniform float toneMappingWhitePoint; + +// exposure only +vec3 LinearToneMapping( vec3 color ) { + + return toneMappingExposure * color; + +} + +// source: https://www.cs.utah.edu/~reinhard/cdrom/ +vec3 ReinhardToneMapping( vec3 color ) { + + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); + +} + +// source: http://filmicgames.com/archives/75 +#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) ) +vec3 Uncharted2ToneMapping( vec3 color ) { + + // John Hable's filmic operator from Uncharted 2 video game + color *= toneMappingExposure; + return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) ); + +} + +// source: http://filmicgames.com/archives/75 +vec3 OptimizedCineonToneMapping( vec3 color ) { + + // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); + +} diff --git a/src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl new file mode 100644 index 00000000000000..37274dbbfbaecf --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl @@ -0,0 +1,5 @@ +#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + + varying vec2 vUv2; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl new file mode 100644 index 00000000000000..6aaa13e304108e --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl @@ -0,0 +1,6 @@ +#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + + attribute vec2 uv2; + varying vec2 vUv2; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/uv2_vertex.glsl b/src/renderers/shaders/ShaderChunk/uv2_vertex.glsl new file mode 100644 index 00000000000000..72d546a36e3487 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/uv2_vertex.glsl @@ -0,0 +1,5 @@ +#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + + vUv2 = uv2; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl b/src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl new file mode 100644 index 00000000000000..d1bb9548cb14f0 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl @@ -0,0 +1,5 @@ +#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP ) + + varying vec2 vUv; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl b/src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl new file mode 100644 index 00000000000000..d2e81dd526c1cc --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl @@ -0,0 +1,6 @@ +#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP ) + + varying vec2 vUv; + uniform vec4 offsetRepeat; + +#endif diff --git a/src/renderers/shaders/ShaderChunk/uv_vertex.glsl b/src/renderers/shaders/ShaderChunk/uv_vertex.glsl new file mode 100644 index 00000000000000..cbcdf48b47a351 --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/uv_vertex.glsl @@ -0,0 +1,5 @@ +#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP ) + + vUv = uv * offsetRepeat.zw + offsetRepeat.xy; + +#endif \ No newline at end of file diff --git a/src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl b/src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl new file mode 100644 index 00000000000000..d1db3f9a04aceb --- /dev/null +++ b/src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl @@ -0,0 +1,13 @@ +#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP ) + + #ifdef USE_SKINNING + + vec4 worldPosition = modelMatrix * skinned; + + #else + + vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 ); + + #endif + +#endif diff --git a/src/renderers/shaders/ShaderLib/cube_frag.glsl b/src/renderers/shaders/ShaderLib/cube_frag.glsl new file mode 100644 index 00000000000000..822084c9375ebf --- /dev/null +++ b/src/renderers/shaders/ShaderLib/cube_frag.glsl @@ -0,0 +1,14 @@ +uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; + +varying vec3 vWorldPosition; + +#include + +void main() { + + gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) ); + gl_FragColor.a *= opacity; + +} diff --git a/src/renderers/shaders/ShaderLib/cube_vert.glsl b/src/renderers/shaders/ShaderLib/cube_vert.glsl new file mode 100644 index 00000000000000..d2ca8a2b0754d6 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/cube_vert.glsl @@ -0,0 +1,12 @@ +varying vec3 vWorldPosition; + +#include + +void main() { + + vWorldPosition = transformDirection( position, modelMatrix ); + + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/depth_frag.glsl b/src/renderers/shaders/ShaderLib/depth_frag.glsl new file mode 100644 index 00000000000000..4078a9c68fe797 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/depth_frag.glsl @@ -0,0 +1,43 @@ +#if DEPTH_PACKING == 3200 + + uniform float opacity; + +#endif + +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + + vec4 diffuseColor = vec4( 1.0 ); + + #if DEPTH_PACKING == 3200 + + diffuseColor.a = opacity; + + #endif + + #include + #include + #include + + #include + + #if DEPTH_PACKING == 3200 + + gl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity ); + + #elif DEPTH_PACKING == 3201 + + gl_FragColor = packDepthToRGBA( gl_FragCoord.z ); + + #endif + +} diff --git a/src/renderers/shaders/ShaderLib/depth_vert.glsl b/src/renderers/shaders/ShaderLib/depth_vert.glsl new file mode 100644 index 00000000000000..590184a0d88a29 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/depth_vert.glsl @@ -0,0 +1,23 @@ +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + + #include + + #include + #include + #include + #include + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl b/src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl new file mode 100644 index 00000000000000..22875fd3add12f --- /dev/null +++ b/src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl @@ -0,0 +1,14 @@ +uniform vec3 lightPos; +varying vec4 vWorldPosition; + +#include +#include +#include + +void main () { + + #include + + gl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 ); + +} diff --git a/src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl b/src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl new file mode 100644 index 00000000000000..445102be1fb8ea --- /dev/null +++ b/src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl @@ -0,0 +1,20 @@ +varying vec4 vWorldPosition; + +#include +#include +#include +#include + +void main() { + + #include + #include + #include + #include + #include + #include + #include + + vWorldPosition = worldPosition; + +} diff --git a/src/renderers/shaders/ShaderLib/equirect_frag.glsl b/src/renderers/shaders/ShaderLib/equirect_frag.glsl new file mode 100644 index 00000000000000..81648499b1e6fc --- /dev/null +++ b/src/renderers/shaders/ShaderLib/equirect_frag.glsl @@ -0,0 +1,17 @@ +uniform sampler2D tEquirect; +uniform float tFlip; + +varying vec3 vWorldPosition; + +#include + +void main() { + + // gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) ); + vec3 direction = normalize( vWorldPosition ); + vec2 sampleUV; + sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 ); + sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5; + gl_FragColor = texture2D( tEquirect, sampleUV ); + +} diff --git a/src/renderers/shaders/ShaderLib/equirect_vert.glsl b/src/renderers/shaders/ShaderLib/equirect_vert.glsl new file mode 100644 index 00000000000000..d2ca8a2b0754d6 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/equirect_vert.glsl @@ -0,0 +1,12 @@ +varying vec3 vWorldPosition; + +#include + +void main() { + + vWorldPosition = transformDirection( position, modelMatrix ); + + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/linedashed_frag.glsl b/src/renderers/shaders/ShaderLib/linedashed_frag.glsl new file mode 100644 index 00000000000000..3c93173641c085 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/linedashed_frag.glsl @@ -0,0 +1,40 @@ +uniform vec3 diffuse; +uniform float opacity; + +uniform float dashSize; +uniform float totalSize; + +varying float vLineDistance; + +#include +#include +#include +#include +#include + +void main() { + + #include + + if ( mod( vLineDistance, totalSize ) > dashSize ) { + + discard; + + } + + vec3 outgoingLight = vec3( 0.0 ); + vec4 diffuseColor = vec4( diffuse, opacity ); + + #include + #include + + outgoingLight = diffuseColor.rgb; // simple shader + + gl_FragColor = vec4( outgoingLight, diffuseColor.a ); + + #include + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/linedashed_vert.glsl b/src/renderers/shaders/ShaderLib/linedashed_vert.glsl new file mode 100644 index 00000000000000..954d57cf1b6c04 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/linedashed_vert.glsl @@ -0,0 +1,23 @@ +uniform float scale; +attribute float lineDistance; + +varying float vLineDistance; + +#include +#include +#include +#include + +void main() { + + #include + + vLineDistance = scale * lineDistance; + + vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); + gl_Position = projectionMatrix * mvPosition; + + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/meshbasic_frag.glsl b/src/renderers/shaders/ShaderLib/meshbasic_frag.glsl new file mode 100644 index 00000000000000..81d8119ee31700 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/meshbasic_frag.glsl @@ -0,0 +1,56 @@ +uniform vec3 diffuse; +uniform float opacity; + +#ifndef FLAT_SHADED + + varying vec3 vNormal; + +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + + vec4 diffuseColor = vec4( diffuse, opacity ); + + #include + #include + #include + #include + #include + #include + + ReflectedLight reflectedLight; + reflectedLight.directDiffuse = vec3( 0.0 ); + reflectedLight.directSpecular = vec3( 0.0 ); + reflectedLight.indirectDiffuse = diffuseColor.rgb; + reflectedLight.indirectSpecular = vec3( 0.0 ); + + #include + + vec3 outgoingLight = reflectedLight.indirectDiffuse; + + #include + #include + + gl_FragColor = vec4( outgoingLight, diffuseColor.a ); + + #include + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/meshbasic_vert.glsl b/src/renderers/shaders/ShaderLib/meshbasic_vert.glsl new file mode 100644 index 00000000000000..7db5a6dd8ebd4d --- /dev/null +++ b/src/renderers/shaders/ShaderLib/meshbasic_vert.glsl @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + #include + #include + #include + + #ifdef USE_ENVMAP + + #include + #include + #include + #include + + #endif + + #include + #include + #include + #include + #include + + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/meshlambert_frag.glsl b/src/renderers/shaders/ShaderLib/meshlambert_frag.glsl new file mode 100644 index 00000000000000..0a718794b9873c --- /dev/null +++ b/src/renderers/shaders/ShaderLib/meshlambert_frag.glsl @@ -0,0 +1,83 @@ +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; + +varying vec3 vLightFront; + +#ifdef DOUBLE_SIDED + + varying vec3 vLightBack; + +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + + #include + #include + #include + #include + #include + #include + #include + + // accumulation + reflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor ); + + #include + + reflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ); + + #ifdef DOUBLE_SIDED + + reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack; + + #else + + reflectedLight.directDiffuse = vLightFront; + + #endif + + reflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask(); + + // modulation + #include + + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + + #include + #include + + gl_FragColor = vec4( outgoingLight, diffuseColor.a ); + + #include + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/meshlambert_vert.glsl b/src/renderers/shaders/ShaderLib/meshlambert_vert.glsl new file mode 100644 index 00000000000000..d70ffa2fbc6e83 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/meshlambert_vert.glsl @@ -0,0 +1,48 @@ +#define LAMBERT + +varying vec3 vLightFront; + +#ifdef DOUBLE_SIDED + + varying vec3 vLightBack; + +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + #include + #include + + #include + #include + #include + #include + #include + + #include + #include + #include + #include + #include + #include + + #include + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/meshphong_frag.glsl b/src/renderers/shaders/ShaderLib/meshphong_frag.glsl new file mode 100644 index 00000000000000..5041e7a5f1949e --- /dev/null +++ b/src/renderers/shaders/ShaderLib/meshphong_frag.glsl @@ -0,0 +1,67 @@ +#define PHONG + +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + + #include + #include + #include + #include + #include + #include + #include + #include + #include + + // accumulation + #include + #include + + // modulation + #include + + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + + #include + + gl_FragColor = vec4( outgoingLight, diffuseColor.a ); + + #include + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/meshphong_vert.glsl b/src/renderers/shaders/ShaderLib/meshphong_vert.glsl new file mode 100644 index 00000000000000..84b9ade640a74b --- /dev/null +++ b/src/renderers/shaders/ShaderLib/meshphong_vert.glsl @@ -0,0 +1,55 @@ +#define PHONG + +varying vec3 vViewPosition; + +#ifndef FLAT_SHADED + + varying vec3 vNormal; + +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + #include + #include + + #include + #include + #include + #include + #include + +#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED + + vNormal = normalize( transformedNormal ); + +#endif + + #include + #include + #include + #include + #include + #include + #include + + vViewPosition = - mvPosition.xyz; + + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/meshphysical_frag.glsl b/src/renderers/shaders/ShaderLib/meshphysical_frag.glsl new file mode 100644 index 00000000000000..9a050e10de7a65 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/meshphysical_frag.glsl @@ -0,0 +1,84 @@ +#define PHYSICAL + +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; + +#ifndef STANDARD + uniform float clearCoat; + uniform float clearCoatRoughness; +#endif + +uniform float envMapIntensity; // temporary + +varying vec3 vViewPosition; + +#ifndef FLAT_SHADED + + varying vec3 vNormal; + +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + // accumulation + #include + #include + + // modulation + #include + + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + + gl_FragColor = vec4( outgoingLight, diffuseColor.a ); + + #include + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/meshphysical_vert.glsl b/src/renderers/shaders/ShaderLib/meshphysical_vert.glsl new file mode 100644 index 00000000000000..14c075e5e6d9b6 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/meshphysical_vert.glsl @@ -0,0 +1,54 @@ +#define PHYSICAL + +varying vec3 vViewPosition; + +#ifndef FLAT_SHADED + + varying vec3 vNormal; + +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + #include + #include + + #include + #include + #include + #include + #include + +#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED + + vNormal = normalize( transformedNormal ); + +#endif + + #include + #include + #include + #include + #include + #include + #include + + vViewPosition = - mvPosition.xyz; + + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/normal_frag.glsl b/src/renderers/shaders/ShaderLib/normal_frag.glsl new file mode 100644 index 00000000000000..e5519cdd890d24 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/normal_frag.glsl @@ -0,0 +1,16 @@ +uniform float opacity; +varying vec3 vNormal; + +#include +#include +#include +#include + +void main() { + + #include + gl_FragColor = vec4( packNormalToRGB( vNormal ), opacity ); + + #include + +} diff --git a/src/renderers/shaders/ShaderLib/normal_vert.glsl b/src/renderers/shaders/ShaderLib/normal_vert.glsl new file mode 100644 index 00000000000000..ed235ee86040a0 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/normal_vert.glsl @@ -0,0 +1,18 @@ +varying vec3 vNormal; + +#include +#include +#include +#include + +void main() { + + vNormal = normalize( normalMatrix * normal ); + + #include + #include + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/points_frag.glsl b/src/renderers/shaders/ShaderLib/points_frag.glsl new file mode 100644 index 00000000000000..dbf516f4767da6 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/points_frag.glsl @@ -0,0 +1,33 @@ +uniform vec3 diffuse; +uniform float opacity; + +#include +#include +#include +#include +#include +#include +#include + +void main() { + + #include + + vec3 outgoingLight = vec3( 0.0 ); + vec4 diffuseColor = vec4( diffuse, opacity ); + + #include + #include + #include + #include + + outgoingLight = diffuseColor.rgb; + + gl_FragColor = vec4( outgoingLight, diffuseColor.a ); + + #include + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/points_vert.glsl b/src/renderers/shaders/ShaderLib/points_vert.glsl new file mode 100644 index 00000000000000..ac53f3668cb66c --- /dev/null +++ b/src/renderers/shaders/ShaderLib/points_vert.glsl @@ -0,0 +1,27 @@ +uniform float size; +uniform float scale; + +#include +#include +#include +#include +#include + +void main() { + + #include + #include + #include + + #ifdef USE_SIZEATTENUATION + gl_PointSize = size * ( scale / - mvPosition.z ); + #else + gl_PointSize = size; + #endif + + #include + #include + #include + #include + +} diff --git a/src/renderers/shaders/ShaderLib/shadow_frag.glsl b/src/renderers/shaders/ShaderLib/shadow_frag.glsl new file mode 100644 index 00000000000000..9dcd83a2ec3048 --- /dev/null +++ b/src/renderers/shaders/ShaderLib/shadow_frag.glsl @@ -0,0 +1,14 @@ +uniform float opacity; + +#include +#include +#include +#include +#include +#include + +void main() { + + gl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) ); + +} diff --git a/src/renderers/shaders/ShaderLib/shadow_vert.glsl b/src/renderers/shaders/ShaderLib/shadow_vert.glsl new file mode 100644 index 00000000000000..e56bd60efa865e --- /dev/null +++ b/src/renderers/shaders/ShaderLib/shadow_vert.glsl @@ -0,0 +1,10 @@ +#include + +void main() { + + #include + #include + #include + #include + +} From fafaa014d45ee19f14a8ab0b7ec9292c2af2dce0 Mon Sep 17 00:00:00 2001 From: Rich-Harris Date: Sat, 9 Jul 2016 10:09:45 -0400 Subject: [PATCH 4/4] reinstate polyfills --- build/three.js | 86 ++++++++++++++++++++++++++++++++++++++++++++++ build/three.min.js | 4 +-- src/Three.js | 4 ++- src/polyfills.js | 85 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 176 insertions(+), 3 deletions(-) create mode 100644 src/polyfills.js diff --git a/build/three.js b/build/three.js index 0b98760d5a8687..8589a079a8039f 100644 --- a/build/three.js +++ b/build/three.js @@ -4,6 +4,92 @@ (factory((global.THREE = global.THREE || {}))); }(this, function (exports) { 'use strict'; + // Polyfills + + if ( Number.EPSILON === undefined ) { + + Number.EPSILON = Math.pow( 2, - 52 ); + + } + + // + + if ( Math.sign === undefined ) { + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + + Math.sign = function ( x ) { + + return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; + + }; + + } + + if ( Function.prototype.name === undefined ) { + + // Missing in IE9-11. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name + + Object.defineProperty( Function.prototype, 'name', { + + get: function () { + + return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; + + } + + } ); + + } + + if ( Object.assign === undefined ) { + + // Missing in IE. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + + ( function () { + + Object.assign = function ( target ) { + + 'use strict'; + + if ( target === undefined || target === null ) { + + throw new TypeError( 'Cannot convert undefined or null to object' ); + + } + + var output = Object( target ); + + for ( var index = 1; index < arguments.length; index ++ ) { + + var source = arguments[ index ]; + + if ( source !== undefined && source !== null ) { + + for ( var nextKey in source ) { + + if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { + + output[ nextKey ] = source[ nextKey ]; + + } + + } + + } + + } + + return output; + + }; + + } )(); + + } + /** * https://github.com/mrdoob/eventdispatcher.js/ */ diff --git a/build/three.min.js b/build/three.min.js index 13d3df762360e1..761d474b49713e 100644 --- a/build/three.min.js +++ b/build/three.min.js @@ -2,8 +2,8 @@ }function w(t,e,i){return this.isColor=!0,void 0===e&&void 0===i?this.set(t):this.setRGB(t,e,i)}function M(t){this.isMeshDepthMaterial=this.isMaterial=!0,x.call(this),this.type="MeshDepthMaterial",this.depthPacking=xa,this.skinning=!1,this.morphTargets=!1,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.setValues(t)}function E(t,e){this.isBox3=!0,this.min=void 0!==t?t:new s((+(1/0)),(+(1/0)),(+(1/0))),this.max=void 0!==e?e:new s((-(1/0)),(-(1/0)),(-(1/0)))}function T(t,e){this.isSphere=!0,this.center=void 0!==t?t:new s,this.radius=void 0!==e?e:0}function S(){this.isMatrix3=!0,this.elements=new Float32Array([1,0,0,0,1,0,0,0,1]),arguments.length>0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function A(t,e){this.isPlane=!0,this.normal=void 0!==t?t:new s(1,0,0),this.constant=void 0!==e?e:0}function L(t,e,i,n,r,a){this.isFrustum=!0,this.planes=[void 0!==t?t:new A,void 0!==e?e:new A,void 0!==i?i:new A,void 0!==n?n:new A,void 0!==r?r:new A,void 0!==a?a:new A]}function R(e,n,r,o){function h(t,i,n,r){var a=t.geometry,o=null,s=A,h=t.customDepthMaterial;if(n&&(s=R,h=t.customDistanceMaterial),h)o=h;else{var c=!1;i.morphTargets&&(a&&a.isBufferGeometry?c=a.morphAttributes&&a.morphAttributes.position&&a.morphAttributes.position.length>0:a&&a.isGeometry&&(c=a.morphTargets&&a.morphTargets.length>0));var l=t&&t.isSkinnedMesh&&i.skinning,u=0;c&&(u|=E),l&&(u|=T),o=s[u]}if(e.localClippingEnabled&&i.clipShadows===!0&&0!==i.clippingPlanes.length){var p=o.uuid,d=i.uuid,f=P[p];void 0===f&&(f={},P[p]=f);var m=f[d];void 0===m&&(m=o.clone(),f[d]=m),o=m}o.visible=i.visible,o.wireframe=i.wireframe;var g=i.side;return V.renderSingleSided&&g==xn&&(g=vn),V.renderReverseSided&&(g===vn?g=yn:g===yn&&(g=vn)),o.side=g,o.clipShadows=i.clipShadows,o.clippingPlanes=i.clippingPlanes,o.wireframeLinewidth=i.wireframeLinewidth,o.linewidth=i.linewidth,n&&void 0!==o.uniforms.lightPos&&o.uniforms.lightPos.value.copy(r),o}function c(t,e,i){if(t.visible!==!1){if(t.layers.test(e.layers)&&(t&&t.isMesh||t&&t.isLine||t&&t.isPoints)&&t.castShadow&&(t.frustumCulled===!1||p.intersectsObject(t)===!0)){var n=t.material;n.visible===!0&&(t.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,t.matrixWorld),w.push(t))}for(var r=t.children,a=0,o=r.length;a0,shadowMapType:e.shadowMap.type,toneMapping:e.toneMapping,physicallyCorrectLights:e.physicallyCorrectLights,premultipliedAlpha:t.premultipliedAlpha,alphaTest:t.alphaTest,doubleSided:t.side===xn,flipSided:t.side===yn,depthPacking:void 0!==t.depthPacking&&t.depthPacking};return f},this.getProgramCode=function(t,e){var i=[];if(e.shaderID?i.push(e.shaderID):(i.push(t.fragmentShader),i.push(t.vertexShader)),void 0!==t.defines)for(var n in t.defines)i.push(n),i.push(t.defines[n]);for(var r=0;r65535?Uint32Array:Uint16Array,y=new U(new v(a),1);return r(y,t.ELEMENT_ARRAY_BUFFER),n.wireframe=y,y}function c(t,e,i){if(e>i){var n=e;e=i,i=n}var r=t[e];return void 0===r?(t[e]=[i],!0):r.indexOf(i)===-1&&(r.push(i),!0)}this.isWebGLObjects=!0;var l=new K(t,e,i);this.getAttributeBuffer=s,this.getWireframeAttribute=h,this.update=n}function tt(){this.isWebGLLights=!0;var t={};this.get=function(e){if(void 0!==t[e.id])return t[e.id];var n;switch(e.type){case"DirectionalLight":n={direction:new s,color:new w,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"SpotLight":n={position:new s,direction:new s,color:new w,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"PointLight":n={position:new s,color:new w,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"HemisphereLight":n={direction:new s,skyColor:new w,groundColor:new w}}return t[e.id]=n,n}}function et(t,e,i){function n(){if(void 0!==a)return a;var i=e.get("EXT_texture_filter_anisotropic");return a=null!==i?t.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}function r(e){if("highp"===e){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}this.isWebGLCapabilities=!0;var a;this.getMaxAnisotropy=n,this.getMaxPrecision=r,this.precision=void 0!==i.precision?i.precision:"highp",this.logarithmicDepthBuffer=void 0!==i.logarithmicDepthBuffer&&i.logarithmicDepthBuffer,this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubemapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxAttributes=t.getParameter(t.MAX_VERTEX_ATTRIBS),this.maxVertexUniforms=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.maxVaryings=t.getParameter(t.MAX_VARYING_VECTORS),this.maxFragmentUniforms=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.vertexTextures=this.maxVertexTextures>0,this.floatFragmentTextures=!!e.get("OES_texture_float"),this.floatVertexTextures=this.vertexTextures&&this.floatFragmentTextures;var o=r(this.precision);o!==this.precision&&(console.warn("THREE.WebGLRenderer:",this.precision,"not supported, using",o,"instead."),this.precision=o),this.logarithmicDepthBuffer&&(this.logarithmicDepthBuffer=!!e.get("EXT_frag_depth"))}function it(t){this.isWebGLExtensions=!0;var e={};this.get=function(i){if(void 0!==e[i])return e[i];var n;switch(i){case"WEBGL_depth_texture":n=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case"WEBGL_compressed_texture_etc1":n=t.getExtension("WEBGL_compressed_texture_etc1");break;default:n=t.getExtension(i)}return null===n&&console.warn("THREE.WebGLRenderer: "+i+" extension not supported."),e[i]=n,n}}function nt(t,e,i){function n(t){s=t}function r(i){i.array instanceof Uint32Array&&e.get("OES_element_index_uint")?(h=t.UNSIGNED_INT,c=4):(h=t.UNSIGNED_SHORT,c=2)}function a(e,n){t.drawElements(s,n,h,e*c),i.calls++,i.vertices+=n,s===t.TRIANGLES&&(i.faces+=n/3)}function o(n,r,a){var o=e.get("ANGLE_instanced_arrays");return null===o?void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(o.drawElementsInstancedANGLE(s,a,h,r*c,n.maxInstancedCount),i.calls++,i.vertices+=a*n.maxInstancedCount,void(s===t.TRIANGLES&&(i.faces+=n.maxInstancedCount*a/3)))}this.isWebGLIndexedBufferRenderer=!0;var s,h,c;this.setMode=n,this.setIndex=r,this.render=a,this.renderInstances=o}function rt(){function t(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),i.numPlanes=r}function e(t,e,n,r){var a=null!==t?t.length:0,o=null;if(0!==a){if(o=c.value,r!==!0||null===o){var l=n+4*a,u=e.matrixWorldInverse;h.getNormalMatrix(u),(null===o||o.length0?1:-1,m[v]=C.x,m[v+1]=C.y,m[v+2]=C.z,g[y]=D/c,g[y+1]=1-U/u,v+=3,y+=2,R+=1}for(U=0;U65535?Uint32Array:Uint16Array)(p),f=new Float32Array(3*u),m=new Float32Array(3*u),g=new Float32Array(2*u),v=0,y=0,x=0,b=0,_=0;c("z","y","x",-1,-1,i,e,t,a,r,0),c("z","y","x",1,-1,i,e,-t,a,r,1),c("x","z","y",1,1,t,i,e,n,a,2),c("x","z","y",1,-1,t,i,-e,n,a,3),c("x","y","z",1,-1,t,e,i,n,r,4),c("x","y","z",-1,-1,t,e,-i,n,r,5),this.setIndex(new U(d,1)),this.addAttribute("position",new U(f,3)),this.addAttribute("normal",new U(m,3)),this.addAttribute("uv",new U(g,2))}function ht(t,e){this.isRay=!0,this.origin=void 0!==t?t:new s,this.direction=void 0!==e?e:new s}function ct(t,e){this.isLine3=!0,this.start=void 0!==t?t:new s,this.end=void 0!==e?e:new s}function lt(t,e,i){this.isTriangle=!0,this.a=void 0!==t?t:new s,this.b=void 0!==e?e:new s,this.c=void 0!==i?i:new s}function ut(t){this.isMeshBasicMaterial=this.isMaterial=!0,x.call(this),this.type="MeshBasicMaterial",this.color=new w(16777215),this.map=null,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.lights=!1,this.setValues(t)}function pt(t,e){this.isMesh=!0,X.call(this),this.type="Mesh",this.geometry=void 0!==t?t:new Q,this.material=void 0!==e?e:new ut({color:16777215*Math.random()}),this.drawMode=ha,this.updateMorphTargets()}function dt(t,e,i,n){this.isPlaneBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="PlaneBufferGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:n};for(var r=t/2,a=e/2,o=Math.floor(i)||1,s=Math.floor(n)||1,h=o+1,c=s+1,l=t/o,u=e/s,p=new Float32Array(h*c*3),d=new Float32Array(h*c*3),f=new Float32Array(h*c*2),m=0,g=0,v=0;v65535?Uint32Array:Uint16Array)(o*s*6),v=0;v=0){var l=a[h];if(void 0!==l){var u=ee.FLOAT,p=l.array,d=l.normalized;p instanceof Float32Array?u=ee.FLOAT:p instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):p instanceof Uint16Array?u=ee.UNSIGNED_SHORT:p instanceof Int16Array?u=ee.SHORT:p instanceof Uint32Array?u=ee.UNSIGNED_INT:p instanceof Int32Array?u=ee.INT:p instanceof Int8Array?u=ee.BYTE:p instanceof Uint8Array&&(u=ee.UNSIGNED_BYTE);var f=l.itemSize,m=he.getAttributeBuffer(l);if(l&&l.isInterleavedBufferAttribute){var g=l.data,v=g.stride,y=l.offset;g&&g.isInstancedInterleavedBuffer?(ae.enableAttributeAndDivisor(c,g.meshPerAttribute,r),void 0===i.maxInstancedCount&&(i.maxInstancedCount=g.meshPerAttribute*g.count)):ae.enableAttribute(c),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(c,f,u,d,v*g.array.BYTES_PER_ELEMENT,(n*v+y)*g.array.BYTES_PER_ELEMENT)}else l&&l.isInstancedBufferAttribute?(ae.enableAttributeAndDivisor(c,l.meshPerAttribute,r),void 0===i.maxInstancedCount&&(i.maxInstancedCount=l.meshPerAttribute*l.count)):ae.enableAttribute(c),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(c,f,u,d,0,n*f*l.array.BYTES_PER_ELEMENT)}else if(void 0!==s){var x=s[h];if(void 0!==x)switch(x.length){case 2:ee.vertexAttrib2fv(c,x);break;case 3:ee.vertexAttrib3fv(c,x);break;case 4:ee.vertexAttrib4fv(c,x);break;default:ee.vertexAttrib1fv(c,x)}}}}ae.disableUnusedAttributes()}function y(t,e){return Math.abs(e[0])-Math.abs(t[0])}function x(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.material.program&&e.material.program&&t.material.program!==e.material.program?t.material.program.id-e.material.program.id:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function b(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function M(t,e,i,n,r){var a,o;i.transparent?(a=wt,o=++Mt):(a=bt,o=++_t);var s=a[o];void 0!==s?(s.id=t.id,s.object=t,s.geometry=e,s.material=i,s.z=Kt.z,s.group=r):(s={id:t.id,object:t,geometry:e,material:i,z:Kt.z,group:r},a.push(s))}function E(t){var e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),Jt.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),A(Jt)}function S(t){return Jt.center.set(0,0,0),Jt.radius=.7071067811865476,Jt.applyMatrix4(t.matrixWorld),A(Jt)}function A(t){if(!Xt.intersectsSphere(t))return!1;var e=Yt.numPlanes;if(0===e)return!0;var i=At.clippingPlanes,n=t.center,r=-t.radius,a=0;do if(i[a].distanceToPoint(n)=0&&e.numSupportedMorphTargets++}if(e.morphNormals){e.numSupportedMorphNormals=0;for(var p=0;p=0&&e.numSupportedMorphNormals++}var d=r.__webglShader.uniforms;(e&&e.isShaderMaterial||e&&e.isRawShaderMaterial)&&e.clipping!==!0||(r.numClippingPlanes=Yt.numPlanes,d.clippingPlanes=Yt.uniform),e.lights&&(r.lightsHash=$t.hash,d.ambientLightColor.value=$t.ambient,d.directionalLights.value=$t.directional,d.spotLights.value=$t.spot,d.pointLights.value=$t.point,d.hemisphereLights.value=$t.hemi,d.directionalShadowMap.value=$t.directionalShadowMap,d.directionalShadowMatrix.value=$t.directionalShadowMatrix,d.spotShadowMap.value=$t.spotShadowMap, d.spotShadowMatrix.value=$t.spotShadowMatrix,d.pointShadowMap.value=$t.pointShadowMap,d.pointShadowMatrix.value=$t.pointShadowMatrix);var f=r.program.getUniforms(),m=t.WebGLUniforms.seqWithValue(f.seq,d);r.uniformsList=m,r.dynamicUniforms=t.WebGLUniforms.splitDynamic(m,d)}function N(t){t.side!==xn?ae.enable(ee.CULL_FACE):ae.disable(ee.CULL_FACE),ae.setFlipSided(t.side===yn),t.transparent===!0?ae.setBlending(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.premultipliedAlpha):ae.setBlending(Tn),ae.setDepthFunc(t.depthFunc),ae.setDepthTest(t.depthTest),ae.setDepthWrite(t.depthWrite),ae.setColorWrite(t.colorWrite),ae.setPolygonOffset(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits)}function O(e,i,n,r){Ft=0;var a=oe.get(n);if(qt){if(Zt||e!==It){var o=e===It&&n.id===Ct;Yt.setState(n.clippingPlanes,n.clipShadows,e,a,o)}void 0!==a.numClippingPlanes&&a.numClippingPlanes!==Yt.numPlanes&&(n.needsUpdate=!0)}void 0===a.program&&(n.needsUpdate=!0),void 0!==a.lightsHash&&a.lightsHash!==$t.hash&&(n.needsUpdate=!0),n.needsUpdate&&(D(n,i,r),n.needsUpdate=!1);var s=!1,h=!1,c=!1,l=a.program,u=l.getUniforms(),p=a.__webglShader.uniforms;if(l.id!==Lt&&(ee.useProgram(l.program),Lt=l.id,s=!0,h=!0,c=!0),n.id!==Ct&&(Ct=n.id,h=!0),s||e!==It){if(u.set(ee,e,"projectionMatrix"),re.logarithmicDepthBuffer&&u.setValue(ee,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),e!==It&&(It=e,h=!0,c=!0),n&&n.isShaderMaterial||n&&n.isMeshPhongMaterial||n&&n.isMeshStandardMaterial||n.envMap){var d=u.map.cameraPosition;void 0!==d&&d.setValue(ee,Kt.setFromMatrixPosition(e.matrixWorld))}(n&&n.isMeshPhongMaterial||n&&n.isMeshLambertMaterial||n&&n.isMeshBasicMaterial||n&&n.isMeshStandardMaterial||n&&n.isShaderMaterial||n.skinning)&&u.setValue(ee,"viewMatrix",e.matrixWorldInverse),u.set(ee,At,"toneMappingExposure"),u.set(ee,At,"toneMappingWhitePoint")}if(n.skinning){u.setOptional(ee,r,"bindMatrix"),u.setOptional(ee,r,"bindMatrixInverse");var f=r.skeleton;f&&(re.floatVertexTextures&&f.useVertexTexture?(u.set(ee,f,"boneTexture"),u.set(ee,f,"boneTextureWidth"),u.set(ee,f,"boneTextureHeight")):u.setOptional(ee,f,"boneMatrices"))}h&&(n.lights&&X(p,c),i&&n.fog&&H(p,i),(n&&n.isMeshBasicMaterial||n&&n.isMeshLambertMaterial||n&&n.isMeshPhongMaterial||n&&n.isMeshStandardMaterial||n&&n.isMeshDepthMaterial)&&F(p,n),n&&n.isLineBasicMaterial?B(p,n):n&&n.isLineDashedMaterial?(B(p,n),z(p,n)):n&&n.isPointsMaterial?G(p,n):n&&n.isMeshLambertMaterial?V(p,n):n&&n.isMeshPhongMaterial?k(p,n):n&&n.isMeshPhysicalMaterial?W(p,n):n&&n.isMeshStandardMaterial?j(p,n):n&&n.isMeshDepthMaterial?n.displacementMap&&(p.displacementMap.value=n.displacementMap,p.displacementScale.value=n.displacementScale,p.displacementBias.value=n.displacementBias):n&&n.isMeshNormalMaterial&&(p.opacity.value=n.opacity),t.WebGLUniforms.upload(ee,a.uniformsList,p,At)),u.set(ee,r,"modelViewMatrix"),u.set(ee,r,"normalMatrix"),u.setValue(ee,"modelMatrix",r.matrixWorld);var m=a.dynamicUniforms;return null!==m&&(t.WebGLUniforms.evalDynamic(m,p,r,e),t.WebGLUniforms.upload(ee,m,p,At)),l}function F(t,e){t.opacity.value=e.opacity,t.diffuse.value=e.color,e.emissive&&t.emissive.value.copy(e.emissive).multiplyScalar(e.emissiveIntensity),t.map.value=e.map,t.specularMap.value=e.specularMap,t.alphaMap.value=e.alphaMap,e.aoMap&&(t.aoMap.value=e.aoMap,t.aoMapIntensity.value=e.aoMapIntensity);var i;if(e.map?i=e.map:e.specularMap?i=e.specularMap:e.displacementMap?i=e.displacementMap:e.normalMap?i=e.normalMap:e.bumpMap?i=e.bumpMap:e.roughnessMap?i=e.roughnessMap:e.metalnessMap?i=e.metalnessMap:e.alphaMap?i=e.alphaMap:e.emissiveMap&&(i=e.emissiveMap),void 0!==i){i&&i.isWebGLRenderTarget&&(i=i.texture);var n=i.offset,r=i.repeat;t.offsetRepeat.value.set(n.x,n.y,r.x,r.y)}t.envMap.value=e.envMap,t.flipEnvMap.value=e.envMap&&e.envMap.isCubeTexture?-1:1,t.reflectivity.value=e.reflectivity,t.refractionRatio.value=e.refractionRatio}function B(t,e){t.diffuse.value=e.color,t.opacity.value=e.opacity}function z(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}function G(t,e){if(t.diffuse.value=e.color,t.opacity.value=e.opacity,t.size.value=e.size*Vt,t.scale.value=.5*K.clientHeight,t.map.value=e.map,null!==e.map){var i=e.map.offset,n=e.map.repeat;t.offsetRepeat.value.set(i.x,i.y,n.x,n.y)}}function H(t,e){t.fogColor.value=e.color,e&&e.isFog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e&&e.isFogExp2&&(t.fogDensity.value=e.density)}function V(t,e){e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap)}function k(t,e){t.specular.value=e.specular,t.shininess.value=Math.max(e.shininess,1e-4),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}function j(t,e){t.roughness.value=e.roughness,t.metalness.value=e.metalness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap),e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias),e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}function W(t,e){t.clearCoat.value=e.clearCoat,t.clearCoatRoughness.value=e.clearCoatRoughness,j(t,e)}function X(t,e){t.ambientLightColor.needsUpdate=e,t.directionalLights.needsUpdate=e,t.pointLights.needsUpdate=e,t.spotLights.needsUpdate=e,t.hemisphereLights.needsUpdate=e}function Y(t){for(var e=0,i=0,n=t.length;i=re.maxTextures&&console.warn("WebGLRenderer: trying to use "+t+" texture units while this GPU supports only "+re.maxTextures),Ft+=1,t}function J(t){var e;if(t===vr)return ee.REPEAT;if(t===yr)return ee.CLAMP_TO_EDGE;if(t===xr)return ee.MIRRORED_REPEAT;if(t===br)return ee.NEAREST;if(t===_r)return ee.NEAREST_MIPMAP_NEAREST;if(t===wr)return ee.NEAREST_MIPMAP_LINEAR;if(t===Mr)return ee.LINEAR;if(t===Er)return ee.LINEAR_MIPMAP_NEAREST;if(t===Tr)return ee.LINEAR_MIPMAP_LINEAR;if(t===Sr)return ee.UNSIGNED_BYTE;if(t===Dr)return ee.UNSIGNED_SHORT_4_4_4_4;if(t===Nr)return ee.UNSIGNED_SHORT_5_5_5_1;if(t===Or)return ee.UNSIGNED_SHORT_5_6_5;if(t===Ar)return ee.BYTE;if(t===Lr)return ee.SHORT;if(t===Rr)return ee.UNSIGNED_SHORT;if(t===Pr)return ee.INT;if(t===Cr)return ee.UNSIGNED_INT;if(t===Ur)return ee.FLOAT;if(e=ne.get("OES_texture_half_float"),null!==e&&t===Ir)return e.HALF_FLOAT_OES;if(t===Fr)return ee.ALPHA;if(t===Br)return ee.RGB;if(t===zr)return ee.RGBA;if(t===Gr)return ee.LUMINANCE;if(t===Hr)return ee.LUMINANCE_ALPHA;if(t===kr)return ee.DEPTH_COMPONENT;if(t===Cn)return ee.FUNC_ADD;if(t===Un)return ee.FUNC_SUBTRACT;if(t===In)return ee.FUNC_REVERSE_SUBTRACT;if(t===On)return ee.ZERO;if(t===Fn)return ee.ONE;if(t===Bn)return ee.SRC_COLOR;if(t===zn)return ee.ONE_MINUS_SRC_COLOR;if(t===Gn)return ee.SRC_ALPHA;if(t===Hn)return ee.ONE_MINUS_SRC_ALPHA;if(t===Vn)return ee.DST_ALPHA;if(t===kn)return ee.ONE_MINUS_DST_ALPHA;if(t===jn)return ee.DST_COLOR;if(t===Wn)return ee.ONE_MINUS_DST_COLOR;if(t===Xn)return ee.SRC_ALPHA_SATURATE;if(e=ne.get("WEBGL_compressed_texture_s3tc"),null!==e){if(t===jr)return e.COMPRESSED_RGB_S3TC_DXT1_EXT;if(t===Wr)return e.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(t===Xr)return e.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(t===Yr)return e.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e=ne.get("WEBGL_compressed_texture_pvrtc"),null!==e){if(t===qr)return e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(t===Zr)return e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(t===Jr)return e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(t===Qr)return e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e=ne.get("WEBGL_compressed_texture_etc1"),null!==e&&t===Kr)return e.COMPRESSED_RGB_ETC1_WEBGL;if(e=ne.get("EXT_blend_minmax"),null!==e){if(t===Dn)return e.MIN_EXT;if(t===Nn)return e.MAX_EXT}return 0}this.isWebGLRenderer=!0,console.log("THREE.WebGLRenderer","79dev"),e=e||{};var K=void 0!==e.canvas?e.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),ot=void 0!==e.context?e.context:null,ht=void 0!==e.alpha&&e.alpha,ct=void 0===e.depth||e.depth,lt=void 0===e.stencil||e.stencil,ft=void 0!==e.antialias&&e.antialias,vt=void 0===e.premultipliedAlpha||e.premultipliedAlpha,yt=void 0!==e.preserveDrawingBuffer&&e.preserveDrawingBuffer,xt=[],bt=[],_t=-1,wt=[],Mt=-1,Et=new Float32Array(8),Tt=[],St=[];this.domElement=K,this.context=null,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.gammaFactor=2,this.gammaInput=!1,this.gammaOutput=!1,this.physicallyCorrectLights=!1,this.toneMapping=ar,this.toneMappingExposure=1,this.toneMappingWhitePoint=1,this.maxMorphTargets=8,this.maxMorphNormals=4;var At=this,Lt=null,Rt=null,Pt=null,Ct=-1,Ut="",It=null,Dt=new d,Nt=null,Ot=new d,Ft=0,Bt=new w(0),zt=0,Gt=K.width,Ht=K.height,Vt=1,kt=new d(0,0,Gt,Ht),jt=!1,Wt=new d(0,0,Gt,Ht),Xt=new L,Yt=new rt,qt=!1,Zt=!1,Jt=new T,Qt=new a,Kt=new s,$t={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},te={calls:0,vertices:0,faces:0,points:0};this.info={render:te,memory:{geometries:0,textures:0},programs:null};var ee;try{var ie={alpha:ht,depth:ct,stencil:lt,antialias:ft,premultipliedAlpha:vt,preserveDrawingBuffer:yt};if(ee=ot||K.getContext("webgl",ie)||K.getContext("experimental-webgl",ie),null===ee)throw null!==K.getContext("webgl")?"Error creating WebGL context with your selected attributes.":"Error creating WebGL context.";void 0===ee.getShaderPrecisionFormat&&(ee.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}}),K.addEventListener("webglcontextlost",c,!1)}catch(t){console.error("THREE.WebGLRenderer: "+t)}var ne=new it(ee);ne.get("WEBGL_depth_texture"),ne.get("OES_texture_float"),ne.get("OES_texture_float_linear"),ne.get("OES_texture_half_float"),ne.get("OES_texture_half_float_linear"),ne.get("OES_standard_derivatives"),ne.get("ANGLE_instanced_arrays"),ne.get("OES_element_index_uint")&&(Q.MaxIndex=4294967296);var re=new et(ee,ne,e),ae=new f(ee,ne,J),oe=new P,se=new p(ee,ne,ae,oe,re,J,this.info),he=new $(ee,oe,this.info),ce=new C(this,re),le=new tt;this.info.programs=ce.programs;var ue=new at(ee,ne,te),pe=new nt(ee,ne,te),de=new gt((-1),1,1,(-1),0,1),fe=new mt,me=new pt(new dt(2,2),new ut({depthTest:!1,depthWrite:!1,fog:!1})),ge=t.ShaderLib.cube,ve=new pt(new st(5,5,5),new _({uniforms:ge.uniforms,vertexShader:ge.vertexShader,fragmentShader:ge.fragmentShader,side:yn,depthTest:!1,depthWrite:!1,fog:!1}));r(),this.context=ee,this.capabilities=re,this.extensions=ne,this.properties=oe,this.state=ae;var ye=new R(this,$t,he,re);this.shadowMap=ye;var xe=new h(this,Tt),be=new l(this,St);this.getContext=function(){return ee},this.getContextAttributes=function(){return ee.getContextAttributes()},this.forceContextLoss=function(){ne.get("WEBGL_lose_context").loseContext()},this.getMaxAnisotropy=function(){return re.getMaxAnisotropy()},this.getPrecision=function(){return re.precision},this.getPixelRatio=function(){return Vt},this.setPixelRatio=function(t){void 0!==t&&(Vt=t,this.setSize(Wt.z,Wt.w,!1))},this.getSize=function(){return{width:Gt,height:Ht}},this.setSize=function(t,e,i){Gt=t,Ht=e,K.width=t*Vt,K.height=e*Vt,i!==!1&&(K.style.width=t+"px",K.style.height=e+"px"),this.setViewport(0,0,t,e)},this.setViewport=function(t,e,i,n){ae.viewport(Wt.set(t,e,i,n))},this.setScissor=function(t,e,i,n){ae.scissor(kt.set(t,e,i,n))},this.setScissorTest=function(t){ae.setScissorTest(jt=t)},this.getClearColor=function(){return Bt},this.setClearColor=function(t,e){Bt.set(t),zt=void 0!==e?e:1,n(Bt.r,Bt.g,Bt.b,zt)},this.getClearAlpha=function(){return zt},this.setClearAlpha=function(t){zt=t,n(Bt.r,Bt.g,Bt.b,zt)},this.clear=function(t,e,i){var n=0;(void 0===t||t)&&(n|=ee.COLOR_BUFFER_BIT),(void 0===e||e)&&(n|=ee.DEPTH_BUFFER_BIT),(void 0===i||i)&&(n|=ee.STENCIL_BUFFER_BIT),ee.clear(n)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.clearTarget=function(t,e,i,n){this.setRenderTarget(t),this.clear(e,i,n)},this.resetGLState=o,this.dispose=function(){wt=[],Mt=-1,bt=[],_t=-1,K.removeEventListener("webglcontextlost",c,!1)},this.renderBufferImmediate=function(t,e,i){ae.initAttributes();var n=oe.get(t);t.hasPositions&&!n.position&&(n.position=ee.createBuffer()),t.hasNormals&&!n.normal&&(n.normal=ee.createBuffer()),t.hasUvs&&!n.uv&&(n.uv=ee.createBuffer()),t.hasColors&&!n.color&&(n.color=ee.createBuffer());var r=e.getAttributes();if(t.hasPositions&&(ee.bindBuffer(ee.ARRAY_BUFFER,n.position),ee.bufferData(ee.ARRAY_BUFFER,t.positionArray,ee.DYNAMIC_DRAW),ae.enableAttribute(r.position),ee.vertexAttribPointer(r.position,3,ee.FLOAT,!1,0,0)),t.hasNormals){if(ee.bindBuffer(ee.ARRAY_BUFFER,n.normal),"MeshPhongMaterial"!==i.type&&"MeshStandardMaterial"!==i.type&&"MeshPhysicalMaterial"!==i.type&&i.shading===bn)for(var a=0,o=3*t.count;a8&&(u.length=8);for(var m=n.morphAttributes,p=0,d=u.length;p0&&b.renderInstances(n,A,R):b.render(A,R)},this.render=function(t,e,i,r){if((e&&e.isCamera)===!1)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");var a=t.fog;Ut="",Ct=-1,It=null,t.autoUpdate===!0&&t.updateMatrixWorld(),null===e.parent&&e.updateMatrixWorld(),e.matrixWorldInverse.getInverse(e.matrixWorld),Qt.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Xt.setFromMatrix(Qt),xt.length=0,_t=-1,Mt=-1,Tt.length=0,St.length=0,Zt=this.localClippingEnabled,qt=Yt.init(this.clippingPlanes,Zt,e),U(t,e),bt.length=_t+1,wt.length=Mt+1,At.sortObjects===!0&&(bt.sort(x),wt.sort(b)),qt&&Yt.beginShadows(),Y(xt),ye.render(t,e),q(xt,e),qt&&Yt.endShadows(),te.calls=0,te.vertices=0,te.faces=0,te.points=0,void 0===i&&(i=null),this.setRenderTarget(i);var o=t.background;if(null===o?n(Bt.r,Bt.g,Bt.b,zt):o&&o.isColor&&n(o.r,o.g,o.b,1),(this.autoClear||r)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil),o&&o.isCubeTexture?(fe.projectionMatrix.copy(e.projectionMatrix),fe.matrixWorld.extractRotation(e.matrixWorld),fe.matrixWorldInverse.getInverse(fe.matrixWorld),ve.material.uniforms.tCube.value=o,ve.modelViewMatrix.multiplyMatrices(fe.matrixWorldInverse,ve.matrixWorld),he.update(ve),At.renderBufferDirect(fe,null,ve.geometry,ve.material,ve,null)):o&&o.isTexture&&(me.material.map=o,he.update(me),At.renderBufferDirect(de,null,me.geometry,me.material,me,null)),t.overrideMaterial){var s=t.overrideMaterial;I(bt,e,a,s),I(wt,e,a,s)}else ae.setBlending(Tn),I(bt,e,a),I(wt,e,a);xe.render(t,e),be.render(t,e,Ot),i&&se.updateRenderTargetMipmap(i),ae.setDepthTest(!0),ae.setDepthWrite(!0),ae.setColorWrite(!0)},this.setFaceCulling=function(t,e){ae.setCullFace(t),ae.setFlipSided(e===pn)},this.allocTextureUnit=Z,this.setTexture2D=function(){var t=!1;return function(e,i){e&&e.isWebGLRenderTarget&&(t||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),se.setTexture2D(e,i)}}(),this.setTexture=function(){var t=!1;return function(e,i){t||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),t=!0),se.setTexture2D(e,i)}}(),this.setTextureCube=function(){var t=!1;return function(e,i){e&&e.isWebGLRenderTargetCube&&(t||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),e&&e.isCubeTexture||Array.isArray(e.image)&&6===e.image.length?se.setTextureCube(e,i):se.setTextureCubeDynamic(e,i)}}(),this.getCurrentRenderTarget=function(){return Rt},this.setRenderTarget=function(t){Rt=t,t&&void 0===oe.get(t).__webglFramebuffer&&se.setupRenderTarget(t);var e,i=t&&t.isWebGLRenderTargetCube;if(t){var n=oe.get(t);e=i?n.__webglFramebuffer[t.activeCubeFace]:n.__webglFramebuffer,Dt.copy(t.scissor),Nt=t.scissorTest,Ot.copy(t.viewport)}else e=null,Dt.copy(kt).multiplyScalar(Vt),Nt=jt,Ot.copy(Wt).multiplyScalar(Vt);if(Pt!==e&&(ee.bindFramebuffer(ee.FRAMEBUFFER,e),Pt=e),ae.scissor(Dt),ae.setScissorTest(Nt),ae.viewport(Ot),i){var r=oe.get(t.texture);ee.framebufferTexture2D(ee.FRAMEBUFFER,ee.COLOR_ATTACHMENT0,ee.TEXTURE_CUBE_MAP_POSITIVE_X+t.activeCubeFace,r.__webglTexture,t.activeMipMapLevel)}},this.readRenderTargetPixels=function(t,e,i,n,r,a){if((t&&t.isWebGLRenderTarget)===!1)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");var o=oe.get(t).__webglFramebuffer;if(o){var s=!1;o!==Pt&&(ee.bindFramebuffer(ee.FRAMEBUFFER,o),s=!0);try{var h=t.texture;if(h.format!==zr&&J(h.format)!==ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!(h.type===Sr||J(h.type)===ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_TYPE)||h.type===Ur&&ne.get("WEBGL_color_buffer_float")||h.type===Ir&&ne.get("EXT_color_buffer_half_float")))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");ee.checkFramebufferStatus(ee.FRAMEBUFFER)===ee.FRAMEBUFFER_COMPLETE?e>=0&&e<=t.width-n&&i>=0&&i<=t.height-r&&ee.readPixels(e,i,n,r,J(h.format),J(h.type),a):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{s&&ee.bindFramebuffer(ee.FRAMEBUFFER,Pt)}}}}function yt(t,e){this.isFogExp2=!0,this.name="",this.color=new w(t),this.density=void 0!==e?e:25e-5}function xt(t,e,i){this.isFog=!0,this.name="",this.color=new w(t),this.near=void 0!==e?e:1,this.far=void 0!==i?i:1e3}function bt(){this.isScene=this.isObject3D=!0,X.call(this),this.type="Scene",this.background=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0}function _t(t,e,i,n,r){this.isLensFlare=!0,X.call(this),this.lensFlares=[],this.positionScreen=new s,this.customUpdateCallback=void 0,void 0!==t&&this.add(t,e,i,n,r)}function wt(t){this.isSpriteMaterial=this.isMaterial=!0,x.call(this),this.type="SpriteMaterial",this.color=new w(16777215),this.map=null,this.rotation=0,this.fog=!1,this.lights=!1,this.setValues(t)}function Mt(t){this.isSprite=!0,X.call(this),this.type="Sprite",this.material=void 0!==t?t:new wt}function Et(){this.isLOD=!0,X.call(this),this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Tt(t,e,i,r,a,o,s,h,c,l,u,p){this.isDataTexture=this.isTexture=!0,n.call(this,null,o,s,h,c,l,r,a,u,p),this.image={data:t,width:e,height:i},this.magFilter=void 0!==c?c:br,this.minFilter=void 0!==l?l:br,this.flipY=!1,this.generateMipmaps=!1}function St(e,i,n){if(this.isSkeleton=!0,this.useVertexTexture=void 0===n||n,this.identityMatrix=new a,e=e||[],this.bones=e.slice(0),this.useVertexTexture){var r=Math.sqrt(4*this.bones.length);r=t.Math.nextPowerOfTwo(Math.ceil(r)),r=Math.max(r,4),this.boneTextureWidth=r,this.boneTextureHeight=r,this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new Tt(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,zr,Ur)}else this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===i)this.calculateInverses();else if(this.bones.length===i.length)this.boneInverses=i.slice(0);else{console.warn("THREE.Skeleton bonInverses is the wrong length."),this.boneInverses=[];for(var o=0,s=this.bones.length;o=t.HAVE_CURRENT_DATA&&(u.needsUpdate=!0)}this.isVideoTexture=this.isTexture=!0,n.call(this,t,e,i,r,a,o,s,h,c),this.generateMipmaps=!1;var u=this;l()}function Ot(t,e,i,r,a,o,s,h,c,l,u,p){this.isCompressedTexture=this.isTexture=!0,n.call(this,null,o,s,h,c,l,r,a,u,p),this.image={width:e,height:i},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}function Ft(t,e,i,r,a,o,s,h,c){this.isCanvasTexture=this.isTexture=!0,n.call(this,t,e,i,r,a,o,s,h,c),this.needsUpdate=!0}function Bt(t,e,i,r,a,o,s,h,c){this.isDepthTexture=this.isTexture=!0,n.call(this,null,r,a,o,s,h,kr,i,c),this.image={width:t,height:e},this.type=void 0!==i?i:Rr,this.magFilter=void 0!==s?s:br,this.minFilter=void 0!==h?h:br,this.flipY=!1,this.generateMipmaps=!1}function zt(){this.isShadowMaterial=this.isShaderMaterial=this.isMaterial=!0,_.call(this,{uniforms:t.UniformsUtils.merge([t.UniformsLib.lights,{opacity:{value:1}}]),vertexShader:ws.shadow_vert,fragmentShader:ws.shadow_frag}),this.lights=!0,this.transparent=!0,Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(t){this.uniforms.opacity.value=t}}})}function Gt(t){this.isRawShaderMaterial=this.isShaderMaterial=this.isMaterial=!0,_.call(this,t),this.type="RawShaderMaterial"}function Ht(e){this.isMultiMaterial=!0,this.uuid=t.Math.generateUUID(),this.type="MultiMaterial",this.materials=e instanceof Array?e:[],this.visible=!0}function Vt(t){this.isMeshStandardMaterial=this.isMaterial=!0,x.call(this),this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new w(16777215),this.roughness=.5,this.metalness=.5,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new i(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function kt(t){this.isMeshPhysicalMaterial=this.isMeshStandardMaterial=this.isMaterial=!0,Vt.call(this),this.defines={PHYSICAL:""},this.type="MeshPhysicalMaterial",this.reflectivity=.5,this.clearCoat=0,this.clearCoatRoughness=0,this.setValues(t)}function jt(t){this.isMeshPhongMaterial=this.isMaterial=!0,x.call(this),this.type="MeshPhongMaterial",this.color=new w(16777215),this.specular=new w(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new i(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Wt(t){this.isMeshNormalMaterial=this.isMaterial=!0,x.call(this,t),this.type="MeshNormalMaterial",this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.morphTargets=!1,this.setValues(t)}function Xt(t){this.isMeshLambertMaterial=this.isMaterial=!0,x.call(this),this.type="MeshLambertMaterial",this.color=new w(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Yt(t){this.isLineDashedMaterial=this.isMaterial=!0,x.call(this),this.type="LineDashedMaterial",this.color=new w(16777215),this.linewidth=1,this.scale=1,this.dashSize=3,this.gapSize=1,this.lights=!1,this.setValues(t)}function qt(t,e,i){this.isLoadingManager=!0;var n=this,r=!1,a=0,o=0;this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=i,this.itemStart=function(t){o++,r===!1&&void 0!==n.onStart&&n.onStart(t,a,o),r=!0},this.itemEnd=function(t){a++,void 0!==n.onProgress&&n.onProgress(t,a,o),a===o&&(r=!1,void 0!==n.onLoad&&n.onLoad())},this.itemError=function(t){void 0!==n.onError&&n.onError(t)}}function Zt(e){this.isXHRLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function Jt(e){this.isCompressedTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Qt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Kt(e){this.isImageLoader=!0, this.manager=void 0!==e?e:t.DefaultLoadingManager}function $t(e){this.isCubeTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function te(e){this.isTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function ee(t,e){this.isLight=!0,X.call(this),this.type="Light",this.color=new w(t),this.intensity=void 0!==e?e:1,this.receiveShadow=void 0}function ie(t,e,i){this.isHemisphereLight=!0,ee.call(this,t,i),this.type="HemisphereLight",this.castShadow=void 0,this.position.copy(X.DefaultUp),this.updateMatrix(),this.groundColor=new w(e)}function ne(t){this.isLightShadow=!0,this.camera=t,this.bias=0,this.radius=1,this.mapSize=new i(512,512),this.map=null,this.matrix=new a}function re(){this.isSpotLightShadow=!0,ne.call(this,new mt(50,1,.5,500))}function ae(t,e,i,n,r,a){this.isSpotLight=!0,ee.call(this,t,e),this.type="SpotLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(t){this.intensity=t/Math.PI}}),this.distance=void 0!==i?i:0,this.angle=void 0!==n?n:Math.PI/3,this.penumbra=void 0!==r?r:0,this.decay=void 0!==a?a:1,this.shadow=new re}function oe(t,e,i,n){this.isPointLight=!0,ee.call(this,t,e),this.type="PointLight",Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(t){this.intensity=t/(4*Math.PI)}}),this.distance=void 0!==i?i:0,this.decay=void 0!==n?n:1,this.shadow=new ne(new mt(90,1,.5,500))}function se(t){this.isDirectionalLightShadow=!0,ne.call(this,new gt((-5),5,5,(-5),.5,500))}function he(t,e){this.isDirectionalLight=!0,ee.call(this,t,e),this.type="DirectionalLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,this.shadow=new se}function ce(t,e){this.isAmbientLight=!0,ee.call(this,t,e),this.type="AmbientLight",this.castShadow=void 0}function le(t,e,i,n){this.isInterpolant=!0,this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==n?n:new e.constructor(i),this.sampleValues=e,this.valueSize=i}function ue(t,e,i,n){this.isCubicInterpolant=!0,le.call(this,t,e,i,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0}function pe(t,e,i,n){this.isLinearInterpolant=!0,le.call(this,t,e,i,n)}function de(t,e,i,n){this.isDiscreteInterpolant=!0,le.call(this,t,e,i,n)}function fe(e,i,n,r){if(this.isKeyframeTrack=!0,void 0===e)throw new Error("track name is undefined");if(void 0===i||0===i.length)throw new Error("no keyframes in track named "+e);this.name=e,this.times=t.AnimationUtils.convertArray(i,this.TimeBufferType),this.values=t.AnimationUtils.convertArray(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation),this.validate(),this.optimize()}function me(t,e,i,n){this.isVectorKeyframeTrack=!0,fe.call(this,t,e,i,n)}function ge(t,e,i,n){this.isQuaternionLinearInterpolant=!0,le.call(this,t,e,i,n)}function ve(t,e,i,n){this.isQuaternionKeyframeTrack=!0,fe.call(this,t,e,i,n)}function ye(t,e,i,n){this.isNumberKeyframeTrack=!0,fe.call(this,t,e,i,n)}function xe(t,e,i,n){this.isStringKeyframeTrack=!0,fe.call(this,t,e,i,n)}function be(t,e,i){this.isBooleanKeyframeTrack=!0,fe.call(this,t,e,i)}function _e(t,e,i,n){this.isColorKeyframeTrack=!0,fe.call(this,t,e,i,n)}function we(t,e,i,n){fe.apply(this,arguments)}function Me(e,i,n){this.isAnimationClip=!0,this.name=e,this.tracks=n,this.duration=void 0!==i?i:-1,this.uuid=t.Math.generateUUID(),this.duration<0&&this.resetDuration(),this.trim(),this.optimize()}function Ee(e){this.isMaterialLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this.textures={}}function Te(e){this.isBufferGeometryLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function Se(){this.isLoader=!0,this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){}}function Ae(e){this.isJSONLoader=!0,"boolean"==typeof e&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),e=void 0),this.manager=void 0!==e?e:t.DefaultLoadingManager,this.withCredentials=!1}function Le(e){this.isObjectLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this.texturePath=""}function Re(){this.isCurve=!0}function Pe(t,e){this.isLineCurve=this.isCurve=!0,this.v1=t,this.v2=e}function Ce(){this.isCurvePath=!0,this.curves=[],this.autoClose=!1}function Ue(t,e,i,n,r,a,o,s){this.isEllipseCurve=this.isCurve=!0,this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=n,this.aStartAngle=r,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s||0}function Ie(t){this.isSplineCurve=this.isCurve=!0,this.points=void 0==t?[]:t}function De(t,e,i,n){this.isCubicBezierCurve=this.isCurve=!0,this.v0=t,this.v1=e,this.v2=i,this.v3=n}function Ne(t,e,i){this.isQuadraticBezierCurve=this.isCurve=!0,this.v0=t,this.v1=e,this.v2=i}function Oe(t,e,n,r,a,o){function h(t,e,i){return C.vertices.push(new s(t,e,i))-1}this.isTubeGeometry=this.isGeometry=!0,q.call(this),this.type="TubeGeometry",this.parameters={path:t,segments:e,radius:n,radialSegments:r,closed:a,taper:o},e=e||64,n=n||1,r=r||8,a=a||!1,o=o||Oe.NoTaper;var c,l,u,p,d,f,m,g,v,y,x,b,_,w,M,E,T,S,A,L,R,P=[],C=this,U=e+1,I=new s,D=new Oe.FrenetFrames(t,e,a),N=D.tangents,O=D.normals,F=D.binormals;for(this.tangents=N,this.normals=O,this.binormals=F,y=0;ythis.points.length-2?this.points.length-1:n+1,p[3]=n>this.points.length-3?this.points.length-1:n+2,h=this.points[p[0]],c=this.points[p[1]],l=this.points[p[2]],u=this.points[p[3]],a=r*r,o=r*a,d.x=e(h.x,c.x,l.x,u.x,r,a,o),d.y=e(h.y,c.y,l.y,u.y,r,a,o),d.z=e(h.z,c.z,l.z,u.z,r,a,o),d},this.getControlPointsArray=function(){var t,e,i=this.points.length,n=[];for(t=0;t0)&&E.push(S,A,R),(g!==i-1||h65535?z:F)(E,1)),this.addAttribute("position",l),this.addAttribute("normal",u),this.addAttribute("uv",p),this.boundingSphere=new T(new s,t)}function Mi(t,e){this.isPointLightHelper=this.isMesh=!0,this.light=t,this.light.updateMatrixWorld();var i=new wi(e,4,2),n=new ut({wireframe:!0,fog:!1});n.color.copy(this.light.color).multiplyScalar(this.light.intensity),pt.call(this,i,n),this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1}function Ei(t,e,i,n,r,a,o){this.isSphereGeometry=this.isGeometry=!0,q.call(this),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:i,phiStart:n,phiLength:r,thetaStart:a,thetaLength:o},this.fromBufferGeometry(new wi(t,e,i,n,r,a,o))}function Ti(t,e){this.isHemisphereLightHelper=this.isObject3D=!0,X.call(this),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.colors=[new w,new w];var i=new Ei(e,4,2);i.rotateX(-Math.PI/2);for(var n=0,r=8;n0&&m++,e>0&&m++);var g=l(),v=u(),y=new U(new(v>65535?Uint32Array:Uint16Array)(v),1),x=new U(new Float32Array(3*g),3),b=new U(new Float32Array(3*g),3),_=new U(new Float32Array(2*g),2),w=0,M=0,E=[],T=n/2,S=0;p(),o===!1&&(t>0&&d(!0),e>0&&d(!1)),this.setIndex(y),this.addAttribute("position",x),this.addAttribute("normal",b),this.addAttribute("uv",_)}function Oi(t){this.isAxisHelper=this.isLineSegments=!0,t=t||1;var e=new Float32Array([0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t]),i=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]),n=new Q;n.addAttribute("position",new U(e,3)),n.addAttribute("color",new U(i,3));var r=new Rt({vertexColors:En});Ct.call(this,n,r)}function Fi(t,e,n){this.isParametricGeometry=this.isGeometry=!0,q.call(this),this.type="ParametricGeometry",this.parameters={func:t,slices:e,stacks:n};var r,a,o,s,h,c=this.vertices,l=this.faces,u=this.faceVertexUvs[0],p=e+1;for(r=0;r<=n;r++)for(h=r/n,a=0;a<=e;a++)s=a/e,o=t(s,h),c.push(o);var d,f,m,g,v,y,x,b;for(r=0;r.9&&L<.1&&(M<.2&&(w[0].x+=1),E<.2&&(w[1].x+=1),S<.2&&(w[2].x+=1))}for(var d=0,f=this.vertices.length;d65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=new s,b=new s,_=new i,w=new s,M=new s,E=new s,T=new s,S=new s;for(c=0;c<=n;++c){var A=c/n*a*Math.PI*2;for(h(A,a,o,t,w),h(A+.01,a,o,t,M),T.subVectors(M,w),S.addVectors(M,w),E.crossVectors(T,S),S.crossVectors(E,T),E.normalize(),S.normalize(),l=0;l<=r;++l){var L=l/r*Math.PI*2,R=-e*Math.cos(L),P=e*Math.sin(L);x.x=w.x+(R*S.x+P*E.x),x.y=w.y+(R*S.y+P*E.y),x.z=w.z+(R*S.z+P*E.z),f.setXYZ(v,x.x,x.y,x.z),b.subVectors(x,w).normalize(),m.setXYZ(v,b.x,b.y,b.z),_.x=c/n,_.y=l/r,g.setXY(v,_.x,_.y),v++}}for(l=1;l<=n;l++)for(c=1;c<=r;c++){var C=(r+1)*(l-1)+(c-1),I=(r+1)*l+(c-1),D=(r+1)*l+c,N=(r+1)*(l-1)+c;d.setX(y,C),y++,d.setX(y,I),y++,d.setX(y,N),y++,d.setX(y,I),y++,d.setX(y,D),y++,d.setX(y,N),y++}this.setIndex(d),this.addAttribute("position",f),this.addAttribute("normal",m),this.addAttribute("uv",g)}function ji(t,e,i,n,r,a,o){this.isTorusKnotGeometry=this.isGeometry=!0,q.call(this),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,tubularSegments:i,radialSegments:n,p:r,q:a},void 0!==o&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead."),this.fromBufferGeometry(new ki(t,e,i,n,r,a)),this.mergeVertices()}function Wi(t,e,i,n,r){this.isTorusBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="TorusBufferGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:r},t=t||100,e=e||40,i=Math.floor(i)||8,n=Math.floor(n)||6,r=r||2*Math.PI;var a,o,h=(i+1)*(n+1),c=i*n*2*3,l=new(c>65535?Uint32Array:Uint16Array)(c),u=new Float32Array(3*h),p=new Float32Array(3*h),d=new Float32Array(2*h),f=0,m=0,g=0,v=new s,y=new s,x=new s;for(a=0;a<=i;a++)for(o=0;o<=n;o++){var b=o/n*r,_=a/i*Math.PI*2;y.x=(t+e*Math.cos(_))*Math.cos(b),y.y=(t+e*Math.cos(_))*Math.sin(b),y.z=e*Math.sin(_),u[f]=y.x,u[f+1]=y.y,u[f+2]=y.z,v.x=t*Math.cos(b),v.y=t*Math.sin(b),x.subVectors(y,v).normalize(),p[f]=x.x,p[f+1]=x.y,p[f+2]=x.z,d[m]=o/n,d[m+1]=a/i,f+=3,m+=2}for(a=1;a<=i;a++)for(o=1;o<=n;o++){var w=(n+1)*a+o-1,M=(n+1)*(a-1)+o-1,E=(n+1)*(a-1)+o,T=(n+1)*a+o;l[g]=w,l[g+1]=M,l[g+2]=T,l[g+3]=M,l[g+4]=E,l[g+5]=T,g+=6}this.setIndex(new U(l,1)), -this.addAttribute("position",new U(u,3)),this.addAttribute("normal",new U(p,3)),this.addAttribute("uv",new U(d,2))}function Xi(t,e,i,n,r){this.isTorusGeometry=this.isGeometry=!0,q.call(this),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:r},this.fromBufferGeometry(new Wi(t,e,i,n,r))}function Yi(t,e){this.isTextGeometry=this.isExtrudeGeometry=this.isGeometry=!0,e=e||{};var i=e.font;if((i&&i.isFont)===!1)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new q;var n=i.generateShapes(t,e.size,e.curveSegments);e.amount=void 0!==e.height?e.height:50,void 0===e.bevelThickness&&(e.bevelThickness=10),void 0===e.bevelSize&&(e.bevelSize=8),void 0===e.bevelEnabled&&(e.bevelEnabled=!1),Fe.call(this,n,e),this.type="TextGeometry"}function qi(t,e,n,r,a,o){this.isRingBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="RingBufferGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:n,phiSegments:r,thetaStart:a,thetaLength:o},t=t||20,e=e||50,a=void 0!==a?a:0,o=void 0!==o?o:2*Math.PI,n=void 0!==n?Math.max(3,n):8,r=void 0!==r?Math.max(1,r):1;var h,c,l,u=(n+1)*(r+1),p=n*r*2*3,d=new U(new(p>65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=t,b=(e-t)/r,_=new s,w=new i;for(c=0;c<=r;c++){for(l=0;l<=n;l++)h=a+l/n*o,_.x=x*Math.cos(h),_.y=x*Math.sin(h),f.setXYZ(v,_.x,_.y,_.z),m.setXYZ(v,0,0,1),w.x=(_.x/e+1)/2,w.y=(_.y/e+1)/2,g.setXY(v,w.x,w.y),v++;x+=b}for(c=0;c65535?Uint32Array:Uint16Array)(u),1),d=new U(new Float32Array(3*l),3),f=new U(new Float32Array(2*l),2),m=0,g=0,v=(1/(e.length-1),1/n),y=new s,x=new i;for(h=0;h<=n;h++){var b=r+h*v*a,_=Math.sin(b),w=Math.cos(b);for(c=0;c<=e.length-1;c++)y.x=e[c].x*_,y.y=e[c].y,y.z=e[c].x*w,d.setXYZ(m,y.x,y.y,y.z),x.x=h/n,x.y=c/(e.length-1),f.setXY(m,x.x,x.y),m++}for(h=0;h>=4,i[r]=e[19===r?3&t|8:t]);return i.join("")}}(),clamp:function(t,e,i){return Math.max(e,Math.min(i,t))},euclideanModulo:function(t,e){return(t%e+e)%e},mapLinear:function(t,e,i,n,r){return n+(t-e)*(r-n)/(i-e)},smoothstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*(3-2*t))},smootherstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*t*(t*(6*t-15)+10))},random16:function(){return console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead."),Math.random()},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},degToRad:function(e){return e*t.Math.DEG2RAD},radToDeg:function(e){return e*t.Math.RAD2DEG},isPowerOfTwo:function(t){return 0===(t&t-1)&&0!==t},nearestPowerOfTwo:function(t){return Math.pow(2,Math.round(Math.log(t)/Math.LN2))},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}},i.prototype={constructor:i,get width(){return this.x},set width(t){this.x=t},get height(){return this.y},set height(t){this.y=t},set:function(t,e){return this.x=t,this.y=e,this},setScalar:function(t){return this.x=t,this.y=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(t){return this.x=t.x,this.y=t.y,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)},addScalar:function(t){return this.x+=t,this.y+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)},subScalar:function(t){return this.x-=t,this.y-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t):(this.x=0,this.y=0),this},divide:function(t){return this.x/=t.x,this.y/=t.y,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this},clampScalar:function(){var t,e;return function(n,r){return void 0===t&&(t=new i,e=new i),t.set(n,n),e.set(r,r),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(t){return this.x*t.x+this.y*t.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var t=Math.atan2(this.y,this.x);return t<0&&(t+=2*Math.PI),t},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y;return e*e+i*i},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},equals:function(t){return t.x===this.x&&t.y===this.y},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this},rotateAround:function(t,e){var i=Math.cos(e),n=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*i-a*n+t.x,this.y=r*n+a*i+t.y,this}},n.DEFAULT_IMAGE=void 0,n.DEFAULT_MAPPING=cr,n.prototype={constructor:n,set needsUpdate(t){t===!0&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.encoding=t.encoding,this},toJSON:function(e){function i(t){var e;return void 0!==t.toDataURL?e=t:(e=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0,t.width,t.height)),e.width>2048||e.height>2048?e.toDataURL("image/jpeg",.6):e.toDataURL("image/png")}if(void 0!==e.textures[this.uuid])return e.textures[this.uuid];var n={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var r=this.image;void 0===r.uuid&&(r.uuid=t.Math.generateUUID()),void 0===e.images[r.uuid]&&(e.images[r.uuid]={uuid:r.uuid,url:i(r)}),n.image=r.uuid}return e.textures[this.uuid]=n,n},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(t){if(this.mapping===cr){if(t.multiply(this.repeat),t.add(this.offset),t.x<0||t.x>1)switch(this.wrapS){case vr:t.x=t.x-Math.floor(t.x);break;case yr:t.x=t.x<0?0:1;break;case xr:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case vr:t.y=t.y-Math.floor(t.y);break;case yr:t.y=t.y<0?0:1;break;case xr:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}this.flipY&&(t.y=1-t.y)}}},Object.assign(n.prototype,e.prototype);var _a=0;a.prototype={constructor:a,set:function(t,e,i,n,r,a,o,s,h,c,l,u,p,d,f,m){var g=this.elements;return g[0]=t,g[4]=e,g[8]=i,g[12]=n,g[1]=r,g[5]=a,g[9]=o,g[13]=s,g[2]=h,g[6]=c,g[10]=l,g[14]=u,g[3]=p,g[7]=d,g[11]=f,g[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},clone:function(){return(new a).fromArray(this.elements)},copy:function(t){return this.elements.set(t.elements),this},copyPosition:function(t){var e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this},extractBasis:function(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this},makeBasis:function(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this},extractRotation:function(){var t;return function(e){void 0===t&&(t=new s);var i=this.elements,n=e.elements,r=1/t.setFromMatrixColumn(e,0).length(),a=1/t.setFromMatrixColumn(e,1).length(),o=1/t.setFromMatrixColumn(e,2).length();return i[0]=n[0]*r,i[1]=n[1]*r,i[2]=n[2]*r,i[4]=n[4]*a,i[5]=n[5]*a,i[6]=n[6]*a,i[8]=n[8]*o,i[9]=n[9]*o,i[10]=n[10]*o,this}}(),makeRotationFromEuler:function(t){(t&&t.isEuler)===!1&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var e=this.elements,i=t.x,n=t.y,r=t.z,a=Math.cos(i),o=Math.sin(i),s=Math.cos(n),h=Math.sin(n),c=Math.cos(r),l=Math.sin(r);if("XYZ"===t.order){var u=a*c,p=a*l,d=o*c,f=o*l;e[0]=s*c,e[4]=-s*l,e[8]=h,e[1]=p+d*h,e[5]=u-f*h,e[9]=-o*s,e[2]=f-u*h,e[6]=d+p*h,e[10]=a*s}else if("YXZ"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m+y*o,e[4]=v*o-g,e[8]=a*h,e[1]=a*l,e[5]=a*c,e[9]=-o,e[2]=g*o-v,e[6]=y+m*o,e[10]=a*s}else if("ZXY"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m-y*o,e[4]=-a*l,e[8]=v+g*o,e[1]=g+v*o,e[5]=a*c,e[9]=y-m*o,e[2]=-a*h,e[6]=o,e[10]=a*s}else if("ZYX"===t.order){var u=a*c,p=a*l,d=o*c,f=o*l;e[0]=s*c,e[4]=d*h-p,e[8]=u*h+f,e[1]=s*l,e[5]=f*h+u,e[9]=p*h-d,e[2]=-h,e[6]=o*s,e[10]=a*s}else if("YZX"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=w-x*l,e[8]=_*l+b,e[1]=l,e[5]=a*c,e[9]=-o*c,e[2]=-h*c,e[6]=b*l+_,e[10]=x-w*l}else if("XZY"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=-l,e[8]=h*c,e[1]=x*l+w,e[5]=a*c,e[9]=b*l-_,e[2]=_*l-b,e[6]=o*c,e[10]=w*l+x}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},makeRotationFromQuaternion:function(t){var e=this.elements,i=t.x,n=t.y,r=t.z,a=t.w,o=i+i,s=n+n,h=r+r,c=i*o,l=i*s,u=i*h,p=n*s,d=n*h,f=r*h,m=a*o,g=a*s,v=a*h;return e[0]=1-(p+f),e[4]=l-v,e[8]=u+g,e[1]=l+v,e[5]=1-(c+f),e[9]=d-m,e[2]=u-g,e[6]=d+m,e[10]=1-(c+p),e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},lookAt:function(){var t,e,i;return function(n,r,a){void 0===t&&(t=new s,e=new s,i=new s);var o=this.elements;return i.subVectors(n,r).normalize(),0===i.lengthSq()&&(i.z=1),t.crossVectors(a,i).normalize(),0===t.lengthSq()&&(i.z+=1e-4,t.crossVectors(a,i).normalize()),e.crossVectors(i,t),o[0]=t.x,o[4]=e.x,o[8]=i.x,o[1]=t.y,o[5]=e.y,o[9]=i.y,o[2]=t.z,o[6]=e.z,o[10]=i.z,this}}(),multiply:function(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)},premultiply:function(t){return this.multiplyMatrices(t,this)},multiplyMatrices:function(t,e){var i=t.elements,n=e.elements,r=this.elements,a=i[0],o=i[4],s=i[8],h=i[12],c=i[1],l=i[5],u=i[9],p=i[13],d=i[2],f=i[6],m=i[10],g=i[14],v=i[3],y=i[7],x=i[11],b=i[15],_=n[0],w=n[4],M=n[8],E=n[12],T=n[1],S=n[5],A=n[9],L=n[13],R=n[2],P=n[6],C=n[10],U=n[14],I=n[3],D=n[7],N=n[11],O=n[15];return r[0]=a*_+o*T+s*R+h*I,r[4]=a*w+o*S+s*P+h*D,r[8]=a*M+o*A+s*C+h*N,r[12]=a*E+o*L+s*U+h*O,r[1]=c*_+l*T+u*R+p*I,r[5]=c*w+l*S+u*P+p*D,r[9]=c*M+l*A+u*C+p*N,r[13]=c*E+l*L+u*U+p*O,r[2]=d*_+f*T+m*R+g*I,r[6]=d*w+f*S+m*P+g*D,r[10]=d*M+f*A+m*C+g*N,r[14]=d*E+f*L+m*U+g*O,r[3]=v*_+y*T+x*R+b*I,r[7]=v*w+y*S+x*P+b*D,r[11]=v*M+y*A+x*C+b*N,r[15]=v*E+y*L+x*U+b*O,this},multiplyToArray:function(t,e,i){var n=this.elements;return this.multiplyMatrices(t,e),i[0]=n[0],i[1]=n[1],i[2]=n[2],i[3]=n[3],i[4]=n[4],i[5]=n[5],i[6]=n[6],i[7]=n[7],i[8]=n[8],i[9]=n[9],i[10]=n[10],i[11]=n[11],i[12]=n[12],i[13]=n[13],i[14]=n[14],i[15]=n[15],this},multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r0?(e=.5/Math.sqrt(p+1),this._w=.25/e,this._x=(l-h)*e,this._y=(a-c)*e,this._z=(o-r)*e):n>s&&n>u?(e=2*Math.sqrt(1+n-s-u),this._w=(l-h)/e,this._x=.25*e,this._y=(r+o)/e,this._z=(a+c)/e):s>u?(e=2*Math.sqrt(1+s-n-u),this._w=(a-c)/e,this._x=(r+o)/e,this._y=.25*e,this._z=(h+l)/e):(e=2*Math.sqrt(1+u-n-s),this._w=(o-r)/e,this._x=(a+c)/e,this._y=(h+l)/e,this._z=.25*e),this.onChangeCallback(),this},setFromUnitVectors:function(){var t,e,i=1e-6;return function(n,r){return void 0===t&&(t=new s),e=n.dot(r)+1,eMath.abs(n.z)?t.set(-n.y,n.x,0):t.set(0,-n.z,n.y)):t.crossVectors(n,r),this._x=t.x,this._y=t.y,this._z=t.z,this._w=e,this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this.onChangeCallback(),this},dot:function(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this.onChangeCallback(),this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)},premultiply:function(t){return this.multiplyQuaternions(t,this)},multiplyQuaternions:function(t,e){var i=t._x,n=t._y,r=t._z,a=t._w,o=e._x,s=e._y,h=e._z,c=e._w;return this._x=i*c+a*o+n*h-r*s,this._y=n*c+a*s+r*o-i*h,this._z=r*c+a*h+i*s-n*o,this._w=a*c-i*o-n*s-r*h,this.onChangeCallback(),this},slerp:function(t,e){if(0===e)return this;if(1===e)return this.copy(t);var i=this._x,n=this._y,r=this._z,a=this._w,o=a*t._w+i*t._x+n*t._y+r*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=a,this._x=i,this._y=n,this._z=r,this;var s=Math.sqrt(1-o*o);if(Math.abs(s)<.001)return this._w=.5*(a+this._w),this._x=.5*(i+this._x),this._y=.5*(n+this._y),this._z=.5*(r+this._z),this;var h=Math.atan2(s,o),c=Math.sin((1-e)*h)/s,l=Math.sin(e*h)/s;return this._w=a*c+this._w*l,this._x=i*c+this._x*l,this._y=n*c+this._y*l,this._z=r*c+this._z*l,this.onChangeCallback(),this},equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w},fromArray:function(t,e){return void 0===e&&(e=0),this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this.onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t},onChange:function(t){return this.onChangeCallback=t,this},onChangeCallback:function(){}},Object.assign(o,{slerp:function(t,e,i,n){return i.copy(t).slerp(e,n)},slerpFlat:function(t,e,i,n,r,a,o){var s=i[n+0],h=i[n+1],c=i[n+2],l=i[n+3],u=r[a+0],p=r[a+1],d=r[a+2],f=r[a+3];if(l!==f||s!==u||h!==p||c!==d){var m=1-o,g=s*u+h*p+c*d+l*f,v=g>=0?1:-1,y=1-g*g;if(y>Number.EPSILON){var x=Math.sqrt(y),b=Math.atan2(x,g*v);m=Math.sin(m*b)/x,o=Math.sin(o*b)/x}var _=o*v;if(s=s*m+u*_,h=h*m+p*_,c=c*m+d*_,l=l*m+f*_,m===1-o){var w=1/Math.sqrt(s*s+h*h+c*c+l*l);s*=w,h*=w,c*=w,l*=w}}t[e]=s,t[e+1]=h,t[e+2]=c,t[e+3]=l}}),s.prototype={constructor:s,set:function(t,e,i){return this.x=t,this.y=e,this.z=i,this},setScalar:function(t){return this.x=t,this.y=t,this.z=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x,this.y*=t.y,this.z*=t.z,this)},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t,this.z*=t):(this.x=0,this.y=0,this.z=0),this},multiplyVectors:function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},applyEuler:function(){var t;return function(e){return(e&&e.isEuler)===!1&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),void 0===t&&(t=new o),this.applyQuaternion(t.setFromEuler(e))}}(),applyAxisAngle:function(){var t;return function(e,i){return void 0===t&&(t=new o),this.applyQuaternion(t.setFromAxisAngle(e,i)); -}}(),applyMatrix3:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[3]*i+r[6]*n,this.y=r[1]*e+r[4]*i+r[7]*n,this.z=r[2]*e+r[5]*i+r[8]*n,this},applyMatrix4:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12],this.y=r[1]*e+r[5]*i+r[9]*n+r[13],this.z=r[2]*e+r[6]*i+r[10]*n+r[14],this},applyProjection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements,a=1/(r[3]*e+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*n+r[12])*a,this.y=(r[1]*e+r[5]*i+r[9]*n+r[13])*a,this.z=(r[2]*e+r[6]*i+r[10]*n+r[14])*a,this},applyQuaternion:function(t){var e=this.x,i=this.y,n=this.z,r=t.x,a=t.y,o=t.z,s=t.w,h=s*e+a*n-o*i,c=s*i+o*e-r*n,l=s*n+r*i-a*e,u=-r*e-a*i-o*n;return this.x=h*s+u*-r+c*-o-l*-a,this.y=c*s+u*-a+l*-r-h*-o,this.z=l*s+u*-o+h*-a-c*-r,this},project:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.projectionMatrix,t.getInverse(e.matrixWorld)),this.applyProjection(t)}}(),unproject:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.matrixWorld,t.getInverse(e.projectionMatrix)),this.applyProjection(t)}}(),transformDirection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n,this.y=r[1]*e+r[5]*i+r[9]*n,this.z=r[2]*e+r[6]*i+r[10]*n,this.normalize()},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this},clampScalar:function(){var t,e;return function(i,n){return void 0===t&&(t=new s,e=new s),t.set(i,i,i),e.set(n,n,n),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},cross:function(t,e){if(void 0!==e)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e);var i=this.x,n=this.y,r=this.z;return this.x=n*t.z-r*t.y,this.y=r*t.x-i*t.z,this.z=i*t.y-n*t.x,this},crossVectors:function(t,e){var i=t.x,n=t.y,r=t.z,a=e.x,o=e.y,s=e.z;return this.x=n*s-r*o,this.y=r*a-i*s,this.z=i*o-n*a,this},projectOnVector:function(t){var e=t.dot(this)/t.lengthSq();return this.copy(t).multiplyScalar(e)},projectOnPlane:function(){var t;return function(e){return void 0===t&&(t=new s),t.copy(this).projectOnVector(e),this.sub(t)}}(),reflect:function(){var t;return function(e){return void 0===t&&(t=new s),this.sub(t.copy(e).multiplyScalar(2*this.dot(e)))}}(),angleTo:function(e){var i=this.dot(e)/Math.sqrt(this.lengthSq()*e.lengthSq());return Math.acos(t.Math.clamp(i,-1,1))},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)},setFromSpherical:function(t){var e=Math.sin(t.phi)*t.radius;return this.x=e*Math.sin(t.theta),this.y=Math.cos(t.phi)*t.radius,this.z=e*Math.cos(t.theta),this},setFromMatrixPosition:function(t){return this.setFromMatrixColumn(t,3)},setFromMatrixScale:function(t){var e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=n,this},setFromMatrixColumn:function(t,e){if("number"==typeof t){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var i=t;t=e,e=i}return this.fromArray(t.elements,4*e)},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this.z=t.array[e+2],this}},c.prototype={constructor:c,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y},getParameter:function(t,e){var n=e||new i;return n.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)},clampPoint:function(t,e){var n=e||new i;return n.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new i;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},u.prototype=Object.create(n.prototype),u.prototype.constructor=u,Object.defineProperty(u.prototype,"images",{get:function(){return this.image},set:function(t){this.image=t}}),t.WebGLUniforms=function(){var t=new n,e=new u,i=function(){this.seq=[],this.map={}},r=[],a=[],o=function(t,e,i){var n=t[0];if(n<=0||n>0)return t;var a=e*i,o=r[a];if(void 0===o&&(o=new Float32Array(a),r[a]=o),0!==e){n.toArray(o,0);for(var s=1,h=0;s!==e;++s)h+=i,t[s].toArray(o,h)}return o},s=function(t,e){var i=a[e];void 0===i&&(i=new Int32Array(e),a[e]=i);for(var n=0;n!==e;++n)i[n]=t.allocTextureUnit();return i},h=function(t,e){t.uniform1f(this.addr,e)},c=function(t,e){t.uniform1i(this.addr,e)},l=function(t,e){void 0===e.x?t.uniform2fv(this.addr,e):t.uniform2f(this.addr,e.x,e.y)},p=function(t,e){void 0!==e.x?t.uniform3f(this.addr,e.x,e.y,e.z):void 0!==e.r?t.uniform3f(this.addr,e.r,e.g,e.b):t.uniform3fv(this.addr,e)},d=function(t,e){void 0===e.x?t.uniform4fv(this.addr,e):t.uniform4f(this.addr,e.x,e.y,e.z,e.w)},f=function(t,e){t.uniformMatrix2fv(this.addr,!1,e.elements||e)},m=function(t,e){t.uniformMatrix3fv(this.addr,!1,e.elements||e)},g=function(t,e){t.uniformMatrix4fv(this.addr,!1,e.elements||e)},v=function(e,i,n){var r=n.allocTextureUnit();e.uniform1i(this.addr,r),n.setTexture2D(i||t,r)},y=function(t,i,n){var r=n.allocTextureUnit();t.uniform1i(this.addr,r),n.setTextureCube(i||e,r)},x=function(t,e){t.uniform2iv(this.addr,e)},b=function(t,e){t.uniform3iv(this.addr,e)},_=function(t,e){t.uniform4iv(this.addr,e)},w=function(t){switch(t){case 5126:return h;case 35664:return l;case 35665:return p;case 35666:return d;case 35674:return f;case 35675:return m;case 35676:return g;case 35678:return v;case 35680:return y;case 5124:case 35670:return c;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},M=function(t,e){t.uniform1fv(this.addr,e)},E=function(t,e){t.uniform1iv(this.addr,e)},T=function(t,e){t.uniform2fv(this.addr,o(e,this.size,2))},S=function(t,e){t.uniform3fv(this.addr,o(e,this.size,3))},A=function(t,e){t.uniform4fv(this.addr,o(e,this.size,4))},L=function(t,e){t.uniformMatrix2fv(this.addr,!1,o(e,this.size,4))},R=function(t,e){t.uniformMatrix3fv(this.addr,!1,o(e,this.size,9))},P=function(t,e){t.uniformMatrix4fv(this.addr,!1,o(e,this.size,16))},C=function(e,i,n){var r=i.length,a=s(n,r);e.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTexture2D(i[o]||t,a[o])},U=function(t,i,n){var r=i.length,a=s(n,r);t.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTextureCube(i[o]||e,a[o])},I=function(t){switch(t){case 5126:return M;case 35664:return T;case 35665:return S;case 35666:return A;case 35674:return L;case 35675:return R;case 35676:return P;case 35678:return C;case 35680:return U;case 5124:case 35670:return E;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},D=function(t,e,i){this.id=t,this.addr=i,this.setValue=w(e.type)},N=function(t,e,i){this.id=t,this.addr=i,this.size=e.size,this.setValue=I(e.type)},O=function(t){this.id=t,i.call(this)};O.prototype.setValue=function(t,e){for(var i=this.seq,n=0,r=i.length;n!==r;++n){var a=i[n];a.setValue(t,e[a.id])}};var F=/([\w\d_]+)(\])?(\[|\.)?/g,B=function(t,e){t.seq.push(e),t.map[e.id]=e},z=function(t,e,i){var n=t.name,r=n.length;for(F.lastIndex=0;;){var a=F.exec(n),o=F.lastIndex,s=a[1],h="]"===a[2],c=a[3];if(h&&(s=0|s),void 0===c||"["===c&&o+2===r){B(i,void 0===c?new D(s,t,e):new N(s,t,e));break}var l=i.map,u=l[s];void 0===u&&(u=new O(s),B(i,u)),i=u}},G=function(t,e,n){i.call(this),this.renderer=n;for(var r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),a=0;a!==r;++a){var o=t.getActiveUniform(e,a),s=o.name,h=t.getUniformLocation(e,s);z(o,h,this)}};return G.prototype.setValue=function(t,e,i){var n=this.map[e];void 0!==n&&n.setValue(t,i,this.renderer)},G.prototype.set=function(t,e,i){var n=this.map[i];void 0!==n&&n.setValue(t,e[i],this.renderer)},G.prototype.setOptional=function(t,e,i){var n=e[i];void 0!==n&&this.setValue(t,i,n)},G.upload=function(t,e,i,n){for(var r=0,a=e.length;r!==a;++r){var o=e[r],s=i[o.id];s.needsUpdate!==!1&&o.setValue(t,s.value,n)}},G.seqWithValue=function(t,e){for(var i=[],n=0,r=t.length;n!==r;++n){var a=t[n];a.id in e&&i.push(a)}return i},G.splitDynamic=function(t,e){for(var i=null,n=t.length,r=0,a=0;a!==n;++a){var o=t[a],s=e[o.id];s&&s.dynamic===!0?(null===i&&(i=[]),i.push(o)):(ry&&v>x?vx?y0&&(n.alphaTest=this.alphaTest),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=this.premultipliedAlpha),this.wireframe===!0&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),i){var r=e(t.textures),a=e(t.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n},clone:function(){return(new this.constructor).copy(this)},copy:function(t){this.name=t.name,this.fog=t.fog,this.lights=t.lights,this.blending=t.blending,this.side=t.side,this.shading=t.shading,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.alphaTest=t.alphaTest,this.premultipliedAlpha=t.premultipliedAlpha,this.overdraw=t.overdraw,this.visible=t.visible,this.clipShadows=t.clipShadows;var e=t.clippingPlanes,i=null;if(null!==e){var n=e.length;i=new Array(n);for(var r=0;r!==n;++r)i[r]=e[r].clone()}return this.clippingPlanes=i,this},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}},Object.assign(x.prototype,e.prototype);var wa=0;t.UniformsUtils={merge:function(t){for(var e={},i=0;i65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=t,b=(e-t)/r,_=new s,w=new i;for(c=0;c<=r;c++){for(l=0;l<=n;l++)h=a+l/n*o,_.x=x*Math.cos(h),_.y=x*Math.sin(h),f.setXYZ(v,_.x,_.y,_.z),m.setXYZ(v,0,0,1),w.x=(_.x/e+1)/2,w.y=(_.y/e+1)/2,g.setXY(v,w.x,w.y),v++;x+=b}for(c=0;c65535?Uint32Array:Uint16Array)(u),1),d=new U(new Float32Array(3*l),3),f=new U(new Float32Array(2*l),2),m=0,g=0,v=(1/(e.length-1),1/n),y=new s,x=new i;for(h=0;h<=n;h++){var b=r+h*v*a,_=Math.sin(b),w=Math.cos(b);for(c=0;c<=e.length-1;c++)y.x=e[c].x*_,y.y=e[c].y,y.z=e[c].x*w,d.setXYZ(m,y.x,y.y,y.z),x.x=h/n,x.y=c/(e.length-1),f.setXY(m,x.x,x.y),m++}for(h=0;h0?1:+t}),void 0===Function.prototype.name&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]}}),void 0===Object.assign&&!function(){Object.assign=function(t){if(void 0===t||null===t)throw new TypeError("Cannot convert undefined or null to object");for(var e=Object(t),i=1;i>=4,i[r]=e[19===r?3&t|8:t]);return i.join("")}}(),clamp:function(t,e,i){return Math.max(e,Math.min(i,t))},euclideanModulo:function(t,e){return(t%e+e)%e},mapLinear:function(t,e,i,n,r){return n+(t-e)*(r-n)/(i-e)},smoothstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*(3-2*t))},smootherstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*t*(t*(6*t-15)+10))},random16:function(){return console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead."),Math.random()},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},degToRad:function(e){return e*t.Math.DEG2RAD},radToDeg:function(e){return e*t.Math.RAD2DEG},isPowerOfTwo:function(t){return 0===(t&t-1)&&0!==t},nearestPowerOfTwo:function(t){return Math.pow(2,Math.round(Math.log(t)/Math.LN2))},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}},i.prototype={constructor:i,get width(){return this.x},set width(t){this.x=t},get height(){return this.y},set height(t){this.y=t},set:function(t,e){return this.x=t,this.y=e,this},setScalar:function(t){return this.x=t,this.y=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(t){return this.x=t.x,this.y=t.y,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)},addScalar:function(t){return this.x+=t,this.y+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)},subScalar:function(t){return this.x-=t,this.y-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t):(this.x=0,this.y=0),this},divide:function(t){return this.x/=t.x,this.y/=t.y,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this},clampScalar:function(){var t,e;return function(n,r){return void 0===t&&(t=new i,e=new i),t.set(n,n),e.set(r,r),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(t){return this.x*t.x+this.y*t.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var t=Math.atan2(this.y,this.x);return t<0&&(t+=2*Math.PI),t},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y;return e*e+i*i},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},equals:function(t){return t.x===this.x&&t.y===this.y},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this},rotateAround:function(t,e){var i=Math.cos(e),n=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*i-a*n+t.x,this.y=r*n+a*i+t.y,this}},n.DEFAULT_IMAGE=void 0,n.DEFAULT_MAPPING=cr,n.prototype={constructor:n,set needsUpdate(t){t===!0&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.encoding=t.encoding,this},toJSON:function(e){function i(t){var e;return void 0!==t.toDataURL?e=t:(e=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0,t.width,t.height)),e.width>2048||e.height>2048?e.toDataURL("image/jpeg",.6):e.toDataURL("image/png")}if(void 0!==e.textures[this.uuid])return e.textures[this.uuid];var n={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var r=this.image;void 0===r.uuid&&(r.uuid=t.Math.generateUUID()),void 0===e.images[r.uuid]&&(e.images[r.uuid]={uuid:r.uuid,url:i(r)}),n.image=r.uuid}return e.textures[this.uuid]=n,n},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(t){if(this.mapping===cr){if(t.multiply(this.repeat),t.add(this.offset),t.x<0||t.x>1)switch(this.wrapS){case vr:t.x=t.x-Math.floor(t.x);break;case yr:t.x=t.x<0?0:1;break;case xr:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case vr:t.y=t.y-Math.floor(t.y);break;case yr:t.y=t.y<0?0:1;break;case xr:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}this.flipY&&(t.y=1-t.y)}}},Object.assign(n.prototype,e.prototype);var _a=0;a.prototype={constructor:a,set:function(t,e,i,n,r,a,o,s,h,c,l,u,p,d,f,m){var g=this.elements;return g[0]=t,g[4]=e,g[8]=i,g[12]=n,g[1]=r,g[5]=a,g[9]=o,g[13]=s,g[2]=h,g[6]=c,g[10]=l,g[14]=u,g[3]=p,g[7]=d,g[11]=f,g[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},clone:function(){return(new a).fromArray(this.elements)},copy:function(t){return this.elements.set(t.elements),this},copyPosition:function(t){var e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this},extractBasis:function(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this},makeBasis:function(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this},extractRotation:function(){var t;return function(e){void 0===t&&(t=new s);var i=this.elements,n=e.elements,r=1/t.setFromMatrixColumn(e,0).length(),a=1/t.setFromMatrixColumn(e,1).length(),o=1/t.setFromMatrixColumn(e,2).length();return i[0]=n[0]*r,i[1]=n[1]*r,i[2]=n[2]*r,i[4]=n[4]*a,i[5]=n[5]*a,i[6]=n[6]*a,i[8]=n[8]*o,i[9]=n[9]*o,i[10]=n[10]*o,this}}(),makeRotationFromEuler:function(t){(t&&t.isEuler)===!1&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var e=this.elements,i=t.x,n=t.y,r=t.z,a=Math.cos(i),o=Math.sin(i),s=Math.cos(n),h=Math.sin(n),c=Math.cos(r),l=Math.sin(r);if("XYZ"===t.order){var u=a*c,p=a*l,d=o*c,f=o*l;e[0]=s*c,e[4]=-s*l,e[8]=h,e[1]=p+d*h,e[5]=u-f*h,e[9]=-o*s,e[2]=f-u*h,e[6]=d+p*h,e[10]=a*s}else if("YXZ"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m+y*o,e[4]=v*o-g,e[8]=a*h,e[1]=a*l,e[5]=a*c,e[9]=-o,e[2]=g*o-v,e[6]=y+m*o,e[10]=a*s}else if("ZXY"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m-y*o,e[4]=-a*l,e[8]=v+g*o,e[1]=g+v*o,e[5]=a*c,e[9]=y-m*o,e[2]=-a*h,e[6]=o,e[10]=a*s}else if("ZYX"===t.order){var u=a*c,p=a*l,d=o*c,f=o*l;e[0]=s*c,e[4]=d*h-p,e[8]=u*h+f,e[1]=s*l,e[5]=f*h+u,e[9]=p*h-d,e[2]=-h,e[6]=o*s,e[10]=a*s}else if("YZX"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=w-x*l,e[8]=_*l+b,e[1]=l,e[5]=a*c,e[9]=-o*c,e[2]=-h*c,e[6]=b*l+_,e[10]=x-w*l}else if("XZY"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=-l,e[8]=h*c,e[1]=x*l+w,e[5]=a*c,e[9]=b*l-_,e[2]=_*l-b,e[6]=o*c,e[10]=w*l+x}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},makeRotationFromQuaternion:function(t){var e=this.elements,i=t.x,n=t.y,r=t.z,a=t.w,o=i+i,s=n+n,h=r+r,c=i*o,l=i*s,u=i*h,p=n*s,d=n*h,f=r*h,m=a*o,g=a*s,v=a*h;return e[0]=1-(p+f),e[4]=l-v,e[8]=u+g,e[1]=l+v,e[5]=1-(c+f),e[9]=d-m,e[2]=u-g,e[6]=d+m,e[10]=1-(c+p),e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},lookAt:function(){var t,e,i;return function(n,r,a){void 0===t&&(t=new s,e=new s,i=new s);var o=this.elements;return i.subVectors(n,r).normalize(),0===i.lengthSq()&&(i.z=1),t.crossVectors(a,i).normalize(),0===t.lengthSq()&&(i.z+=1e-4,t.crossVectors(a,i).normalize()),e.crossVectors(i,t),o[0]=t.x,o[4]=e.x,o[8]=i.x,o[1]=t.y,o[5]=e.y,o[9]=i.y,o[2]=t.z,o[6]=e.z,o[10]=i.z,this}}(),multiply:function(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)},premultiply:function(t){return this.multiplyMatrices(t,this)},multiplyMatrices:function(t,e){var i=t.elements,n=e.elements,r=this.elements,a=i[0],o=i[4],s=i[8],h=i[12],c=i[1],l=i[5],u=i[9],p=i[13],d=i[2],f=i[6],m=i[10],g=i[14],v=i[3],y=i[7],x=i[11],b=i[15],_=n[0],w=n[4],M=n[8],E=n[12],T=n[1],S=n[5],A=n[9],L=n[13],R=n[2],P=n[6],C=n[10],U=n[14],I=n[3],D=n[7],N=n[11],O=n[15];return r[0]=a*_+o*T+s*R+h*I,r[4]=a*w+o*S+s*P+h*D,r[8]=a*M+o*A+s*C+h*N,r[12]=a*E+o*L+s*U+h*O,r[1]=c*_+l*T+u*R+p*I,r[5]=c*w+l*S+u*P+p*D,r[9]=c*M+l*A+u*C+p*N,r[13]=c*E+l*L+u*U+p*O,r[2]=d*_+f*T+m*R+g*I,r[6]=d*w+f*S+m*P+g*D,r[10]=d*M+f*A+m*C+g*N,r[14]=d*E+f*L+m*U+g*O,r[3]=v*_+y*T+x*R+b*I,r[7]=v*w+y*S+x*P+b*D,r[11]=v*M+y*A+x*C+b*N,r[15]=v*E+y*L+x*U+b*O,this},multiplyToArray:function(t,e,i){var n=this.elements;return this.multiplyMatrices(t,e),i[0]=n[0],i[1]=n[1],i[2]=n[2],i[3]=n[3],i[4]=n[4],i[5]=n[5],i[6]=n[6],i[7]=n[7],i[8]=n[8],i[9]=n[9],i[10]=n[10],i[11]=n[11],i[12]=n[12],i[13]=n[13],i[14]=n[14],i[15]=n[15],this},multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r0?(e=.5/Math.sqrt(p+1),this._w=.25/e,this._x=(l-h)*e,this._y=(a-c)*e,this._z=(o-r)*e):n>s&&n>u?(e=2*Math.sqrt(1+n-s-u),this._w=(l-h)/e,this._x=.25*e,this._y=(r+o)/e,this._z=(a+c)/e):s>u?(e=2*Math.sqrt(1+s-n-u),this._w=(a-c)/e,this._x=(r+o)/e,this._y=.25*e,this._z=(h+l)/e):(e=2*Math.sqrt(1+u-n-s),this._w=(o-r)/e,this._x=(a+c)/e,this._y=(h+l)/e,this._z=.25*e),this.onChangeCallback(),this},setFromUnitVectors:function(){var t,e,i=1e-6;return function(n,r){return void 0===t&&(t=new s),e=n.dot(r)+1,eMath.abs(n.z)?t.set(-n.y,n.x,0):t.set(0,-n.z,n.y)):t.crossVectors(n,r),this._x=t.x,this._y=t.y,this._z=t.z,this._w=e,this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this.onChangeCallback(),this},dot:function(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this.onChangeCallback(),this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)},premultiply:function(t){return this.multiplyQuaternions(t,this)},multiplyQuaternions:function(t,e){var i=t._x,n=t._y,r=t._z,a=t._w,o=e._x,s=e._y,h=e._z,c=e._w;return this._x=i*c+a*o+n*h-r*s,this._y=n*c+a*s+r*o-i*h,this._z=r*c+a*h+i*s-n*o,this._w=a*c-i*o-n*s-r*h,this.onChangeCallback(),this},slerp:function(t,e){if(0===e)return this;if(1===e)return this.copy(t);var i=this._x,n=this._y,r=this._z,a=this._w,o=a*t._w+i*t._x+n*t._y+r*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=a,this._x=i,this._y=n,this._z=r,this;var s=Math.sqrt(1-o*o);if(Math.abs(s)<.001)return this._w=.5*(a+this._w),this._x=.5*(i+this._x),this._y=.5*(n+this._y),this._z=.5*(r+this._z),this;var h=Math.atan2(s,o),c=Math.sin((1-e)*h)/s,l=Math.sin(e*h)/s;return this._w=a*c+this._w*l,this._x=i*c+this._x*l,this._y=n*c+this._y*l,this._z=r*c+this._z*l,this.onChangeCallback(),this},equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w},fromArray:function(t,e){return void 0===e&&(e=0),this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this.onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t},onChange:function(t){return this.onChangeCallback=t,this},onChangeCallback:function(){}},Object.assign(o,{slerp:function(t,e,i,n){return i.copy(t).slerp(e,n)},slerpFlat:function(t,e,i,n,r,a,o){var s=i[n+0],h=i[n+1],c=i[n+2],l=i[n+3],u=r[a+0],p=r[a+1],d=r[a+2],f=r[a+3];if(l!==f||s!==u||h!==p||c!==d){var m=1-o,g=s*u+h*p+c*d+l*f,v=g>=0?1:-1,y=1-g*g;if(y>Number.EPSILON){var x=Math.sqrt(y),b=Math.atan2(x,g*v);m=Math.sin(m*b)/x,o=Math.sin(o*b)/x}var _=o*v;if(s=s*m+u*_,h=h*m+p*_,c=c*m+d*_,l=l*m+f*_,m===1-o){var w=1/Math.sqrt(s*s+h*h+c*c+l*l);s*=w,h*=w,c*=w,l*=w}}t[e]=s,t[e+1]=h,t[e+2]=c,t[e+3]=l}}),s.prototype={constructor:s,set:function(t,e,i){return this.x=t,this.y=e,this.z=i,this},setScalar:function(t){return this.x=t,this.y=t,this.z=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x, +this.y*=t.y,this.z*=t.z,this)},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t,this.z*=t):(this.x=0,this.y=0,this.z=0),this},multiplyVectors:function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},applyEuler:function(){var t;return function(e){return(e&&e.isEuler)===!1&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),void 0===t&&(t=new o),this.applyQuaternion(t.setFromEuler(e))}}(),applyAxisAngle:function(){var t;return function(e,i){return void 0===t&&(t=new o),this.applyQuaternion(t.setFromAxisAngle(e,i))}}(),applyMatrix3:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[3]*i+r[6]*n,this.y=r[1]*e+r[4]*i+r[7]*n,this.z=r[2]*e+r[5]*i+r[8]*n,this},applyMatrix4:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12],this.y=r[1]*e+r[5]*i+r[9]*n+r[13],this.z=r[2]*e+r[6]*i+r[10]*n+r[14],this},applyProjection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements,a=1/(r[3]*e+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*n+r[12])*a,this.y=(r[1]*e+r[5]*i+r[9]*n+r[13])*a,this.z=(r[2]*e+r[6]*i+r[10]*n+r[14])*a,this},applyQuaternion:function(t){var e=this.x,i=this.y,n=this.z,r=t.x,a=t.y,o=t.z,s=t.w,h=s*e+a*n-o*i,c=s*i+o*e-r*n,l=s*n+r*i-a*e,u=-r*e-a*i-o*n;return this.x=h*s+u*-r+c*-o-l*-a,this.y=c*s+u*-a+l*-r-h*-o,this.z=l*s+u*-o+h*-a-c*-r,this},project:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.projectionMatrix,t.getInverse(e.matrixWorld)),this.applyProjection(t)}}(),unproject:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.matrixWorld,t.getInverse(e.projectionMatrix)),this.applyProjection(t)}}(),transformDirection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n,this.y=r[1]*e+r[5]*i+r[9]*n,this.z=r[2]*e+r[6]*i+r[10]*n,this.normalize()},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this},clampScalar:function(){var t,e;return function(i,n){return void 0===t&&(t=new s,e=new s),t.set(i,i,i),e.set(n,n,n),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},cross:function(t,e){if(void 0!==e)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e);var i=this.x,n=this.y,r=this.z;return this.x=n*t.z-r*t.y,this.y=r*t.x-i*t.z,this.z=i*t.y-n*t.x,this},crossVectors:function(t,e){var i=t.x,n=t.y,r=t.z,a=e.x,o=e.y,s=e.z;return this.x=n*s-r*o,this.y=r*a-i*s,this.z=i*o-n*a,this},projectOnVector:function(t){var e=t.dot(this)/t.lengthSq();return this.copy(t).multiplyScalar(e)},projectOnPlane:function(){var t;return function(e){return void 0===t&&(t=new s),t.copy(this).projectOnVector(e),this.sub(t)}}(),reflect:function(){var t;return function(e){return void 0===t&&(t=new s),this.sub(t.copy(e).multiplyScalar(2*this.dot(e)))}}(),angleTo:function(e){var i=this.dot(e)/Math.sqrt(this.lengthSq()*e.lengthSq());return Math.acos(t.Math.clamp(i,-1,1))},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)},setFromSpherical:function(t){var e=Math.sin(t.phi)*t.radius;return this.x=e*Math.sin(t.theta),this.y=Math.cos(t.phi)*t.radius,this.z=e*Math.cos(t.theta),this},setFromMatrixPosition:function(t){return this.setFromMatrixColumn(t,3)},setFromMatrixScale:function(t){var e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=n,this},setFromMatrixColumn:function(t,e){if("number"==typeof t){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var i=t;t=e,e=i}return this.fromArray(t.elements,4*e)},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this.z=t.array[e+2],this}},c.prototype={constructor:c,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y},getParameter:function(t,e){var n=e||new i;return n.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)},clampPoint:function(t,e){var n=e||new i;return n.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new i;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},u.prototype=Object.create(n.prototype),u.prototype.constructor=u,Object.defineProperty(u.prototype,"images",{get:function(){return this.image},set:function(t){this.image=t}}),t.WebGLUniforms=function(){var t=new n,e=new u,i=function(){this.seq=[],this.map={}},r=[],a=[],o=function(t,e,i){var n=t[0];if(n<=0||n>0)return t;var a=e*i,o=r[a];if(void 0===o&&(o=new Float32Array(a),r[a]=o),0!==e){n.toArray(o,0);for(var s=1,h=0;s!==e;++s)h+=i,t[s].toArray(o,h)}return o},s=function(t,e){var i=a[e];void 0===i&&(i=new Int32Array(e),a[e]=i);for(var n=0;n!==e;++n)i[n]=t.allocTextureUnit();return i},h=function(t,e){t.uniform1f(this.addr,e)},c=function(t,e){t.uniform1i(this.addr,e)},l=function(t,e){void 0===e.x?t.uniform2fv(this.addr,e):t.uniform2f(this.addr,e.x,e.y)},p=function(t,e){void 0!==e.x?t.uniform3f(this.addr,e.x,e.y,e.z):void 0!==e.r?t.uniform3f(this.addr,e.r,e.g,e.b):t.uniform3fv(this.addr,e)},d=function(t,e){void 0===e.x?t.uniform4fv(this.addr,e):t.uniform4f(this.addr,e.x,e.y,e.z,e.w)},f=function(t,e){t.uniformMatrix2fv(this.addr,!1,e.elements||e)},m=function(t,e){t.uniformMatrix3fv(this.addr,!1,e.elements||e)},g=function(t,e){t.uniformMatrix4fv(this.addr,!1,e.elements||e)},v=function(e,i,n){var r=n.allocTextureUnit();e.uniform1i(this.addr,r),n.setTexture2D(i||t,r)},y=function(t,i,n){var r=n.allocTextureUnit();t.uniform1i(this.addr,r),n.setTextureCube(i||e,r)},x=function(t,e){t.uniform2iv(this.addr,e)},b=function(t,e){t.uniform3iv(this.addr,e)},_=function(t,e){t.uniform4iv(this.addr,e)},w=function(t){switch(t){case 5126:return h;case 35664:return l;case 35665:return p;case 35666:return d;case 35674:return f;case 35675:return m;case 35676:return g;case 35678:return v;case 35680:return y;case 5124:case 35670:return c;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},M=function(t,e){t.uniform1fv(this.addr,e)},E=function(t,e){t.uniform1iv(this.addr,e)},T=function(t,e){t.uniform2fv(this.addr,o(e,this.size,2))},S=function(t,e){t.uniform3fv(this.addr,o(e,this.size,3))},A=function(t,e){t.uniform4fv(this.addr,o(e,this.size,4))},L=function(t,e){t.uniformMatrix2fv(this.addr,!1,o(e,this.size,4))},R=function(t,e){t.uniformMatrix3fv(this.addr,!1,o(e,this.size,9))},P=function(t,e){t.uniformMatrix4fv(this.addr,!1,o(e,this.size,16))},C=function(e,i,n){var r=i.length,a=s(n,r);e.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTexture2D(i[o]||t,a[o])},U=function(t,i,n){var r=i.length,a=s(n,r);t.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTextureCube(i[o]||e,a[o])},I=function(t){switch(t){case 5126:return M;case 35664:return T;case 35665:return S;case 35666:return A;case 35674:return L;case 35675:return R;case 35676:return P;case 35678:return C;case 35680:return U;case 5124:case 35670:return E;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},D=function(t,e,i){this.id=t,this.addr=i,this.setValue=w(e.type)},N=function(t,e,i){this.id=t,this.addr=i,this.size=e.size,this.setValue=I(e.type)},O=function(t){this.id=t,i.call(this)};O.prototype.setValue=function(t,e){for(var i=this.seq,n=0,r=i.length;n!==r;++n){var a=i[n];a.setValue(t,e[a.id])}};var F=/([\w\d_]+)(\])?(\[|\.)?/g,B=function(t,e){t.seq.push(e),t.map[e.id]=e},z=function(t,e,i){var n=t.name,r=n.length;for(F.lastIndex=0;;){var a=F.exec(n),o=F.lastIndex,s=a[1],h="]"===a[2],c=a[3];if(h&&(s=0|s),void 0===c||"["===c&&o+2===r){B(i,void 0===c?new D(s,t,e):new N(s,t,e));break}var l=i.map,u=l[s];void 0===u&&(u=new O(s),B(i,u)),i=u}},G=function(t,e,n){i.call(this),this.renderer=n;for(var r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),a=0;a!==r;++a){var o=t.getActiveUniform(e,a),s=o.name,h=t.getUniformLocation(e,s);z(o,h,this)}};return G.prototype.setValue=function(t,e,i){var n=this.map[e];void 0!==n&&n.setValue(t,i,this.renderer)},G.prototype.set=function(t,e,i){var n=this.map[i];void 0!==n&&n.setValue(t,e[i],this.renderer)},G.prototype.setOptional=function(t,e,i){var n=e[i];void 0!==n&&this.setValue(t,i,n)},G.upload=function(t,e,i,n){for(var r=0,a=e.length;r!==a;++r){var o=e[r],s=i[o.id];s.needsUpdate!==!1&&o.setValue(t,s.value,n)}},G.seqWithValue=function(t,e){for(var i=[],n=0,r=t.length;n!==r;++n){var a=t[n];a.id in e&&i.push(a)}return i},G.splitDynamic=function(t,e){for(var i=null,n=t.length,r=0,a=0;a!==n;++a){var o=t[a],s=e[o.id];s&&s.dynamic===!0?(null===i&&(i=[]),i.push(o)):(ry&&v>x?vx?y0&&(n.alphaTest=this.alphaTest),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=this.premultipliedAlpha),this.wireframe===!0&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),i){var r=e(t.textures),a=e(t.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n},clone:function(){return(new this.constructor).copy(this)},copy:function(t){this.name=t.name,this.fog=t.fog,this.lights=t.lights,this.blending=t.blending,this.side=t.side,this.shading=t.shading,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.alphaTest=t.alphaTest,this.premultipliedAlpha=t.premultipliedAlpha,this.overdraw=t.overdraw,this.visible=t.visible,this.clipShadows=t.clipShadows;var e=t.clippingPlanes,i=null;if(null!==e){var n=e.length;i=new Array(n);for(var r=0;r!==n;++r)i[r]=e[r].clone()}return this.clippingPlanes=i,this},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}},Object.assign(x.prototype,e.prototype);var wa=0;t.UniformsUtils={merge:function(t){for(var e={},i=0;i>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this},setRGB:function(t,e,i){return this.r=t,this.g=e,this.b=i,this},setHSL:function(){function e(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+6*(e-t)*(2/3-i):t}return function(i,n,r){if(i=t.Math.euclideanModulo(i,1),n=t.Math.clamp(n,0,1),r=t.Math.clamp(r,0,1),0===n)this.r=this.g=this.b=r;else{var a=r<=.5?r*(1+n):r+n-r*n,o=2*r-a;this.r=e(o,a,i+1/3),this.g=e(o,a,i),this.b=e(o,a,i-1/3)}return this}}(),setStyle:function(e){function i(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}var n;if(n=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(e)){var r,a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(r=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(255,parseInt(r[1],10))/255,this.g=Math.min(255,parseInt(r[2],10))/255,this.b=Math.min(255,parseInt(r[3],10))/255,i(r[5]),this;if(r=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(100,parseInt(r[1],10))/100,this.g=Math.min(100,parseInt(r[2],10))/100,this.b=Math.min(100,parseInt(r[3],10))/100,i(r[5]),this;break;case"hsl":case"hsla":if(r=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o)){var s=parseFloat(r[1])/360,h=parseInt(r[2],10)/100,c=parseInt(r[3],10)/100;return i(r[5]),this.setHSL(s,h,c)}}}else if(n=/^\#([A-Fa-f0-9]+)$/.exec(e)){var l=n[1],u=l.length;if(3===u)return this.r=parseInt(l.charAt(0)+l.charAt(0),16)/255,this.g=parseInt(l.charAt(1)+l.charAt(1),16)/255,this.b=parseInt(l.charAt(2)+l.charAt(2),16)/255,this;if(6===u)return this.r=parseInt(l.charAt(0)+l.charAt(1),16)/255,this.g=parseInt(l.charAt(2)+l.charAt(3),16)/255,this.b=parseInt(l.charAt(4)+l.charAt(5),16)/255,this}if(e&&e.length>0){var l=t.ColorKeywords[e];void 0!==l?this.setHex(l):console.warn("THREE.Color: Unknown color "+e)}return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},copyGammaToLinear:function(t,e){return void 0===e&&(e=2),this.r=Math.pow(t.r,e),this.g=Math.pow(t.g,e),this.b=Math.pow(t.b,e),this},copyLinearToGamma:function(t,e){void 0===e&&(e=2);var i=e>0?1/e:1;return this.r=Math.pow(t.r,i),this.g=Math.pow(t.g,i),this.b=Math.pow(t.b,i),this},convertGammaToLinear:function(){var t=this.r,e=this.g,i=this.b;return this.r=t*t,this.g=e*e,this.b=i*i,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(t){var e,i,n=t||{h:0,s:0,l:0},r=this.r,a=this.g,o=this.b,s=Math.max(r,a,o),h=Math.min(r,a,o),c=(h+s)/2;if(h===s)e=0,i=0;else{var l=s-h;switch(i=c<=.5?l/(s+h):l/(2-s-h),s){case r:e=(a-o)/l+(ar&&(r=c),l>a&&(a=l),u>o&&(o=u)}this.min.set(e,i,n),this.max.set(r,a,o)},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z},getParameter:function(t,e){var i=e||new s;return i.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)},intersectsSphere:function(){var t;return function(e){return void 0===t&&(t=new s),this.clampPoint(e.center,t),t.distanceToSquared(e.center)<=e.radius*e.radius}}(),intersectsPlane:function(t){var e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=t.constant&&i>=t.constant},clampPoint:function(t,e){var i=e||new s;return i.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new s;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),getBoundingSphere:function(){var t=new s;return function(e){var i=e||new T;return i.center=this.center(),i.radius=.5*this.size(t).length(),i}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},applyMatrix4:function(){var t=[new s,new s,new s,new s,new s,new s,new s,new s];return function(e){return this.isEmpty()?this:(t[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),t[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),t[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),t[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),t[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),t[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),t[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),t[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(t),this)}}(),translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},T.prototype={constructor:T,set:function(t,e){return this.center.copy(t),this.radius=e,this},setFromPoints:function(){var t=new E;return function(e,i){var n=this.center;void 0!==i?n.copy(i):t.setFromPoints(e).center(n);for(var r=0,a=0,o=e.length;athis.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n},getBoundingBox:function(t){var e=t||new E;return e.set(this.center,this.center),e.expandByScalar(this.radius),e},applyMatrix4:function(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this},translate:function(t){return this.center.add(t),this},equals:function(t){return t.center.equals(this.center)&&t.radius===this.radius}},S.prototype={constructor:S,set:function(t,e,i,n,r,a,o,s,h){var c=this.elements;return c[0]=t,c[1]=n,c[2]=o,c[3]=e,c[4]=r,c[5]=s,c[6]=i,c[7]=a,c[8]=h,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(t){var e=t.elements;return this.set(e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]),this},setFromMatrix4:function(t){var e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r1))return n.copy(r).multiplyScalar(o).add(e.start)}else if(0===this.distanceToPoint(e.start))return n.copy(e.start)}}(),intersectsLine:function(t){var e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0},intersectsBox:function(t){return t.intersectsPlane(this)},intersectsSphere:function(t){return t.intersectsPlane(this)},coplanarPoint:function(t){var e=t||new s;return e.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var t=new s,e=new S;return function(i,n){var r=this.coplanarPoint(t).applyMatrix4(i),a=n||e.getNormalMatrix(i),o=this.normal.applyMatrix3(a).normalize();return this.constant=-r.dot(o),this}}(),translate:function(t){return this.constant=this.constant-t.dot(this.normal),this},equals:function(t){return t.normal.equals(this.normal)&&t.constant===this.constant}},L.prototype={constructor:L,set:function(t,e,i,n,r,a){var o=this.planes;return o[0].copy(t),o[1].copy(e),o[2].copy(i),o[3].copy(n),o[4].copy(r),o[5].copy(a),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){for(var e=this.planes,i=0;i<6;i++)e[i].copy(t.planes[i]);return this},setFromMatrix:function(t){var e=this.planes,i=t.elements,n=i[0],r=i[1],a=i[2],o=i[3],s=i[4],h=i[5],c=i[6],l=i[7],u=i[8],p=i[9],d=i[10],f=i[11],m=i[12],g=i[13],v=i[14],y=i[15];return e[0].setComponents(o-n,l-s,f-u,y-m).normalize(),e[1].setComponents(o+n,l+s,f+u,y+m).normalize(),e[2].setComponents(o+r,l+h,f+p,y+g).normalize(),e[3].setComponents(o-r,l-h,f-p,y-g).normalize(),e[4].setComponents(o-a,l-c,f-d,y-v).normalize(),e[5].setComponents(o+a,l+c,f+d,y+v).normalize(),this},intersectsObject:function(){var t=new T;return function(e){var i=e.geometry;return null===i.boundingSphere&&i.computeBoundingSphere(),t.copy(i.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSprite:function(){var t=new T;return function(e){return t.center.set(0,0,0),t.radius=.7071067811865476,t.applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSphere:function(t){for(var e=this.planes,i=t.center,n=-t.radius,r=0;r<6;r++){var a=e[r].distanceToPoint(i);if(a0?i.min.x:i.max.x,e.x=a.normal.x>0?i.max.x:i.min.x,t.y=a.normal.y>0?i.min.y:i.max.y,e.y=a.normal.y>0?i.max.y:i.min.y,t.z=a.normal.z>0?i.min.z:i.max.z,e.z=a.normal.z>0?i.max.z:i.min.z;var o=a.distanceToPoint(t),s=a.distanceToPoint(e);if(o<0&&s<0)return!1}return!0}}(),containsPoint:function(t){for(var e=this.planes,i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}},t.WebGLShader=function(){function t(t){for(var e=t.split("\n"),i=0;i");return l(i)}var i=/#include +<([\w\d.]+)>/g;return t.replace(i,e)}function u(t){function e(t,e,i,n){for(var r="",a=parseInt(e);a0?e.gammaFactor:1,L=a(v,m,e.extensions),R=o(y),P=g.createProgram();f&&f.isRawShaderMaterial?(T=[R].filter(h).join("\n"),S=[R].filter(h).join("\n")):(T=["precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+A,"#define MAX_BONES "+m.maxBones,m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+M:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.displacementMap&&m.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.skinning?"#define USE_SKINNING":"",m.useVertexTexture?"#define BONE_TEXTURE":"",m.morphTargets?"#define USE_MORPHTARGETS":"",m.morphNormals&&m.flatShading===!1?"#define USE_MORPHNORMALS":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+_:"",m.sizeAttenuation?"#define USE_SIZEATTENUATION":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(h).join("\n"), S=[L,"precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.alphaTest?"#define ALPHATEST "+m.alphaTest:"","#define GAMMA_FACTOR "+A,m.useFog&&m.fog?"#define USE_FOG":"",m.useFog&&m.fogExp?"#define FOG_EXP2":"",m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+w:"",m.envMap?"#define "+M:"",m.envMap?"#define "+E:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+_:"",m.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",m.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",m.envMap&&e.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",m.toneMapping!==rr?"#define TONE_MAPPING":"",m.toneMapping!==rr?ws.tonemapping_pars_fragment:"",m.toneMapping!==rr?r("toneMapping",m.toneMapping):"",m.outputEncoding||m.mapEncoding||m.envMapEncoding||m.emissiveMapEncoding?ws.encodings_pars_fragment:"",m.mapEncoding?i("mapTexelToLinear",m.mapEncoding):"",m.envMapEncoding?i("envMapTexelToLinear",m.envMapEncoding):"",m.emissiveMapEncoding?i("emissiveMapTexelToLinear",m.emissiveMapEncoding):"",m.outputEncoding?n("linearToOutputTexel",m.outputEncoding):"",m.depthPacking?"#define DEPTH_PACKING "+f.depthPacking:"","\n"].filter(h).join("\n")),x=l(x,m),x=c(x,m),b=l(b,m),b=c(b,m),(f&&f.isShaderMaterial)===!1&&(x=u(x),b=u(b));var C=T+x,U=S+b,I=t.WebGLShader(g,g.VERTEX_SHADER,C),D=t.WebGLShader(g,g.FRAGMENT_SHADER,U);g.attachShader(P,I),g.attachShader(P,D),void 0!==f.index0AttributeName?g.bindAttribLocation(P,0,f.index0AttributeName):m.morphTargets===!0&&g.bindAttribLocation(P,0,"position"),g.linkProgram(P);var N=g.getProgramInfoLog(P),O=g.getShaderInfoLog(I),F=g.getShaderInfoLog(D),B=!0,z=!0;g.getProgramParameter(P,g.LINK_STATUS)===!1?(B=!1,console.error("THREE.WebGLProgram: shader error: ",g.getError(),"gl.VALIDATE_STATUS",g.getProgramParameter(P,g.VALIDATE_STATUS),"gl.getProgramInfoLog",N,O,F)):""!==N?console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",N):""!==O&&""!==F||(z=!1),z&&(this.diagnostics={runnable:B,material:f,programLog:N,vertexShader:{log:O,prefix:T},fragmentShader:{log:F,prefix:S}}),g.deleteShader(I),g.deleteShader(D);var G;this.getUniforms=function(){return void 0===G&&(G=new t.WebGLUniforms(g,P,e)),G};var H;return this.getAttributes=function(){return void 0===H&&(H=s(g,P)),H},this.destroy=function(){g.deleteProgram(P),this.program=void 0},Object.defineProperties(this,{uniforms:{get:function(){return console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms()."),this.getUniforms()}},attributes:{get:function(){return console.warn("THREE.WebGLProgram: .attributes is now .getAttributes()."),this.getAttributes()}}}),this.id=p++,this.code=d,this.usedTimes=1,this.program=P,this.vertexShader=I,this.fragmentShader=D,this}}(),U.prototype={constructor:U,get count(){return this.array.length/this.itemSize},set needsUpdate(t){t===!0&&this.version++},setDynamic:function(t){return this.dynamic=t,this},copy:function(t){return this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.dynamic=t.dynamic,this},copyAt:function(t,e,i){t*=this.itemSize,i*=e.itemSize;for(var n=0,r=this.itemSize;n1){for(var e=0;e1)for(var e=0;e0){r.children=[];for(var a=0;a0&&(n.geometries=o),s.length>0&&(n.materials=s),h.length>0&&(n.textures=h),c.length>0&&(n.images=c)}return n.object=r,n},clone:function(t){return(new this.constructor).copy(this,t)},copy:function(t,e){if(void 0===e&&(e=!0),this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(var i=0;i0)for(var m=0;m0&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var t,e,i,n,r;for(i=0,n=this.faces.length;i0&&(t+=e[i].distanceTo(e[i-1])),this.lineDistances[i]=t},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E),this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new T),this.boundingSphere.setFromPoints(this.vertices)},merge:function(t,e,i){if((t&&t.isGeometry)===!1)return void console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",t);var n,r=this.vertices.length,a=this.vertices,o=t.vertices,s=this.faces,h=t.faces,c=this.faceVertexUvs[0],l=t.faceVertexUvs[0];void 0===i&&(i=0),void 0!==e&&(n=(new S).getNormalMatrix(e));for(var u=0,p=o.length;u=0;i--){var g=d[i];for(this.faces.splice(g,1),o=0,s=this.faceVertexUvs.length;o0,w=v.vertexNormals.length>0,M=1!==v.color.r||1!==v.color.g||1!==v.color.b,E=v.vertexColors.length>0,T=0;if(T=t(T,0,0),T=t(T,1,y),T=t(T,2,x),T=t(T,3,b),T=t(T,4,_),T=t(T,5,w),T=t(T,6,M),T=t(T,7,E),l.push(T),l.push(v.a,v.b,v.c),l.push(v.materialIndex),b){var S=this.faceVertexUvs[0][h];l.push(n(S[0]),n(S[1]),n(S[2]))}if(_&&l.push(e(v.normal)),w){var A=v.vertexNormals;l.push(e(A[0]),e(A[1]),e(A[2]))}if(M&&l.push(i(v.color)),E){var L=v.vertexColors;l.push(i(L[0]),i(L[1]),i(L[2]))}}return r.data={},r.data.vertices=s,r.data.normals=u,d.length>0&&(r.data.colors=d),m.length>0&&(r.data.uvs=[m]),r.data.faces=l,r},clone:function(){return(new q).copy(this)},copy:function(t){this.vertices=[],this.faces=[],this.faceVertexUvs=[[]];for(var e=t.vertices,i=0,n=e.length;i0,s=a[1]&&a[1].length>0,h=t.morphTargets,c=h.length;if(c>0){e=[];for(var l=0;l0){u=[];for(var l=0;l0){var i=new Float32Array(3*t.normals.length);this.addAttribute("normal",new U(i,3).copyVector3sArray(t.normals))}if(t.colors.length>0){var n=new Float32Array(3*t.colors.length);this.addAttribute("color",new U(n,3).copyColorsArray(t.colors))}if(t.uvs.length>0){var r=new Float32Array(2*t.uvs.length);this.addAttribute("uv",new U(r,2).copyVector2sArray(t.uvs))}if(t.uvs2.length>0){var a=new Float32Array(2*t.uvs2.length);this.addAttribute("uv2",new U(a,2).copyVector2sArray(t.uvs2))}if(t.indices.length>0){var o=t.vertices.length>65535?Uint32Array:Uint16Array,s=new o(3*t.indices.length);this.setIndex(new U(s,1).copyIndicesArray(t.indices))}this.groups=t.groups;for(var h in t.morphTargets){for(var c=[],l=t.morphTargets[h],u=0,p=l.length;u0){var m=new G(4*t.skinIndices.length,4);this.addAttribute("skinIndex",m.copyVector4sArray(t.skinIndices))}if(t.skinWeights.length>0){var g=new G(4*t.skinWeights.length,4);this.addAttribute("skinWeight",g.copyVector4sArray(t.skinWeights))}return null!==t.boundingSphere&&(this.boundingSphere=t.boundingSphere.clone()),null!==t.boundingBox&&(this.boundingBox=t.boundingBox.clone()),this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E);var t=this.attributes.position.array;void 0!==t?this.boundingBox.setFromArray(t):this.boundingBox.makeEmpty(),(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var t=new E,e=new s;return function(){null===this.boundingSphere&&(this.boundingSphere=new T);var i=this.attributes.position;if(i){var n=i.array,r=this.boundingSphere.center;t.setFromArray(n),t.center(r);for(var a=0,o=0,s=n.length;o0&&(t.data.groups=JSON.parse(JSON.stringify(s)));var h=this.boundingSphere;return null!==h&&(t.data.boundingSphere={center:h.center.toArray(),radius:h.radius}),t},clone:function(){return(new Q).copy(this)},copy:function(t){var e=t.index;null!==e&&this.setIndex(e.clone());var i=t.attributes;for(var n in i){var r=i[n];this.addAttribute(n,r.clone())}for(var a=t.groups,o=0,s=a.length;o0)if(s=p*f-d,h=p*d-f,l=u*g,s>=0)if(h>=-l)if(h<=l){var v=1/g;s*=v,h*=v,c=s*(s+p*h+2*d)+h*(p*s+h+2*f)+m}else h=u,s=Math.max(0,-(p*h+d)),c=-s*s+h*(h+2*f)+m;else h=-u,s=Math.max(0,-(p*h+d)),c=-s*s+h*(h+2*f)+m;else h<=-l?(s=Math.max(0,-(-p*u+d)),h=s>0?-u:Math.min(Math.max(-u,-f),u),c=-s*s+h*(h+2*f)+m):h<=l?(s=0,h=Math.min(Math.max(-u,-f),u),c=h*(h+2*f)+m):(s=Math.max(0,-(p*u+d)),h=s>0?u:Math.min(Math.max(-u,-f),u),c=-s*s+h*(h+2*f)+m);else h=p>0?-u:u,s=Math.max(0,-(p*h+d)),c=-s*s+h*(h+2*f)+m;return a&&a.copy(this.direction).multiplyScalar(s).add(this.origin),o&&o.copy(e).multiplyScalar(h).add(t),c}}(),intersectSphere:function(){var t=new s;return function(e,i){t.subVectors(e.center,this.origin);var n=t.dot(this.direction),r=t.dot(t)-n*n,a=e.radius*e.radius;if(r>a)return null;var o=Math.sqrt(a-r),s=n-o,h=n+o;return s<0&&h<0?null:s<0?this.at(h,i):this.at(s,i)}}(),intersectsSphere:function(t){return this.distanceToPoint(t.center)<=t.radius},distanceToPlane:function(t){var e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;var i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null},intersectPlane:function(t,e){var i=this.distanceToPlane(t);return null===i?null:this.at(i,e)},intersectsPlane:function(t){var e=t.distanceToPoint(this.origin);if(0===e)return!0;var i=t.normal.dot(this.direction);return i*e<0},intersectBox:function(t,e){var i,n,r,a,o,s,h=1/this.direction.x,c=1/this.direction.y,l=1/this.direction.z,u=this.origin;return h>=0?(i=(t.min.x-u.x)*h,n=(t.max.x-u.x)*h):(i=(t.max.x-u.x)*h,n=(t.min.x-u.x)*h),c>=0?(r=(t.min.y-u.y)*c,a=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,a=(t.min.y-u.y)*c),i>a||r>n?null:((r>i||i!==i)&&(i=r),(a=0?(o=(t.min.z-u.z)*l,s=(t.max.z-u.z)*l):(o=(t.max.z-u.z)*l,s=(t.min.z-u.z)*l),i>s||o>n?null:((o>i||i!==i)&&(i=o),(s=0?i:n,e)))},intersectsBox:function(){var t=new s;return function(e){return null!==this.intersectBox(e,t)}}(),intersectTriangle:function(){var t=new s,e=new s,i=new s,n=new s;return function(r,a,o,s,h){e.subVectors(a,r),i.subVectors(o,r),n.crossVectors(e,i);var c,l=this.direction.dot(n);if(l>0){if(s)return null;c=1}else{if(!(l<0))return null;c=-1,l=-l}t.subVectors(this.origin,r);var u=c*this.direction.dot(i.crossVectors(t,i));if(u<0)return null;var p=c*this.direction.dot(e.cross(t));if(p<0)return null;if(u+p>l)return null;var d=-c*t.dot(n);return d<0?null:this.at(d/l,h)}}(),applyMatrix4:function(t){return this.direction.add(this.origin).applyMatrix4(t),this.origin.applyMatrix4(t),this.direction.sub(this.origin),this.direction.normalize(),this},equals:function(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}},ct.prototype={constructor:ct,set:function(t,e){return this.start.copy(t),this.end.copy(e),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.start.copy(t.start),this.end.copy(t.end),this},center:function(t){var e=t||new s;return e.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(t){var e=t||new s;return e.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(t,e){var i=e||new s;return this.delta(i).multiplyScalar(t).add(this.start)},closestPointToPointParameter:function(){var e=new s,i=new s;return function(n,r){e.subVectors(n,this.start),i.subVectors(this.end,this.start);var a=i.dot(i),o=i.dot(e),s=o/a;return r&&(s=t.Math.clamp(s,0,1)),s}}(),closestPointToPoint:function(t,e,i){var n=this.closestPointToPointParameter(t,e),r=i||new s;return this.delta(r).multiplyScalar(n).add(this.start)},applyMatrix4:function(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this},equals:function(t){return t.start.equals(this.start)&&t.end.equals(this.end)}},lt.normal=function(){var t=new s;return function(e,i,n,r){var a=r||new s;a.subVectors(n,i),t.subVectors(e,i),a.cross(t);var o=a.lengthSq();return o>0?a.multiplyScalar(1/Math.sqrt(o)):a.set(0,0,0)}}(),lt.barycoordFromPoint=function(){var t=new s,e=new s,i=new s;return function(n,r,a,o,h){t.subVectors(o,r),e.subVectors(a,r),i.subVectors(n,r);var c=t.dot(t),l=t.dot(e),u=t.dot(i),p=e.dot(e),d=e.dot(i),f=c*p-l*l,m=h||new s;if(0===f)return m.set(-2,-1,-1);var g=1/f,v=(p*u-l*d)*g,y=(c*d-l*u)*g;return m.set(1-v-y,y,v)}}(),lt.containsPoint=function(){var t=new s;return function(e,i,n,r){var a=lt.barycoordFromPoint(e,i,n,r,t);return a.x>=0&&a.y>=0&&a.x+a.y<=1}}(),lt.prototype={constructor:lt,set:function(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this},setFromPointsAndIndices:function(t,e,i,n){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[n]),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this},area:function(){var t=new s,e=new s;return function(){return t.subVectors(this.c,this.b),e.subVectors(this.a,this.b),.5*t.cross(e).length()}}(),midpoint:function(t){var e=t||new s;return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(t){return lt.normal(this.a,this.b,this.c,t)},plane:function(t){var e=t||new A;return e.setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(t,e){return lt.barycoordFromPoint(t,this.a,this.b,this.c,e)},containsPoint:function(t){return lt.containsPoint(t,this.a,this.b,this.c)},closestPointToPoint:function(){var t,e,i,n;return function(r,a){void 0===t&&(t=new A,e=[new ct,new ct,new ct],i=new s,n=new s);var o=a||new s,h=1/0;if(t.setFromCoplanarPoints(this.a,this.b,this.c),t.projectPoint(r,i),this.containsPoint(i)===!0)o.copy(i);else{e[0].set(this.a,this.b),e[1].set(this.b,this.c),e[2].set(this.c,this.a);for(var c=0;c0){this.morphTargetBase=-1,this.morphTargetInfluences=[],this.morphTargetDictionary={};for(var t=0,e=this.geometry.morphTargets.length;te.far?null:{distance:c,point:b.clone(),object:t}}function n(i,n,r,a,o,s,h,p){c.fromArray(a,3*s),l.fromArray(a,3*h),u.fromArray(a,3*p);var d=e(i,n,r,c,l,u,x);return d&&(o&&(m.fromArray(o,2*s),g.fromArray(o,2*h),v.fromArray(o,2*p),d.uv=t(x,c,l,u,m,g,v)),d.face=new k(s,h,p,lt.normal(c,l,u)),d.faceIndex=s),d}var r=new a,o=new ht,h=new T,c=new s,l=new s,u=new s,p=new s,d=new s,f=new s,m=new i,g=new i,v=new i,y=new s,x=new s,b=new s;return function(i,a){var s=this.geometry,y=this.material,b=this.matrixWorld;if(void 0!==y&&(null===s.boundingSphere&&s.computeBoundingSphere(),h.copy(s.boundingSphere),h.applyMatrix4(b),i.ray.intersectsSphere(h)!==!1&&(r.getInverse(b),o.copy(i.ray).applyMatrix4(r),null===s.boundingBox||o.intersectsBox(s.boundingBox)!==!1))){var _,w;if(s&&s.isBufferGeometry){var M,E,T,S=s.index,A=s.attributes,L=A.position.array;if(void 0!==A.uv&&(_=A.uv.array),null!==S)for(var R=S.array,P=0,C=R.length;P0&&(_=z);for(var G=0,H=B.length;Gr||i.push({distance:Math.sqrt(n),point:this.position,face:null,object:this})}}(),clone:function(){return new this.constructor(this.material).copy(this)}}),Et.prototype=Object.assign(Object.create(X.prototype),{constructor:Et,copy:function(t){X.prototype.copy.call(this,t,!1);for(var e=t.levels,i=0,n=e.length;i1){t.setFromMatrixPosition(i.matrixWorld),e.setFromMatrixPosition(this.matrixWorld);var r=t.distanceTo(e);n[0].object.visible=!0;for(var a=1,o=n.length;a=n[a].distance;a++)n[a-1].object.visible=!1,n[a].object.visible=!0;for(;ao)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}else for(var x=0,b=v.length/3-1;xo)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}else if(h&&h.isGeometry)for(var T=h.vertices,S=T.length,x=0;xo)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}}),Ct.prototype=Object.assign(Object.create(Pt.prototype),{constructor:Ct}),Ut.prototype=Object.create(x.prototype),Ut.prototype.constructor=Ut,Ut.prototype.copy=function(t){return x.prototype.copy.call(this,t),this.color.copy(t.color),this.map=t.map,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this},It.prototype=Object.assign(Object.create(X.prototype),{constructor:It,raycast:function(){var t=new a,e=new ht,i=new T;return function(n,r){function a(t,i){var a=e.distanceSqToPoint(t);if(an.far)return;r.push({distance:h,distanceToRay:Math.sqrt(a),point:s.clone(),index:i,face:null,object:o})}}var o=this,h=this.geometry,c=this.matrixWorld,l=n.params.Points.threshold;if(null===h.boundingSphere&&h.computeBoundingSphere(),i.copy(h.boundingSphere),i.applyMatrix4(c),n.ray.intersectsSphere(i)!==!1){t.getInverse(c),e.copy(n.ray).applyMatrix4(t);var u=l/((this.scale.x+this.scale.y+this.scale.z)/3),p=u*u,d=new s;if(h&&h.isBufferGeometry){var f=h.index,m=h.attributes,g=m.position.array;if(null!==f)for(var v=f.array,y=0,x=v.length;y 0 ) ? 1 : + x; + + }; + +} + +if ( Function.prototype.name === undefined ) { + + // Missing in IE9-11. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name + + Object.defineProperty( Function.prototype, 'name', { + + get: function () { + + return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; + + } + + } ); + +} + +if ( Object.assign === undefined ) { + + // Missing in IE. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + + ( function () { + + Object.assign = function ( target ) { + + 'use strict'; + + if ( target === undefined || target === null ) { + + throw new TypeError( 'Cannot convert undefined or null to object' ); + + } + + var output = Object( target ); + + for ( var index = 1; index < arguments.length; index ++ ) { + + var source = arguments[ index ]; + + if ( source !== undefined && source !== null ) { + + for ( var nextKey in source ) { + + if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { + + output[ nextKey ] = source[ nextKey ]; + + } + + } + + } + + } + + return output; + + }; + + } )(); + +}